[
  {
    "path": ".gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files for more about ignoring files.\n#\n# If you find yourself ignoring temporary files generated by your text editor\n# or operating system, you probably want to add a global ignore instead:\n#   git config --global core.excludesfile '~/.gitignore_global'\n\n# Ignore bundler config.\n/.bundle\n\n# Ignore the default SQLite database.\n/db/*.sqlite3\n/db/*.sqlite3-journal\n\n# Ignore all logfiles and tempfiles.\n/log/stress\n/stress-test-results.pdf\n/log/*.log\n/tmp\nconfig/database.yml\n.ruby-version\n"
  },
  {
    "path": "Gemfile",
    "content": "source 'https://rubygems.org'\n\nruby \"2.2.0\"\n\ngem 'rails'                     , '4.1.6'\ngem 'sass-rails'                , '~> 4.0.3'\ngem 'uglifier'                  , '>= 1.3.0'\ngem 'coffee-rails'              , '~> 4.0.0'\ngem 'jquery-rails'\ngem 'turbolinks'\ngem 'jbuilder'                  , '~> 2.0'\ngem 'pg'                        , '~> 0.17.1'\ngem 'delayed_job_active_record' , '~> 4.0.2'\ngem 'unicorn'                   , '~> 4.8.3'\ngem 'devise'                    , '~> 3.4.1'\ngem 'rest-client'               , '~> 1.7.2'\ngem 'oauth'                     , '~> 0.4.7'\ngem 'oauth2'                    , '~> 0.9.3'\ngem 'airbrake'                  , '~> 4.1.0'\ngem 'activeadmin'               , '1.0.0.pre', :github => 'activeadmin', :ref => '0becbef0'\ngem 'gibberish'                 , '~> 1.4.0'\ngem 'foreman'                   , '~> 0.75.0'\n\ngem 'rails_stdout_logging'      , :group => [:staging, :production]\ngem 'rails_12factor'            , :group => :production\n# gem 'newrelic_rpm'              , :group => :production\n\ngem 'spring'                    , :group => :development\ngem 'sqlite3'                   , :group => :development\ngem 'pry'                       , :group => :development\ngem 'pry-byebug'                , :group => :development\ngem 'ruby-prof'                 , :group => :stress\n\ngem 'sdoc'                      , '~> 0.4.0', :group => :doc\n"
  },
  {
    "path": "Procfile",
    "content": "web:            bundle exec unicorn -p $PORT -c ./config/unicorn.rb\nworker:         bundle exec rake jobs:work\n\n# Heroku dynos have thread limits. (1x = 256, 2x = 512, px =\n# 32767). For 1x and 2x dynos, we set MAX_USER_THREADS way below the\n# limit because IMAP also consumes some threads. For px dynos, we use\n# foreman to create multiple imap_client instances on a single box.\n#\n# See https://devcenter.heroku.com/articles/limits#processes-threads\n\nimap_client_1x: NUM_WORKER_THREADS=1 MAX_USER_THREADS=200 bundle exec rake imap:client\nimap_client_2x: NUM_WORKER_THREADS=2 MAX_USER_THREADS=500 bundle exec rake imap:client\nimap_client_px: bundle exec foreman s -f Procfile.imap-client-px\n"
  },
  {
    "path": "Procfile.development",
    "content": "web:         bundle exec unicorn -p $PORT -c ./config/unicorn.rb\nworker:      bundle exec rake jobs:work\nimap_client: bundle exec rake imap:client\n"
  },
  {
    "path": "Procfile.imap-client-px",
    "content": "north: DYNO=$DYNO-1 NUM_WORKER_THREADS=3 MAX_USER_THREADS=3750 bundle exec rake imap:client\nsouth: DYNO=$DYNO-2 NUM_WORKER_THREADS=3 MAX_USER_THREADS=3750 bundle exec rake imap:client\neast: DYNO=$DYNO-3 NUM_WORKER_THREADS=3 MAX_USER_THREADS=3750 bundle exec rake imap:client\nwest: DYNO=$DYNO-4 NUM_WORKER_THREADS=3 MAX_USER_THREADS=3750 bundle exec rake imap:client\n"
  },
  {
    "path": "Procfile.stress-test",
    "content": "imap_test_server: rake imap:test_server\nimap_client_1: rake imap:client STRESS_TEST_MODE=true ENABLE_PROFILER=$ENABLE_PROFILER\nimap_client_2: rake imap:client STRESS_TEST_MODE=true ENABLE_PROFILER=false\nimap_client_3: rake imap:client STRESS_TEST_MODE=true ENABLE_PROFILER=false\n"
  },
  {
    "path": "README.md",
    "content": "# SuperIMAP - Version 0.1.2\n\nSuperIMAP helps you build email-driven applications. It takes care of\nconnecting to a customer's IMAP inbox, watching for new email, and\ntriggering a webhook to your application when a new email arrives,\ntypically within seconds.\n\nSuperIMAP is built for\nscale. [FiveStreet.com](https://www.fivestreet.com) built SuperIMAP as\nan alternative to Context.io. It contains a subset of Context.io Lite\nAPI functionality. As of July 2015, the FiveStreet team runs a\nSuperIMAP cluster processing ~400k emails per day for thousands of\nusers.\n\nSuperIMAP is written in Ruby and open sourced under the MIT license. [Why Ruby?](#why-ruby)\n\n[![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy?template=https://github.com/rustyio/super-imap)\n\n## Contents\n\n* [Installation](#installation)\n  * [Installing on Heroku](#installing-on-heroku)\n  * [Installing Elsewhere](#installing-elsewhere)\n* [Usage](#usage)\n  * [Set up a Partner](#set-up-a-partner)\n  * [Set up a Partner Connection](#set-up-a-partner-connection)\n  * [Add and Connect a User](#add-and-connect-a-user)\n  * [Add and Connect a User Programatically](#add-and-connect-a-user-programatically)\n  * [Disconnect a User Programatically](#disconnect-a-user-programatically)\n  * [Security](#security)\n* [Webhooks](#webhooks)\n  * [Webhook Security](#webhook-security)\n  * [New Mail Webhook](#new-mail-webhook)\n  * [User Connected Webhook](#user-connected-webhook)\n  * [User Disconnected Webhook](#user-disconnected-webhook)\n* [API](#api)\n  * [Manage Partner Connections](#apiv1connections)\n  * [Manage a Partner Connection](#apiv1connectionsimap_provider_code)\n  * [Manage Users](#apiv1connectionsimap_provider_codeusers)\n  * [Manage a User](#apiv1connectionsimap_provider_codeuserstag)\n* [Operations](#operations)\n  * [Process Types](#process-types)\n  * [Why Ruby?](#why-ruby)\n  * [Environment Variables](#environment-variables)\n  * [Scaling](#scaling)\n  * [Monitoring](#monitoring)\n  * [Performance](#performance)\n  * [Tracer Emails](#tracer-emails)\n* [Appendix](#appendix)\n  * [Understanding OAuth 2.0](#understanding-oauth-20)\n  * [Understanding IMAP](#understanding-imap)\n* [Development Tasks](#development-tasks)\n  * [Running Unit Tests](#running-unit-tests)\n  * [Running Stress Tests](#running-stress-tests)\n  * [Future Work](#future-work)\n  * [Contributions](#contributions)\n* [Changes](#changes)\n* [License](#license)\n\n## Screenshot\n\n![Screenshot](screenshot.png)\n\n## Installation\n\nSuperIMAP was built to run on Heroku, but can run in any environment that supports Rails.\n\n#### Installing on Heroku\n\n1. Provision a new Heroku project.\n2. Add an encrypted database.\n3. Set the `SECRET_KEY_BASE` and `ENCRYPTION_KEY` environment\n   variables to something really long and complicated.\n4. Add a Heroku remote endpoint, and push the code.\n5. Ramp up some workers.\n5. Seed the database with  `heroku run rake db:setup db:seed`\n\nThen, log in as the default user: `admin@example.com` / `password`.\n\n**Remember: Change the username and password immediately!**\n\nThe production Procfile assumes that you are installing on Heroku. As\na result it has multiple definitions for the `imap_client` process\ncorresponding to different sized Heroku dynos. In order for load\nbalancing to work correctly, you should have all `imap_client`\nprocesses use the same dyno size. Do not mix and match boxes.\n\n#### Installing Elsewhere\n\n1. Get the code: `git clone https://github.com/rustyio/super-imap.git`\n2. Update `config/database.yml`. (Use `config/database.yml.example`)\n3. Run `bundle` to install dependencies.\n4. Set the `SECRET_KEY_BASE` and `ENCRYPTION_KEY` environment\n   variables to something really long and complicated.\n5. Seed the database with `RAILS_ENV=production rake db:setup db:seed`\n6. Start the processes: `foreman start -c \"web=1, worker=1, imap_client_1x=1`\n\nThen, log in as the default user: `admin@example.com` / `password`.\n\n**Remember: Change the username and password immediately!**\n\nThe production Procfile assumes that you are installing on Heroku. As\na result it has multiple definitions for the `imap_client` process\ncorresponding to different sized Heroku dynos. In order for load\nbalancing to work correctly, you should ensure that all `imap_client`\nprocesses are the same size and point to the same database.\n\n## Usage\n\n#### Set up a Partner\n\nA single SuperIMAP instance can support multiple applications (and/or multiple environments for a single application.) This is done by creating a new \"Partner\" for every different application (and/or environment).\n\n1. Open the SuperIMAP dashboard.\n2. Click on the \"Partners\" tab. Click \"New Partner\".\n3. Set webhooks to notify your application of the following events:\n   * A new email has arrived.\n   * A user has connected their email account.\n   * A user has disconnected their email account.\n\n#### Set up a Partner Connection\n\n1. Still within the dashboard, click the \"Partners\" tab.\n2. Click on the \"Connections\" link next to your Partner.\n3. Click on \"New Partner Connection\".\n4. Choose an authentication type, and fill out any necessary credentials.\n\nFor Gmail, you will need to get OAuth 2.0 Client credentials here from the [Developer Console](https://console.developers.google.com/project).\n\n#### Add and Connect a User\n\n1. Still within the dashboard, click on \"Partners\".\n2. Click on the \"Connections\" link next to your partner.\n3. Click on the \"Users\" link next to your connection.\n4. Click on the \"New User\" button.\n5. Click the 'Connect' link to connect the user to an IMAP provider.\n6. Send yourself email, and watch the logs!\n\n#### Add and Connect a User Programatically\n\nThe next step is to update your application to handle the process of creating and connecting to SuperIMAP users. Here is some example code:\n\n```ruby\n    require 'rest-client'\n\n    url = \"https://my-app.com/api/v1/connections/GMAIL_OAUTH2/users\"\n    users = RestClient::Resource.new(url, :headers => {\n      :'x-api-key'  => \"$API_KEY$\",\n      :content_type => :json,\n      :accept       => :json\n    })\n\n    # Create the user.\n    users.post(:tag => \"MY_USER\")\n\n    # Get the connect url.\n    response = users[\"MY_USER\"].get\n    connect_url = JSON.parse(response)['connect_url']\n\n    # Set up the success and failure callbacks.\n    callbacks = {\n      :success => \"http://my-app.com/connect_callback?success=1\",\n      :failure => \"http://my-app.com/connect_callback?failure=1\"\n    }\n\n    # Redirect the user to the connect url.\n    redirect_to connect_url  + \"?\" + callbacks.to_query\n```\n\n#### Disconnect a User Programatically\n\nBelow is sample code to disconnect a user:\n\n```ruby\n    url = \"https://my-host.com/api/v1/connections/GMAIL_OAUTH2/users\"\n    users = RestClient::Resource.new(url, :headers => {\n      :'x-api-key'  => \"$API_KEY$\",\n      :content_type => :json,\n      :accept       => :json\n    })\n\n    # Later, if you want to disconnect the user.\n    response = users[\"MY_USER\"].get\n    disconnect_url = JSON.parse(response)['disconnect_url']\n\n    # Set up the success and failure callbacks.\n    callbacks = {\n      :success => \"http://my-app.com/disconnect_callback?success=1\"\n    }\n\n    # Redirect the user to the disconnect url.\n    redirect_to disconnect_url  + \"?\" + callbacks.to_query\n```\n\n#### Security\n\nThis is a good time to mention security. It is a big responsibility to\nhold the keys to someone's email. Treat it with the appropriate amount\nof caution.\n\nIf you use this code:\n\n* *PLEASE* ensure that you use very strong, safeguarded passwords.\n* *PLEASE* use enable 2-factor-authentication for your Heroku account.\n* *PLEASE* make sure your entire database is encrypted at rest.\n\nOther security measures within SuperIMAP:\n\n+ SSL is *required* in production.\n+ Secure fields (e.g. passwords and other credentials) are never exposed via the web interface, and are encrypted in the database.\n+ Passwords are not recoverable by email.\n+ Accounts are locked for an hour after three invalid password attempts.\n\n## Webhooks\n\nSuperIMAP sends new email events (and other events) to your\napplications through webhooks:\n\n+ All webhooks are dispatched through delayed jobs.\n+ Webhooks will be retried up to 6 times, with exponential backoff.\n+ Webhooks will fail if the receiving server takes more than 30 seconds to respond.\n+ Webhooks expect a success response (HTTP code 200 - 206).\n+ A \"Forbidden\" response code of 403 will automatically archive the user.\n+ Any other response codes count as an error, and will trigger a retry.\n\n#### Webhook Security\n\nAll webhooks are signed. You can validate the signature as follows:\n\n```ruby\n    # Parse the incoming JSON body.\n    json_params = JSON.parse(request.raw_post)\n\n    # Calculate expected signature.\n    digest    = OpenSSL::Digest.new('sha256')\n    api_key   = Rails.application.config.super_imap_api_key\n    sha1      = json_params['sha1']\n    timestamp = json_params['timestamp']\n    expected_signature = OpenSSL::HMAC.hexdigest(digest, api_key, \"#{timestamp}#{sha1}\")\n\n    # Get actual signature.\n    actual_signature = json_params['signature']\n\n    # Compare signatures.\n    valid = expected_signature == actual_signature\n```\n\n#### New Mail Webhook\n\nCalled when a new mail arrives in a user's inbox.\n\n+ `timestamp` - Timestamp the webhook was sent. Seconds since Jan 1, 1970.\n+ `sha1` - The SHA1 hash of the rfc822 parameter.\n+ `imap_provider_code` - The IMAP provider code (e.g. \"GMAIL_OAUTH2\")\n+ `user_tag` - The user's tag.\n+ `envelope - The email envelope, including date, subject, from, sender, reply_to, to, cc, bcc, in_reply_to, and message_id.\n+ `rfc822` - The raw body of the email. http://www.w3.org/Protocols/rfc822/\n\n#### User Connected Webhook\n\nCalled when a user has successfully authenticated with an IMAP\nprovider. Only applies to OAuth connections at the moment.\n\n+ `timestamp` - Timestamp the webhook was sent. Seconds since Jan 1, 1970.\n+ `sha1` - The SHA1 hash of the user's tag.\n+ `imap_provider_code` - The IMAP provider code (e.g. \"GMAIL_OAUTH2\")\n+ `user_tag` - The user's tag.\n+ `email` - The email address with which the user authenticated.\n\n#### User Disconnected Webhook\n\nCalled when a user has disconnected from an IMAP provider. Only\napplies to OAuth connections at the moment.\n\n+ `timestamp` - Timestamp the webhook was sent. Seconds since Jan 1, 1970.\n+ `sha1` - The SHA1 hash of the user's tag.\n+ `imap_provider_code` - The IMAP provider code (e.g. \"GMAIL_OAUTH2\")\n+ `user_tag` - The user's tag.\n\n## API\n\nAll API calls are scoped by partner. To authenticate, send the\nPartner's API key using a header or a parameter. (A header is\npreferred because it won't normally appear in HTTP logs.)\n\n```sh\n    # Access the API curl:\n    curl -H \"Accept: json\" \\\n         -H \"x-api-key:APIKEY\" \\\n         https://my-host.com/api/v1/connections\n```\n\n\n```ruby\n    # Access the API using the rest-client gem:\n    url = \"https://my-host.com/api/v1\"\n    resource = RestClient::Resource.new(url, :headers => {\n      :'x-api-key'  => \"$API_KEY$\",\n      :content_type => :json,\n      :accept       => :json\n    })\n    resource['connections'].get\n```\n___\n\n#### /api/v1/connections\n\n**GET**\n\nGet a list of connections for the specified partner.\n\n**POST**\n\nCreate a new connection.\n\n* `imap_provider_code` is required.\n* Other required parameters depend on the IMAP Provider used.\n\n___\n\n#### /api/v1/connections/:IMAP_PROVIDER_CODE\n\n**GET**\n\nGet information about a given connection.\n\n**PUT**\n\nUpdate settings for a given connection. The required parameters depend on the IMAP provider used.\n\n**DELETE**\n\nDelete a connection and all underlying user data.\n\n___\n\n#### /api/v1/connections/:IMAP_PROVIDER_CODE/users\n\n**GET**\n\nGet a list of users for the specified IMAP Provider.\n\n**POST**\n\nCreate a new user.\n\n* `tag` - Required, a unique tag within the scope of a partner\n  connection, selected by the partner application.\n* Other required parameters depend on the IMAP Provider used.\n\n___\n\n#### /api/v1/connections/:IMAP_PROVIDER_CODE/users/:TAG\n\n**GET**\n\nGet information about the given user, including:\n\n* `email` - The IMAP email address to which the user's account is connected.\n* `connected_at` - The date when the user's account was connected. Present only if connected.\n* `connect_url` - Redirect to this url to connect a user to a provider. For OAuth based IMAP providers, this begins the OAuth dance.\n* `disconnect_url` - Redirect to this url to disconnect a user from a provider.\n\n**PUT**\n\nUpdate a user. The required parameters depend on the IMAP provider used.\n\n**DELETE**\n\nArchive a user. The user can be restored in the web interface, or by\nupdating the user (ie: a PUT request.\n\n## Operations\n\n#### Process Types\n\nSuperIMAP consists of 3 different processes, all written in Ruby / Rails:\n\n+ `web` - Serves the admin interface and the API.\n+ `imap_client` - Handles the task of connecting to IMAP providers and listening for email.\n+ `worker` - Processes background jobs generated by the 'imap_client' process.\n\n#### Environment Variables\n\n+ `ENCRYPTION_KEY` - If provided, used to encrypt passwords and secret keys. Required in production.\n+ `MAX_USER_THREADS` - Change the maximum number of user threads. Default is 500.\n+ `NUM_WORKER_THREADS` - Change the number of worker threads. Default is 5.\n+ `MAX_EMAIL_SIZE` - Change the maximum email size. Default is 1 MiB (1,048,576 bytes).\n+ `TRACER_INTERVAL` - Interval, in seconds, between outgoing tracer emails. Default is 600 seconds (10 minutes).\n+ `NUM_TRACERS` - Number of tracers to send at the end of each tracer interval. Default is 3.\n\n#### Scaling\n\nTo scale SuperIMAP, you will mainly want to increase the number of IMAP\nClient processes. The IMAP Client processes automatically publish a\nheartbeat every 10 seconds. Other instances look for this heartbeat\nand re-calculate which neighboring processes are alive based on any\nprocesses that have published a heartbeat within the last 30 seconds.\n\nThe IMAP Client processes re-balance users every 10 seconds. If no new\ninstances have entered or left the pool, then re-balancing will have\nno effect.\n\nIf a new IMAP Client instance is started, then a small number of users\nwill be taken from each running instance and handed to the new\ninstance. If one of the IMAP Client instances is stopped it is removed\nfrom the pool, then it's users will be evenly distributed to the\nremaining instances (assuming they are still below the\n`MAX_USER_THREADS` threshold.)\n\nThere is no \"master\" process that decides which IMAP Client process\nshould handle a given user. SuperIMAP uses a\n[Rendezvous Hash](http://en.wikipedia.org/wiki/Rendezvous_hashing) to\nallow IMAP Client instances to agree on how to evenly assign users\nwithout any central coordination. The algorithm assumes that all\nSuperIMAP instances have roughly the same number of resources.\n\n#### Monitoring\n\nSuperIMAP publishes some useful monitoring information in the logs.\nThis includes:\n\n+ `imap_client.user_thread.count` - The size of the imap client work queue. Backups may indicate that your servers are overloaded.\n+ `imap_client.total_emails_processed` - The total number of emails processed since the instance was started.\n+ `imap_client.work_queue.length` - The number of user threads. This indicates how many users are connected on a given IMAP Client instance.\n+ `work_queue.latency` - The latency, in seconds, between when an item is added to the work queue and when it is processed.\n\nThese metrics are published in a format that can be consumed by the\nLibrato Add-On in Heroku. See\nhttps://devcenter.heroku.com/articles/librato#custom-log-based-metrics\nfor more information.\n\nApart from keeping an eye on these metrics, SuperIMAP should need no other regular metrics.\n\nYou may also want to keep an eye out for any failing Delayed Job tasks. You can view these from the Admin site.\n\n#### Tracer Emails\n\nSuperIMAP has the ability to give you useful monitoring information\nthrough \"tracer emails\". The system will send a specially formatted\nemail to an account, wait for the incoming email, and log the\nresults. The logs can be accessed through the \"Tracer Logs\" tab.\n\nTo enable Tracer Emails, navigate to a user and check the \"Enable\nTracer\" checkbox. It is recommended that you create a few dummy email\naddresses to use for tracer emails.\n\nBy default, a cluster of three tracers are sent every ten minutes from\neach `imap_client` instance to a random tracer-enabled user managed by\nthat instance.\n\nKeep in mind that this could generate a lot of email. Three emails\nevery ten minutes works out to ~430 emails per day.\n\n#### Performance\n\nSuperIMAP's architecture makes judicious use of system resources:\n\nAll connections to the IMAP server are managed by separate \"user\nthreads\", but these threads sit dormant most of the time. When\nanything interesting happens that requires real work, the operation is\nqueued and handled by a worker in a worker pool. The size of the\nworker pool is controlled by the `NUM_WORKER_THREADS` environment\nvariable. Only worker pools threads, and a small number of other\nsystem threads, require a database connection.\n\nIn terms of tradeoffs, this architecture chooses to slightly degrade\nan individual user's response time in favor of making sure that the\nsystem will not get overloaded when things get rough. When things get\nbusy, the work simply builds up in the queue. The size of the worker\nqueue, and the queue latency, becomes a rough measure of system\nhealth.\n\nTypically, a SuperIMAP box is resource-limited by the number of user\nprocesses that can be started. SuperIMAP requires 2 user processes for\neach user's IMAP connection. On Heroku, the number of user processes\nare limited at 256 for a 1X box, 512 for a 2X box, and 32,767 for a PX\nbox. You can set this at home using `ulimit -u`. Divide this in half\nto get the maximum number of users that the SuperIMAP process can\nmanage.\n\n[FiveStreet.com](https://www.fivestreet.com) uses SuperIMAP to manages\nthousands of users and process over 1M incoming emails per week (as of\nJanuary 2015). We currently run this load on a single Heroku PX dyno,\nwith plenty of headroom. Our SuperIMAP instance serving thousands of\nusers requires just 10 database connections, uses about 3GB of RAM,\nand has a 0.50 load average. The work queue usually sits near 0, with\na latency of < 0.5 seconds.\n\n#### Why Ruby?\n\nAt first glance, and from a purely technical point-of-view, Ruby is a\npoor choice for an application like SuperIMAP. SuperIMAP is highly\nconcurrent, and Ruby is bad at concurrency.\n\nSpecifically, the `imap_client` process spawns what could technically\nbe described as a \"boatload\" of threads (2 threads per connected user,\nplus a handful of other threads). Ruby threads are heavyweight, so the\ninterpreter has to burn significant resources just to create and\nschedule the threads before it can do any real work.\n\nUsing Erlang, Go, or Rust (all of which support lightweight threads\nand actor-style programming) would have made the concurrent bits of\nSuperIMAP less tricky to write, and would have required fewer\ncomputing resources, possibly allowing a single box to handle tens of\nthousands of active users.\n\nSo, why Ruby? A few reasons:\n\n+ **FiveStreet uses Ruby** - The primary goal of SuperIMAP is to power\n  a critical part of FiveStreet's application. FiveStreet.com is\n  written in Ruby. It is built and maintained by a small team of Ruby\n  engineers. Introducing a new language would force the team to spend\n  dozens of hours learning a new stack and maintaining a new\n  development environment.\n\n+ **Low barrier to entry** - A secondary goal of SuperIMAP is to become\n  a healthy open-source project. Based only on language popularity, it\n  is more likely that another team can use, troubleshoot, and contribute to\n  a Ruby-based SuperIMAP than an Erlang/Go/Rust-based SuperIMAP.\n\n+ **For us, the cost savings are small** - FiveStreet's SuperIMAP\n  cluster currently runs on three commodity servers and easily handles\n  thousands of users. It's possible that if SuperIMAP were written in\n  a different language, we could handle the load on a single machine,\n  saving us a few hundred dollars a month. Not worth changing our\n  stack for it.\n\n+ **The concurrency is not complicated** - The concurrency in SuperIMAP is\n  fairly straightforward -- one parent process, many child\n  processes. It's a little painful to solve the problem in Ruby, but\n  not impossible.\n\n+ **Ruby has mature IMAP and OAuth 2.0 libraries** - Ruby has a\n  [built-in IMAP library](http://ruby-doc.org/stdlib-2.0.0/libdoc/net/imap/rdoc/Net/IMAP.html),\n  and a\n  [widely-used OAuth 2.0 library](https://github.com/intridea/oauth2). As\n  of 2015, the IMAP and OAuth 2.0 libraries for other languages are\n  [far](https://github.com/alexcrichton/oauth2-rs)\n  [less](https://github.com/boorad/erlimap)\n  [mature](https://github.com/mxk/go-imap).\n\nSide Note: This was a deeply considered choice. I (Rusty Klophaus, the\nauthor of SuperIMAP) spent about 4 years writing Erlang\nprofessionally. It's a fascinating language.\n\n## Appendix\n\n#### Understanding OAuth 2.0\n\nSuperIMAP can authenticate to email providers using OAuth 2.0. OAuth\n2.0 can be difficult to understand. Here is how it works, in the\ncontext of a user authenticating to Gmail through SuperIMAP:\n\nOn your application:\n\n* John visits a \"Connect Your Email\" page on your website.\n* On the server side, your application uses the SuperIMAP API to fetch a special url called a `connect_url`. ([sample code](#add-and-connect-a-user-programatically))\n* John clicks a link and is redirected to the `connect_url`.\n\nOn your SuperIMAP instance:\n\n* The `connect_url` links to a SuperIMAP page.\n* The SuperIMAP page construct a special URL and redirects to Google.\n\nOn Google:\n\n* Google displays a page asking John to confirm certain permissions for your application.\n* John clicks the \"Approve\" button.\n* Google redirects John to SuperIMAP and includes a \"refresh token\" parameter.\n\nOn your SuperIMAP instance:\n\n* SuperIMAP grabs the \"refresh token\", and issues a server side request for an \"access token\".\n* SuperIMAP saves the \"access token\". This is what allows SuperIMAP to connect to Google on behalf of the user in the future.\n* SuperIMAP redirects the user back to the \"success\" page provided in step #2 above.\n\nOn your application:\n\n* Your application tells John that the connection was successful.\n\nTo get one step more complicated, OAuth is secured in a few different ways:\n\n+ Google requires your application to pre-register callback URLS for your app. Sending the user back to a non-registered URL will fail.\n+ The access token is tied to a client id and a client secret on our site. Someone needs all three to authenticate as the user.\n+ There is more too it, but that's the extent of my knowledge.\n\nIf you want more detail, here's a video tutorial: https://www.youtube.com/watch?v=tFYrq3d54Dc\n\nThe OAuth settings are configured through the Google Developer console: https://console.developers.google.com/\n\n#### Understanding IMAP\n\nOnce you are authenticated to an IMAP server, IMAP itself is a fairly\nstraightforward protocol. It consists of simple plain text commands\nand responses. The commands and responses are tagged, allowing\nmultiple commands to run in parallel.\n\nBelow is a sample IMAP session, taken directly from the [Internet Message Access Protocol RFC (3501)](https://tools.ietf.org/html/rfc3501#section-8):\n\n```\n    S:   * OK IMAP4rev1 Service Ready\n    C:   a001 login mrc secret\n    S:   a001 OK LOGIN completed\n    C:   a002 select inbox\n    S:   * 18 EXISTS\n    S:   * FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\n    S:   * 2 RECENT\n    S:   * OK [UNSEEN 17] Message 17 is the first unseen message\n    S:   * OK [UIDVALIDITY 3857529045] UIDs valid\n    S:   a002 OK [READ-WRITE] SELECT completed\n    C:   a003 fetch 12 full\n    S:   * 12 FETCH (FLAGS (\\Seen) INTERNALDATE \"17-Jul-1996 02:44:25 -0700\"\n         RFC822.SIZE 4286 ENVELOPE (\"Wed, 17 Jul 1996 02:23:25 -0700 (PDT)\"\n         \"IMAP4rev1 WG mtg summary and minutes\"\n         ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\"))\n         ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\"))\n         ((\"Terry Gray\" NIL \"gray\" \"cac.washington.edu\"))\n         ((NIL NIL \"imap\" \"cac.washington.edu\"))\n         ((NIL NIL \"minutes\" \"CNRI.Reston.VA.US\")\n          (\"John Klensin\" NIL \"KLENSIN\" \"MIT.EDU\")) NIL NIL\n          \"<B27397-0100000@cac.washington.edu>\")\n          BODY (\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" 3028 92))\n    S:    a003 OK FETCH completed\n    C:    a004 fetch 12 body[header]\n    S:    * 12 FETCH (BODY[HEADER] {342}\n    S:    Date: Wed, 17 Jul 1996 02:23:25 -0700 (PDT)\n    S:    From: Terry Gray <gray@cac.washington.edu>\n    S:    Subject: IMAP4rev1 WG mtg summary and minutes\n    S:    To: imap@cac.washington.edu\n    S:    cc: minutes@CNRI.Reston.VA.US, John Klensin <KLENSIN@MIT.EDU>\n    S:    Message-Id: <B27397-0100000@cac.washington.edu>\n    S:    MIME-Version: 1.0\n    S:    Content-Type: TEXT/PLAIN; CHARSET=US-ASCII\n    S:\n    S:    )\n    S:    a004 OK FETCH completed\n    C:    a005 store 12 +flags \\deleted\n    S:    * 12 FETCH (FLAGS (\\Seen \\Deleted))\n    S:    a005 OK +FLAGS completed\n    C:    a006 logout\n    S:    * BYE IMAP4rev1 server terminating connection\n    S:    a006 OK LOGOUT completed\n```\n\nSuperIMAP uses the IDLE command to wait for incoming email, defined in\nthe\n[IMAP4 Idle Command RFC (2177)](https://tools.ietf.org/html/rfc2177). The\nIMAP client sends an IDLE command to the server and awaits a\nresponse. When an IMAP connection is in IDLE mode, no other commands\nare allowed.\n\n## Development Tasks\n\nThe information below is mainly intended at developers who want to modify the SuperIMAP codebase.\n\n#### Running Unit Tests\n\nRun this once:\n\n    RAILS_ENV=test rake db:setup db:seed\n\nThen run all tests:\n\n    rake test:all\n\n#### Running Stress Tests\n\nThe stress test exercises the multi-threaded aspects of SuperIMAP, as\nwell as the error recovery code. To do this, we point the SuperIMAP IMAP\nclient code against a local IMAP server and generate a bunch of fake emails\nfor many users.\n\nAdditionally, the IMAP server generates 'chaotic' events; it will\nintentionally generate incorrect or gibberish responses. The SuperIMAP\nIMAP client code is expected to recover gracefully while using a\nminimal amount of system resources.\n\nRun this once:\n\n    RAILS_ENV=stress rake db:setup db:seed\n\nThen run the stress test:\n\n    script/stress-test\n\n#### Future Work\n\n* Configure stress test to report code coverage.\n* Make a way to \"sweep\" a user's inbox, generating webhook events for all emails.\n\n#### Contributions\n\nTo contribute to this project, please fork and file a pull\nrequest. Small patches will be accepted more quickly than large\npatches.\n\n## Changes\n\n#### Version 0.1.2\n\n* Re-organize and improve documentation in README.md.\n* Detect and handle race condition around changing UIDVALIDITY.\n* Properly escape OAuth 2.0 disconnect URL.\n* Improve usage of Rails connection pool.\n* Clean up heartbeat records during exit.\n* Synchronize access to shared objects.\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 Rusty Klophaus / FiveStreet.com\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": "Rakefile",
    "content": "# Add your own tasks in files placed in lib/tasks ending in .rake,\n# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.\n\nrequire File.expand_path('../config/application', __FILE__)\n\nRails.application.load_tasks\n"
  },
  {
    "path": "app/admin/admin_user.rb",
    "content": "ActiveAdmin.register AdminUser do\n  permit_params :email, :password, :password_confirmation\n  menu priority: 100\n  config.sort_order = \"email_asc\"\n  config.filters = false\n\n  index do\n    column :tag do |obj|\n      link_to obj.email, admin_admin_user_path(obj)\n    end\n    column :last_sign_in_at\n  end\n\n  show do |obj|\n    panel \"Details\" do\n      attributes_table_for obj do\n        row :id\n        row :email\n        row :sign_in_count\n        row :current_sign_in_at\n        row :current_sign_in_ip\n        row :last_sign_in_at\n        row :last_sign_in_ip\n        row :created_at\n      end\n    end\n  end\n\n  form do |f|\n    f.inputs \"Admin Details\" do\n      f.input :email\n      f.input :password\n      f.input :password_confirmation\n    end\n    f.actions\n  end\nend\n"
  },
  {
    "path": "app/admin/delayed_job.rb",
    "content": "ActiveAdmin.register DelayedJob do\n  menu priority: 90\n  config.sort_order = \"created_at_desc\"\n  config.batch_actions = true\n\n  # Only allow viewing and deleting.\n  actions :all, :except => [:new, :edit]\n\n  filter :handler\n  filter :last_error\n  filter :queue\n\n  index do\n    column \"Handler\" do |obj|\n      link_to obj.handler.slice(0, 250), admin_delayed_job_path(obj)\n    end\n    column :created_at\n    column :failed_at\n    column :attempts\n    column :queue\n  end\n\n  show do |obj|\n    panel \"Details\" do\n      attributes_table_for obj do\n        row :id\n        row :queue\n        row :created_at\n        row :failed_at if obj.attempts > 0\n        row :attempts if obj.attempts > 0\n        row :message do\n          link_to \"Download Message\", message_admin_delayed_job_path(obj, \"eml\")\n        end if /CallNewMailWebhook/.match(obj.handler)\n      end\n    end\n\n    panel \"Handler\" do\n      pre obj.handler\n    end\n\n    panel \"Last Error\" do\n      pre obj.last_error\n    end if obj.attempts > 0\n  end\n\n  member_action :message, :method => :get do\n    # HACK - Make sure the class is loaded.\n    CallNewMailWebhook\n\n    job = YAML.load(resource.handler)\n    if job.object.class == CallNewMailWebhook\n      render :text => job.object.raw_eml, :content_type => 'message/rfc822'\n    else\n      render :text => \"There was a problem.\"\n    end\n  end\nend\n"
  },
  {
    "path": "app/admin/imap_provider.rb",
    "content": "ActiveAdmin.register ImapProvider do\n  config.sort_order = \"code_asc\"\n  permit_params :code, :title,\n                :imap_host, :imap_port, :imap_use_ssl,\n                :smtp_host, :smtp_port, :smtp_domain, :smtp_enable_starttls_auto,\n                *Plain::ImapProvider.connection_fields,\n                *Oauth2::ImapProvider.connection_fields\n\n  config.filters = false\n\n  config.clear_action_items!\n  actions :all, :except => [:edit, :destroy]\n\n  index do\n    column \"Connection Type\" do |obj|\n      link_to \"#{obj.title} (#{obj.code})\", admin_imap_provider_path(obj)\n    end\n\n    column \"IMAP Server\" do |obj|\n       \"#{obj.imap_host}:#{obj.imap_port}\"\n    end\n\n    column \"SMTP Server\" do |obj|\n       \"#{obj.smtp_host}:#{obj.smtp_port}\"\n    end\n  end\n\n  show do |obj|\n    panel \"Details\" do\n      attributes_table_for obj do\n        row :code\n        row :title\n        row :type\n      end\n    end\n\n    panel \"IMAP Settings\" do\n      attributes_table_for obj do\n        row :imap_host\n        row :imap_port\n        row :imap_use_ssl\n      end\n    end\n\n    panel \"SMTP Settings\" do\n      attributes_table_for obj do\n        row :smtp_host\n        row :smtp_port\n        row :smtp_domain\n        row :smtp_enable_starttls_auto\n      end\n    end\n\n    panel \"Connection Settings\" do\n      attributes_table_for obj do\n        obj.connection_fields.map do |field|\n          row field\n        end\n      end\n    end if obj.connection_fields.present?\n  end\nend\n"
  },
  {
    "path": "app/admin/mail_log.rb",
    "content": "ActiveAdmin.register MailLog do\n  belongs_to :user\n\n  config.sort_order = \"created_at_desc\"\n\n  # Only allow viewing.\n  config.clear_action_items!\n  actions :all, :except => [:new, :edit, :destroy]\n\n  filter :message_id\n\n  breadcrumb do\n    user = User.find(params[:user_id])\n    connection = user.partner_connection\n    partner = connection.partner\n    [\n      link_to(\"Partners\", admin_partners_path),\n      link_to(partner.name, admin_partner_path(partner)),\n      link_to(\"Connections\", admin_partner_partner_connections_path(partner)),\n      link_to(connection.imap_provider.code, admin_partner_partner_connection_path(partner, connection)),\n      link_to(\"Users\", admin_partner_connection_users_path(connection)),\n      link_to(user.email, admin_partner_connection_user_path(connection, user)),\n      link_to(\"Mail Logs\", admin_user_mail_logs_path(user))\n    ]\n  end\n\n  index do\n    column :created_at\n    column \"Message ID\" do |obj|\n      link_to obj.message_id, admin_user_mail_log_path(obj.user, obj)\n    end\n    column \"Transmit Logs\", :sortable => :transmit_logs_count do |obj|\n      link_to(\"Transmit Logs (#{obj.transmit_logs_count})\", admin_mail_log_transmit_logs_path(obj))\n    end\n    actions\n  end\n\n  show do\n    attributes_table do\n      row :created_at\n      row :id\n      row :message_id\n    end\n  end\nend\n"
  },
  {
    "path": "app/admin/partner.rb",
    "content": "ActiveAdmin.register Partner do\n  menu :priority => 0\n  permit_params :name, :api_key,\n                :success_url, :failure_url,\n                :new_mail_webhook,\n                :user_connected_webhook,\n                :user_disconnected_webhook\n\n  breadcrumb do\n    [\n      link_to(\"Partners\", admin_partners_path)\n    ]\n  end\n\n  config.filters = false\n\n  index do\n    column :name do |partner|\n      link_to partner.name, admin_partner_path(partner)\n    end\n    column :links do |partner|\n      link_to(\"Connections (#{partner.partner_connections_count})\",\n              admin_partner_partner_connections_path(partner))\n    end\n\n    actions\n  end\n\n  show do |obj|\n    panel \"Connection Settings\" do\n      attributes_table_for obj do\n        row :name\n        row :api_key\n      end\n    end\n\n    panel \"Client Side Redirects\" do\n      attributes_table_for obj do\n        row :success_url\n        row :failure_url\n      end\n    end\n\n    panel \"Webhooks\" do\n      attributes_table_for obj do\n        row :user_connected_webhook\n        row :user_disconnected_webhook\n        row :new_mail_webhook\n      end\n    end\n  end\n\n  form do |f|\n    f.inputs \"Details\" do\n      f.input :name\n      f.input :api_key unless f.object.new_record?\n    end\n\n    f.inputs \"Client Side Redirects\" do\n      f.input :success_url\n      f.input :failure_url\n    end\n\n    f.inputs \"Webhooks\" do\n      f.input :user_connected_webhook\n      f.input :user_disconnected_webhook\n      f.input :new_mail_webhook\n    end\n    f.actions\n  end\nend\n"
  },
  {
    "path": "app/admin/partner_connection.rb",
    "content": "ActiveAdmin.register PartnerConnection do\n  belongs_to :partner\n\n  permit_params :imap_provider_id,\n                *Plain::PartnerConnection.connection_fields,\n                *Oauth2::PartnerConnection.connection_fields\n\n  controller do\n    def create\n      imap_provider = ImapProvider.find(params[:partner_connection][:imap_provider_id])\n      new_type = imap_provider.type.gsub(\"::ImapProvider\", \"::PartnerConnection\")\n      params[:partner_connection].merge!(:type => new_type)\n      super\n    end\n  end\n\n  breadcrumb do\n    partner = Partner.find(params[:partner_id])\n    [\n      link_to(\"Partners\", admin_partners_path),\n      link_to(partner.name, admin_partner_path(partner)),\n      link_to(\"Connections\", admin_partner_partner_connections_path(partner))\n    ]\n  end\n\n  config.filters = false\n\n  index do\n    column \"Imap Provider\" do |obj|\n      link_to obj.imap_provider.title, admin_partner_partner_connection_path(obj.partner, obj)\n    end\n\n    column \"Links\" do |obj|\n      raw [\n        link_to(\"Connection Type\",\n                admin_imap_provider_path(obj)),\n        link_to(\"Users (#{obj.users_count})\",\n                admin_partner_connection_users_path(obj))\n      ].join(\", \")\n    end\n    actions\n  end\n\n  show do |obj|\n    panel \"Details\" do\n      attributes_table_for obj do\n        row :imap_provider_code\n      end\n    end\n    panel \"Connection Settings\" do\n      attributes_table_for obj do\n        obj.connection_fields.map do |field|\n          row field\n        end\n      end\n    end if obj.connection_fields.present?\n  end\n\n  form do |f|\n    f.inputs \"Details\" do\n      f.input :imap_provider, :label => \"Auth Mechanism\",\n              :as => :select, :collection => ImapProvider.pluck(:title, :id)\n    end if f.object.new_record?\n\n    if !f.object.new_record? && f.object.connection_fields.present?\n      f.inputs \"Connection Settings\" do\n        f.object.connection_fields.each do |field|\n          f.input field, :input_html => { :value => f.object.send(field) }\n        end\n      end\n    end\n\n    f.actions\n  end\nend\n"
  },
  {
    "path": "app/admin/tracer_log.rb",
    "content": "ActiveAdmin.register TracerLog do\n  config.sort_order = \"created_at_desc\"\n\n  # Only allow viewing.\n  config.clear_action_items!\n  actions :all, :except => [:new, :edit, :destroy]\n\n  config.filters = false\n\n\n  index do\n    column :user\n    column :uid do |obj|\n      link_to obj.uid, admin_tracer_log_path(obj)\n    end\n    column :created_at\n    column :detected_at\n    column \"Elapsed\" do |obj|\n      if obj.detected_at && obj.created_at\n        seconds = obj.detected_at - obj.created_at\n        \"#{seconds.round(2)} s\"\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "app/admin/transmit_log.rb",
    "content": "ActiveAdmin.register TransmitLog do\n  belongs_to :mail_log\n\n  config.sort_order = \"created_at_desc\"\n\n  # Only allow viewing.\n  config.clear_action_items!\n  actions :all, :except => [:new, :edit, :destroy]\n\n  filter :response_code\n  filter :response_body\n\n  breadcrumb do\n    mail_log   = MailLog.find(params[:mail_log_id])\n    user       = mail_log.user\n    connection = user.partner_connection\n    partner    = connection.partner\n    [\n      link_to(\"Partners\", admin_partners_path),\n      link_to(partner.name, admin_partner_path(partner)),\n      link_to(\"Connections\", admin_partner_partner_connections_path(partner)),\n      link_to(connection.imap_provider.code, admin_partner_partner_connection_path(partner, connection)),\n      link_to(\"Users\", admin_partner_connection_users_path(connection)),\n      link_to(user.email, admin_partner_connection_user_path(connection, user)),\n      link_to(\"Mail Logs\", admin_user_mail_logs_path(user)),\n      link_to(mail_log.id, admin_user_mail_log_path(user, mail_log)),\n      link_to(\"Transmit Logs\", admin_mail_log_transmit_logs_path(mail_log))\n    ]\n  end\n\n  index do\n    column :response_code\n    column :response_body\n    column :created_at\n    actions\n  end\n\n  show do\n    attributes_table do\n      row :created_at\n      row :response_code\n      row :response_body\n    end\n  end\nend\n"
  },
  {
    "path": "app/admin/user.rb",
    "content": "ActiveAdmin.register User do\n  belongs_to :partner_connection\n  config.sort_order = \"email_asc\"\n  permit_params :tag, :enable_tracer,\n                *Plain::User.connection_fields,\n                *Oauth2::User.connection_fields\n\n  actions :all, :except => [:destroy]\n\n  action_item :only => :show do\n    if user.archived\n      link_to('Restore User', restore_admin_partner_connection_user_path(params[:partner_connection_id], user.id))\n    else\n      link_to('Archive User', archive_admin_partner_connection_user_path(params[:partner_connection_id], user.id))\n    end\n  end\n\n  member_action :archive, :method => :get do\n    user = User.find(params[:id])\n    user.update_attributes!(:archived => true)\n    redirect_to({:action => :show}, {:notice => \"User archived!\"})\n  end\n\n  member_action :restore, :method => :get do\n    user = User.find(params[:id])\n    user.update_attributes!(:archived => false)\n    redirect_to({:action => :show}, {:notice => \"User restored!\"})\n  end\n\n  breadcrumb do\n    connection = PartnerConnection.find(params[:partner_connection_id])\n    partner = connection.partner\n    [\n      link_to(\"Partners\", admin_partners_path),\n      link_to(partner.name, admin_partner_path(partner)),\n      link_to(\"Connections\", admin_partner_partner_connections_path(partner)),\n      link_to(connection.imap_provider_code,\n              admin_partner_partner_connection_path(partner, connection)),\n      link_to(\"Users\",\n              admin_partner_connection_users_path(connection))\n    ]\n  end\n\n  filter :tag\n  filter :email\n  scope :active\n  scope :archived\n  scope :tracer\n\n  index do\n    column :tag do |obj|\n      link_to obj.tag, admin_partner_connection_user_path(obj.connection, obj)\n    end\n    column :email do |obj|\n      if obj.email\n        link_to obj.email, admin_partner_connection_user_path(obj.connection, obj)\n      end\n    end\n    column \"Mail Logs\", :sortable => :mail_logs_count do |obj|\n      link_to(\"Mail Logs (#{obj.mail_logs_count})\",\n              admin_user_mail_logs_path(obj))\n    end\n    column :connected_at\n    column :last_login_at\n    column :last_email_at\n    column :tracer do |obj|\n      \"YES\" if obj.enable_tracer\n    end\n    column :archived do |obj|\n      \"YES\" if obj.archived\n    end\n  end\n\n  show do |obj|\n    panel \"Details\" do\n      attributes_table_for obj do\n        row :id\n        row :tag\n        row :connected_at\n        row :last_login_at\n        row :last_email_at\n        row :last_uid\n        row :last_uid_validity\n        row :type\n        row \"Links\" do\n          link_to(\"Connect\", new_users_connect_url(obj.signed_request_params)) +\n            \", \" +\n            link_to(\"Disconnect\", new_users_disconnect_url(obj.signed_request_params))\n          # [\n          # ].join(\", \")\n        end\n        row :enable_tracer\n        row :archived\n      end\n    end\n\n    panel \"Connection Settings\" do\n      attributes_table_for obj do\n        obj.connection_fields.map do |field|\n          row field\n        end\n      end\n    end if obj.connection_fields.present?\n  end\n\n  form do |f|\n    f.inputs \"Details\" do\n      f.input :tag\n      f.input :enable_tracer\n    end\n\n    if !f.object.new_record? && f.object.connection_fields.present?\n      f.inputs \"Connection Settings\" do\n        f.object.connection_fields.each do |field|\n          f.input field, :input_html => { :value => f.object.send(field) }\n        end\n      end\n    end\n\n    f.actions\n  end\nend\n"
  },
  {
    "path": "app/assets/images/.keep",
    "content": ""
  },
  {
    "path": "app/assets/javascripts/active_admin.js.coffee",
    "content": "#= require active_admin/base\n"
  },
  {
    "path": "app/assets/javascripts/application.js",
    "content": "// This is a manifest file that'll be compiled into application.js, which will include all the files\n// listed below.\n//\n// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,\n// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.\n//\n// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the\n// compiled file.\n//\n// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details\n// about supported directives.\n//\n//= require jquery\n//= require jquery_ujs\n//= require turbolinks\n//= require_tree .\n"
  },
  {
    "path": "app/assets/stylesheets/active_admin.css.scss",
    "content": "// SASS variable overrides must be declared before loading up Active Admin's styles.\n//\n// To view the variables that Active Admin provides, take a look at\n// `app/assets/stylesheets/active_admin/mixins/_variables.css.scss` in the\n// Active Admin source.\n//\n// For example, to change the sidebar width:\n// $sidebar-width: 242px;\n\n$body-background-color: #FFF !default;\n$primary-color: #8B1B89 !default;\n$secondary-color: #ffffff !default;\n$text-color: #333333 !default;\n$table-stripe-color: lighten($primary-color, 66%) !default;\n\n// Active Admin's got SASS!\n@import \"active_admin/mixins\";\n@import \"active_admin/base\";\n\nbody {\n    font-size: 14px;\n}\n\nth {\n    white-space: nowrap;\n}\n"
  },
  {
    "path": "app/assets/stylesheets/application.css",
    "content": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the bottom of the\n * compiled file so the styles you add here take precedence over styles defined in any styles\n * defined in the other CSS/SCSS files in this directory. It is generally better to create a new\n * file per style scope.\n *\n *= require_tree .\n *= require_self\n */\n"
  },
  {
    "path": "app/controllers/api/v1/connections_controller.rb",
    "content": "class Api::V1::ConnectionsController < ApplicationController\n  layout \"blank\"\n  respond_to :json\n  skip_before_action :verify_authenticity_token\n  before_action :default_format_json\n  before_action :load_partner\n  before_action :load_imap_provider, :only => [:create, :update, :show, :destroy]\n  before_action :load_connection, :only => [:update, :show, :destroy]\n\n  attr_accessor :partner, :imap_provider, :connection\n\n  def index\n    @connections = self.partner.connections\n  end\n\n  def create\n    self.connection = self.partner.connections.where(:imap_provider_id => imap_provider.id).build\n    self.connection.update_attributes!(connection_params)\n    render :show\n  rescue ActiveRecord::RecordInvalid => e\n    render :status => :bad_request, :text => e.to_s\n  end\n\n  def update\n    self.connection.update_attributes!(connection_params)\n    render :show\n  rescue ActiveRecord::RecordInvalid => e\n    render :status => :bad_request, :text => e.to_s\n  end\n\n  def show\n    # Pass.\n  end\n\n  def destroy\n    self.connection.destroy\n    render :status => :no_content, :text => \"Deleted connection.\"\n  end\n\n  private\n\n  def default_format_json\n    request.format = \"json\" unless params[:format]\n  end\n\n  def load_partner\n    api_key = request.headers['x-api-key'] || params[:api_key]\n    self.partner = Partner.find_by_api_key(api_key)\n    if self.partner.nil?\n      render :status => :not_found, :text => \"Partner not found. Check your api_key.\"\n    end\n  end\n\n  def load_imap_provider\n    code = params[:imap_provider_code]\n    self.imap_provider = ImapProvider.find_by_code(code)\n    if self.imap_provider.nil?\n      render :status => :not_found, :text => \"Imap Provider not found for '#{code}'.\"\n    end\n  end\n\n  def load_connection\n    self.connection = self.partner.connections.where(:imap_provider_id => imap_provider.id).first\n    if self.connection.nil?\n      render :status => :not_found, :text => \"Connection not found.\"\n    end\n  end\n\n  def connection_params\n    if self.connection\n      params.permit(self.connection.connection_fields)\n    else\n      params.permit()\n    end\n  end\nend\n"
  },
  {
    "path": "app/controllers/api/v1/users_controller.rb",
    "content": "class Api::V1::UsersController < ApplicationController\n  layout \"blank\"\n  respond_to :json\n  skip_before_action :verify_authenticity_token\n  before_action :default_format_json\n  before_action :load_partner\n  before_action :load_imap_provider\n  before_action :load_connection\n  before_action :load_user, :only => [:update, :show, :destroy]\n\n  attr_accessor :partner, :imap_provider, :connection, :user\n\n  def index\n    @users = self.connection.users.order(:email)\n  end\n\n  def create\n    self.user = self.connection.new_typed_user\n    self.user.update_attributes!(user_params)\n    render :show\n  rescue ActiveRecord::RecordInvalid => e\n    render :status => :bad_request, :text => e.to_s\n  end\n\n  def update\n    self.user.update_attributes!(user_params)\n    render :show\n  rescue ActiveRecord::RecordInvalid => e\n    render :status => :bad_request, :text => e.to_s\n  end\n\n  def show\n    # pass\n  end\n\n  def destroy\n    self.user.update_attributes(:archived => true)\n    render :status => :no_content, :text => \"Archived user.\"\n  end\n\n  private\n\n  def default_format_json\n    request.format = \"json\" unless params[:format]\n  end\n\n  def load_partner\n    api_key = request.headers['x-api-key'] || params[:api_key]\n    self.partner = Partner.find_by_api_key(api_key)\n    if partner.nil?\n      render :status => :not_found, :text => \"Partner not found. Check your api_key.\"\n    end\n  end\n\n  def load_imap_provider\n    code = params[:connection_imap_provider_code]\n    self.imap_provider = ImapProvider.find_by_code(code)\n    if self.imap_provider.nil?\n      render :status => :not_found, :text => \"Imap Provider not found for '#{code}'.\"\n    end\n  end\n\n  def load_connection\n    self.connection = self.partner.connections.find_by_imap_provider_id(self.imap_provider.id)\n    if self.connection.nil?\n      render :status => :not_found, :text => \"Connection not found.\"\n    end\n  end\n\n  def load_user\n    tag = params[:tag]\n    self.user = self.connection.users.find_by_tag(tag)\n    if self.user.nil?\n      render :status => :not_found, :text => \"User not found for '#{tag}'.\"\n    end\n  end\n\n  def user_params\n    if self.user\n      params.permit([:tag, :email, :archived] + self.user.connection_fields)\n    else\n      params.permit([:tag, :email, :archived])\n    end\n  end\nend\n"
  },
  {
    "path": "app/controllers/application_controller.rb",
    "content": "class ApplicationController < ActionController::Base\n  # Prevent CSRF attacks by raising an exception.\n  # For APIs, you may want to use :null_session instead.\n  protect_from_forgery with: :exception\n\n  before_action :ensure_secure\n\n  def ensure_secure\n    if !request.ssl? && Rails.env.production?\n      redirect_to request.original_url.gsub(/^http:/, \"https:\")\n    end\n  end\nend\n"
  },
  {
    "path": "app/controllers/concerns/.keep",
    "content": ""
  },
  {
    "path": "app/controllers/concerns/link_rel.rb",
    "content": "module LinkRel\n  extend ActiveSupport::Concern\n\n  included do\n    def self.link_rel(tag, url)\n      @links ||= []\n      @links << %(<#{url}; rel=\"#{tag}\")\n      headers['Link'] = @links.join(', ') if links.present?\n    end\n  end\nend\n"
  },
  {
    "path": "app/controllers/users/base_callback_controller.rb",
    "content": "class Users::BaseCallbackController < ApplicationController\n  before_action :load_user\n  before_action :validate_signature\n\n  attr_accessor :user\n\n  def new\n    # Store user in session.\n    self.user.signed_request_params.each do |key, value|\n      session[key] = value\n    end\n\n    # Set up the callback URLs.\n    session[:success_url] = params[:success] || partner.success_url\n    session[:failure_url] = params[:failure] || partner.failure_url\n\n    apply_helper\n  end\n\n  def callback\n    apply_helper\n  end\n\n  private\n\n  def apply_helper\n    helper = self.user.imap_provider.helper_for(params[:action])\n    self.send(helper)\n  end\n\n  def load_user(user_id = nil)\n    # Load from params or for a specific auth method.\n    self.user = User.find_by_id(user_id || params[:user_id] || session[:user_id])\n    if self.user.nil?\n      render :status => :not_found, :text => \"User not found.\"\n    end\n  end\n\n  def validate_signature(options = {})\n    # Validate from params or for a specific auth method.\n    is_valid =\n      self.user.valid_signature?(options) ||\n      self.user.valid_signature?(params) ||\n      self.user.valid_signature?(session)\n\n    if !is_valid\n      render :status => :not_found, :text => \"User not found.\"\n    end\n  end\n\n  def connection\n    self.user.connection\n  end\n\n  def partner\n    self.user.connection.partner\n  end\n\n  def imap_provider\n    self.user.connection.imap_provider\n  end\n\n  def redirect_to_success_url\n    redirect_to session[:success_url]\n  end\n\n  def redirect_to_failure_url\n    redirect_to session[:failure_url]\n  end\nend\n"
  },
  {
    "path": "app/controllers/users/connects_controller.rb",
    "content": "class Users::ConnectsController < Users::BaseCallbackController\n  include Plain::ConnectsHelper\n  include Oauth2::ConnectsHelper\n\n  # The new and callback actions are contained in\n  # Users::BaseCallbackController, which itself calls helpers\n  # according to the authentication type.\nend\n"
  },
  {
    "path": "app/controllers/users/disconnects_controller.rb",
    "content": "class Users::DisconnectsController < Users::BaseCallbackController\n  include Plain::DisconnectsHelper\n  include Oauth2::DisconnectsHelper\n\n  # The new and callback actions are contained in\n  # Users::BaseCallbackController, which itself calls helpers\n  # according to the authentication type.\nend\n"
  },
  {
    "path": "app/controllers/webhook_test_controller.rb",
    "content": "class WebhookTestController < ApplicationController\n  layout \"blank\"\n  skip_before_action :verify_authenticity_token\n\n  attr_accessor :json_params, :user\n\n  def new_mail\n    Log.info request.body\n    render :status => :ok, :text => \"OK\"\n  end\n\n  def user_connected\n    Log.info request.body\n    render :status => :ok, :text => \"OK\"\n  end\n\n  def user_disconnected\n    Log.info request.body\n    render :status => :ok, :text => \"OK\"\n  end\nend\n"
  },
  {
    "path": "app/helpers/application_helper.rb",
    "content": "module ApplicationHelper\n  def array_to_hash(values)\n    hash = {}\n    values.each do |k,v|\n      hash[k] = v\n    end\n    return hash\n  end\nend\n"
  },
  {
    "path": "app/helpers/oauth2/connects_helper.rb",
    "content": "module Oauth2::ConnectsHelper\n  BadRequestError = Class.new(StandardError)\n\n  attr_accessor :oauth2_token\n\n  def oauth2_new_helper\n    # Construct the client.\n    client = OAuth2::Client.new(\n      connection.oauth2_client_id,\n      connection.oauth2_client_secret_secure,\n      :site          => imap_provider.oauth2_site,\n      :authorize_url => imap_provider.oauth2_authorize_url)\n\n    # Construct the auth url.\n    auth_url = client.auth_code.authorize_url(\n      :redirect_uri    => callback_users_connect_url(),\n      :response_type   => imap_provider.oauth2_response_type,\n      :state           => \"\",\n      :scope           => imap_provider.oauth2_scope,\n      :access_type     => imap_provider.oauth2_access_type,\n      :approval_prompt => imap_provider.oauth2_approval_prompt)\n\n    # Redirect.\n    redirect_to auth_url\n  end\n\n  def oauth2_callback_helper\n    # Exchange the code for a refresh token.\n    # https://developers.google.com/accounts/docs/OAuth2WebServer\n    client = OAuth2::Client.new(\n      connection.oauth2_client_id,\n      connection.oauth2_client_secret_secure,\n      :site        => imap_provider.oauth2_site,\n      :token_url   => imap_provider.oauth2_token_url)\n\n    self.oauth2_token = client.auth_code.get_token(\n      params[:code],\n      :redirect_uri => callback_users_connect_url())\n\n    user.update_attributes!(\n      :email                => oauth2_email,\n      :oauth2_refresh_token => oauth2_token.refresh_token,\n      :connected_at         => Time.now)\n\n    begin\n      CallUserConnectedWebhook.new(user).run\n    rescue => e\n      CallUserConnectedWebhook.new(user).delay.run\n    end\n\n    redirect_to_success_url\n  rescue => e\n    Log.exception(e)\n    redirect_to_failure_url\n  end\n\n  def oauth2_email\n    method = \"#{imap_provider.code.downcase}_email\".to_sym\n    send(method)\n  end\n\n  def gmail_oauth2_email\n    # Get the google email address.\n    data = JSON.parse(oauth2_token.get(\"https://www.googleapis.com/userinfo/email?alt=json\").body)\n    return data[\"data\"][\"email\"]\n  end\nend\n"
  },
  {
    "path": "app/helpers/oauth2/disconnects_helper.rb",
    "content": "require 'uri'\n\nmodule Oauth2::DisconnectsHelper\n  def oauth2_new_helper\n    # Disconnect the user. Assume that this succeeds.\n    token = self.user.oauth2_refresh_token_secure || \"\"\n    url = \"https://accounts.google.com/o/oauth2/revoke?token=#{URI.escape(token)}\"\n    Net::HTTP.get_response(URI(url))\n\n    # Throw away our credentials.\n    self.user.update_attributes!(\n      :email                => nil,\n      :oauth2_refresh_token => nil,\n      :connected_at         => nil)\n\n    begin\n      CallUserDisconnectedWebhook.new(user).run\n    rescue => e\n      CallUserDisconnectedWebhook.new(user).delay.run\n    end\n\n    # Redirect.\n    redirect_to_success_url\n  end\nend\n"
  },
  {
    "path": "app/helpers/plain/connects_helper.rb",
    "content": "module Plain::ConnectsHelper\n  def plain_new_helper\n    raise :todo\n  end\n\n  def plain_callback_helper\n    raise :todo\n  end\nend\n"
  },
  {
    "path": "app/helpers/plain/disconnects_helper.rb",
    "content": "module Plain::DisconnectsHelper\n  def plain_new_helper\n    raise :todo\n  end\nend\n"
  },
  {
    "path": "app/interactors/base_webhook.rb",
    "content": "require 'timeout'\nrequire 'net/imap'\n\nclass BaseWebhook\n  private unless Rails.env.test?\n\n  def calculate_signature(api_key, uid, timestamp)\n    digest = OpenSSL::Digest.new('sha256')\n    return OpenSSL::HMAC.hexdigest(digest, api_key, \"#{timestamp}#{uid}\")\n  end\nend\n"
  },
  {
    "path": "app/interactors/call_new_mail_webhook.rb",
    "content": "# encoding: utf-8\n\nclass CallNewMailWebhook < BaseWebhook\n  attr_accessor :mail_log, :envelope, :raw_eml\n\n  def initialize(mail_log, envelope, raw_eml)\n    self.mail_log = mail_log\n    self.envelope = envelope\n    self.raw_eml = raw_eml\n  end\n\n  def run\n    user = mail_log.user\n    partner = user.partner_connection.partner\n\n    if partner.new_mail_webhook.blank?\n      return false\n    end\n\n    # Assemble the payload.\n    data = {\n      :timestamp          => Time.now.to_i,\n      :sha1               => mail_log.sha1,\n      :user_tag           => user.tag,\n      :imap_provider_code => user.connection.imap_provider_code,\n      :envelope           => envelope,\n      :rfc822             => raw_eml\n    }\n    data[:signature] = calculate_signature(partner.api_key, data[:sha1], data[:timestamp])\n\n    # START DEBUGGING!\n    begin\n      envelope.to_json\n    rescue => e\n      Log.info(\"Problem converting to JSON:\\n#{envelope}.\")\n    end\n\n    begin\n      raw_eml.to_json\n    rescue => e\n      Log.info(\"Problem converting to JSON:\\n#{raw_eml}.\")\n    end\n    # END DEBUGGING!\n\n    # Post the data\n    begin\n      transmit_log = mail_log.transmit_logs.create()\n\n      # Post the data.\n      webhook = RestClient::Resource.new(partner.new_mail_webhook)\n      response = Timeout::timeout(30) do\n        webhook.post(data.to_json, :content_type => :json, :accept => :json)\n      end\n\n      # Update the transmit log record.\n      transmit_log.update_attributes!(:response_code => response.code.to_i,\n                                      :response_body => response.to_s.slice(0, 1024))\n\n      Log.librato(:count, 'app.call_new_mail_webhook.count', 1)\n      return true\n    rescue RestClient::Forbidden => e\n      response = e.response\n      transmit_log.update_attributes!(:response_code => response.code.to_i,\n                                      :response_body => response.to_s.slice(0, 1024))\n\n      # The server understood the request but refused it. Mark the\n      # user as archived, but only if it's not a tracer user.\n      if !user.enable_tracer\n        user.update_attributes!(:archived => true)\n      end\n    rescue RestClient::Exception => e\n      response = e.response\n      transmit_log.update_attributes!(:response_code => response.code.to_i,\n                                      :response_body => response.to_s.slice(0, 1024))\n      raise e\n    rescue => e\n      transmit_log.update_attributes!(:response_code => \"ERROR\",\n                                      :response_body => e.to_s.slice(0, 1024))\n      raise e\n    end\n  end\nend\n"
  },
  {
    "path": "app/interactors/call_user_connected_webhook.rb",
    "content": "class CallUserConnectedWebhook < BaseWebhook\n  attr_accessor :user\n\n  def initialize(user)\n    self.user = user\n  end\n\n  def run\n    partner = user.partner_connection.partner\n\n    if partner.user_connected_webhook.blank?\n      return false\n    end\n\n    # Assemble the payload.\n    data = {\n      :timestamp          => Time.now.to_i,\n      :sha1               => Digest::SHA1.hexdigest(user.tag),\n      :user_tag           => user.tag,\n      :imap_provider_code => user.connection.imap_provider_code,\n      :email              => user.email\n    }\n    data[:signature] = calculate_signature(partner.api_key, data[:sha1], data[:timestamp])\n\n    # Post the data.\n    begin\n      webhook = RestClient::Resource.new(partner.user_connected_webhook)\n      response = Timeout::timeout(30) do\n        webhook.post(data.to_json, :content_type => :json, :accept => :json)\n      end\n      Log.librato(:count, 'app.call_user_connected_webhook.count', 1)\n    rescue RestClient::Forbidden => e\n      # The server understood the request but refused it. Mark the\n      # user as archived, but only if it's not a tracer user.\n      if !user.enable_tracer\n        user.update_attributes!(:archived => true)\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "app/interactors/call_user_disconnected_webhook.rb",
    "content": "class CallUserDisconnectedWebhook < BaseWebhook\n  attr_accessor :user\n\n  def initialize(user)\n    self.user = user\n  end\n\n  def run\n    partner = user.partner_connection.partner\n\n    if partner.user_disconnected_webhook.blank?\n      return false\n    end\n\n    # Assemble the payload.\n    data = {\n      :timestamp          => Time.now.to_i,\n      :sha1               => Digest::SHA1.hexdigest(user.tag),\n      :user_tag           => user.tag,\n      :imap_provider_code => user.connection.imap_provider_code\n    }\n    data[:signature] = calculate_signature(partner.api_key, data[:sha1], data[:timestamp])\n\n    begin\n      # Post the data.\n      webhook = RestClient::Resource.new(partner.user_disconnected_webhook)\n      response = Timeout::timeout(30) do\n        webhook.post(data.to_json, :content_type => :json, :accept => :json)\n      end\n      Log.librato(:count, 'app.call_user_disconnected_webhook.count', 1)\n    rescue RestClient::Forbidden => e\n      # The server understood the request but refused it. Mark the\n      # user as archived, but only if it's not a tracer user.\n      if !user.enable_tracer\n        user.update_attributes!(:archived => true)\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "app/interactors/schedule_tracer_emails.rb",
    "content": "class ScheduleTracerEmails\n  attr_accessor :user, :num_tracers\n\n  def initialize(user, num_tracers)\n    self.user = user\n    self.num_tracers = num_tracers\n  end\n\n  def run\n    num_tracers.times.each do |n|\n      send_tracer_to_user(user)\n    end\n  end\n\n  def send_tracer_to_user(user)\n    # Deliver the mail.\n    uid = SecureRandom.hex(10)\n    mail = TracerMailer.tracer_email(user, uid)\n    user.connection.imap_provider.authenticate_smtp(mail, user)\n    mail.deliver\n    Log.librato(:count, 'app.schedule_tracer_email.count', 1)\n\n    # Log the tracer.\n    user.tracer_logs.create!(:uid => uid)\n  end\nend\n"
  },
  {
    "path": "app/mailers/.keep",
    "content": ""
  },
  {
    "path": "app/mailers/tracer_mailer.rb",
    "content": "class TracerMailer < ActionMailer::Base\n  def tracer_email(user, uid)\n    @uid = uid\n    mail(:from => user.email,\n         :to => user.email,\n         :subject => \"TRACER: #{uid}\")\n  end\nend\n"
  },
  {
    "path": "app/models/.keep",
    "content": ""
  },
  {
    "path": "app/models/admin_user.rb",
    "content": "class AdminUser < ActiveRecord::Base\n  # Include default devise modules. Others available are:\n  # :confirmable, :lockable, :timeoutable and :omniauthable\n  devise :database_authenticatable, :trackable, :validatable, :lockable\nend\n"
  },
  {
    "path": "app/models/concerns/.keep",
    "content": ""
  },
  {
    "path": "app/models/concerns/auth_method_helper.rb",
    "content": "module AuthMethodHelper\n  def auth_method_plain?\n    /^plain$/i.match(self.auth_method)\n  end\n\n  def auth_method_oauth2?\n    /^oauth2$/i.match(self.oauth_method)\n  end\nend\n"
  },
  {
    "path": "app/models/concerns/connection_fields.rb",
    "content": "# coding: utf-8\nmodule ConnectionFields\n  extend ActiveSupport::Concern\n\n  included do\n    @connection_fields = []\n\n    def self.encrypt(value)\n      if Rails.application.config.encryption_cipher && value.present?\n        Rails.application.config.encryption_cipher.encrypt(value)\n      else\n        value\n      end\n    end\n\n    def self.decrypt(value)\n      begin\n        if Rails.application.config.encryption_cipher && value.present?\n          Rails.application.config.encryption_cipher.decrypt(value)\n        else\n          value\n        end\n      rescue\n        value\n      end\n    end\n\n    def self.connection_field(field, options = {})\n      @connection_fields ||= []\n      @connection_fields << field\n\n      # Maybe validate presence.\n      if options[:required]\n        validates_presence_of(field)\n      end\n\n      # Maybe obscure the actual value.\n      if options[:secure]\n        define_method(field) do |secure = false|\n          if !secure && self[field].present?\n            \"- encrypted -\"\n          else\n            self.class.decrypt(super())\n          end\n        end\n\n        define_method(\"#{field}_secure\".to_sym) do\n          self.send(field, true)\n        end\n\n        define_method(\"#{field}=\".to_sym) do |value|\n          if value != self.send(field)\n            super(self.class.encrypt(value))\n          end\n        end\n      end\n    end\n\n    def self.connection_fields\n      @connection_fields || []\n    end\n\n    def connection_fields\n      self.class.connection_fields\n    end\n  end\nend\n"
  },
  {
    "path": "app/models/delayed_job.rb",
    "content": "class DelayedJob < ActiveRecord::Base\n  # Run all existing delayed_job records. Log errors, return true if\n  # everything was run.\n  def self.flush\n    count = 0\n    while job = Delayed::Job.where(\"locked_at IS NULL\").first do\n      count += 1\n      raise \"Delayed Job loop?\" if count > 10\n      begin\n        job.invoke_job\n        job.destroy\n      rescue => e\n        print \"Problem processing delayed job:\\n#{job.to_yaml}\"\n        raise e\n      end\n    end\n    return true\n  end\nend\n"
  },
  {
    "path": "app/models/imap_daemon_heartbeat.rb",
    "content": "class ImapDaemonHeartbeat < ActiveRecord::Base\nend\n"
  },
  {
    "path": "app/models/imap_provider.rb",
    "content": "class ImapProvider < ActiveRecord::Base\n  include ConnectionFields\n  has_many :partner_connections\n\n  def display_name\n    self.code\n  end\n\n  # Public: Single Table Inheritance helper. Returns the correct\n  # inherited class depending on the ImapProvider class.\n  #\n  # Usage:\n  #\n  #     imap_provider = Oauth2::ImapProvider.new\n  #     imap_provider.class_for(User) => Oauth2::User\n  #\n  # Returns a class.\n  def class_for(c)\n    (self.class.parent_name + \"::\" + c.base_class.name).constantize\n  end\n\n  # Public: Single Table Inheritance helper. Returns the name of a\n  # helper method depending on the ImapProvider class.\n  #\n  # Usage:\n  #\n  #     imap_provider = Oauth2::ImapProvider.new\n  #     imap_provider.helper_for(:connects, :new) => :oauth2_new_connects_helper\n  #\n  # Returns a symbol.\n  def helper_for(action)\n    \"#{self.class.parent_name.underscore}_#{action}_helper\".to_sym\n  end\nend\n"
  },
  {
    "path": "app/models/mail_log.rb",
    "content": "class MailLog < ActiveRecord::Base\n  belongs_to :user, :counter_cache => true\n  has_many :transmit_logs, :dependent => :destroy\nend\n"
  },
  {
    "path": "app/models/oauth2/imap_provider.rb",
    "content": "require 'xoauth2_authenticator'\n\nclass Oauth2::ImapProvider < ImapProvider\n  include ConnectionFields\n\n  connection_field :oauth2_grant_type, :required => true\n  connection_field :oauth2_scope, :required => true\n  connection_field :oauth2_site, :required => true\n  connection_field :oauth2_token_method, :required => true\n  connection_field :oauth2_token_url, :required => true\n  connection_field :oauth2_authorize_url, :required => true\n  connection_field :oauth2_response_type, :required => true\n  connection_field :oauth2_access_type, :required => true\n  connection_field :oauth2_approval_prompt, :required => true\n\n  def authenticate_imap(client, user)\n    client.authenticate('XOAUTH2', user.email, _access_token(user))\n  end\n\n  def authenticate_smtp(mail, user)\n    mail.delivery_method.settings.merge!(\n      :address              => smtp_host,\n      :port                 => smtp_port,\n      :domain               => smtp_domain,\n      :user_name            => user.email,\n      :password             => _access_token(user),\n      :authentication       => :xoauth2,\n      :enable_starttls_auto => smtp_enable_starttls_auto\n    )\n  end\n\n  private\n\n  def _access_token(user)\n    partner_connection = user.connection\n\n    oauth_client = OAuth2::Client.new(\n      partner_connection.oauth2_client_id,\n      partner_connection.oauth2_client_secret_secure,\n      {\n        :site         => oauth2_site,\n        :token_url    => oauth2_token_url,\n        :token_method => oauth2_token_method.to_sym,\n        :grant_type   => oauth2_grant_type,\n        :scope        => oauth2_scope\n      })\n\n    oauth2_access_token = oauth_client.get_token(\n      {\n        :client_id     => partner_connection.oauth2_client_id,\n        :client_secret => partner_connection.oauth2_client_secret_secure,\n        :refresh_token => user.oauth2_refresh_token_secure,\n        :grant_type    => oauth2_grant_type\n      })\n\n    oauth2_access_token.token\n  end\nend\n"
  },
  {
    "path": "app/models/oauth2/partner_connection.rb",
    "content": "class Oauth2::PartnerConnection < PartnerConnection\n  include ConnectionFields\n  connection_field :oauth2_client_id, :required => true\n  connection_field :oauth2_client_secret, :required => true, :secure => true\nend\n"
  },
  {
    "path": "app/models/oauth2/user.rb",
    "content": "class Oauth2::User < User\n  include ConnectionFields\n  before_save :update_connected_at\n\n  connection_field :email\n  connection_field :oauth2_refresh_token, :secure => true\n\n  def update_connected_at\n    if email.present? && oauth2_refresh_token.present?\n      self.connected_at ||= Time.now\n    else\n      self.connected_at = nil\n    end\n  end\nend\n"
  },
  {
    "path": "app/models/partner.rb",
    "content": "class Partner < ActiveRecord::Base\n  # Magic.\n  before_save :ensure_api_key\n\n  # Relations\n  has_many :partner_connections, :dependent => :destroy\n  alias_method :connections, :partner_connections\n\n  # Validations\n  validates :name, :presence => true\n\n  def ensure_api_key\n    self.api_key ||= SecureRandom.hex(10)\n  end\n\n  # Public: Create a new connection that bases it's type on the\n  # provided imap_provider. In other words, if this is an\n  # Oauth2::ImapProvider, then return an Oauth2::ImapProvider.\n  def new_typed_connection(imap_provider)\n    connection = imap_provider.class_for(PartnerConnection).new\n    self.connections << connection\n    connection\n  end\nend\n"
  },
  {
    "path": "app/models/partner_connection.rb",
    "content": "class PartnerConnection < ActiveRecord::Base\n  include ConnectionFields\n\n  # Magic.\n  before_validation :fix_type\n\n  # Relations.\n  belongs_to :partner, :counter_cache => true\n  belongs_to :imap_provider, :counter_cache => true\n  has_many :users, :dependent => :destroy\n\n  # Validation.\n  validates_presence_of :imap_provider_id\n  validates_uniqueness_of :imap_provider_id, :scope => :partner_id\n\n  # Public: Used by ActiveAdmin.\n  def display_name\n    self.imap_provider_code\n  end\n\n  def imap_provider_code\n    self.imap_provider.code\n  end\n\n  # Public: Create a new user that bases it's type on the\n  # PartnerConnection type. In other words, if this is an\n  # Oauth2::PartnerConnection, then return an Oauth2::User.\n  def new_typed_user\n    user = self.imap_provider.class_for(User).new\n    self.users << user\n    user\n  end\n\n  private\n\n  # Private: Automatically set the STI type based on the imap_provider.\n  def fix_type\n    self.type ||= self.imap_provider.class_for(PartnerConnection).to_s\n  end\nend\n"
  },
  {
    "path": "app/models/plain/imap_provider.rb",
    "content": "class Plain::ImapProvider < ImapProvider\n  include ConnectionFields\n\n  def authenticate_smtp(mail, user)\n    mail.delivery_method.settings.merge!(\n      :address              => smtp_host,\n      :port                 => smtp_port,\n      :domain               => smtp_domain,\n      :user_name            => user.login_username,\n      :password             => user.login_password,\n      :authentication       => :plain,\n      :enable_starttls_auto => enable_starttls_auto\n    )\n\n    client.login(user.login_username, user.login_password_secure)\n  end\n\n  def authenticate_imap(client, user)\n    client.login(user.login_username, user.login_password_secure)\n  end\nend\n"
  },
  {
    "path": "app/models/plain/partner_connection.rb",
    "content": "class Plain::PartnerConnection < PartnerConnection\n  include ConnectionFields\nend\n"
  },
  {
    "path": "app/models/plain/user.rb",
    "content": "class Plain::User < User\n  include ConnectionFields\n  before_save :update_connected_at\n\n  connection_field :login_username\n  connection_field :login_password, :secure => true\n\n  def update_connected_at\n    if login_username.present? && login_password.present?\n      self.connected_at ||= Time.now\n    else\n      self.connected_at = nil\n    end\n  end\nend\n"
  },
  {
    "path": "app/models/tracer_log.rb",
    "content": "class TracerLog < ActiveRecord::Base\n  belongs_to :user\nend\n"
  },
  {
    "path": "app/models/transmit_log.rb",
    "content": "class TransmitLog < ActiveRecord::Base\n  belongs_to :mail_log, :counter_cache => true\nend\n"
  },
  {
    "path": "app/models/user.rb",
    "content": "class User < ActiveRecord::Base\n  include ConnectionFields\n\n  # Magic.\n  before_validation :fix_type\n\n  # Scopes.\n  scope :active, proc { where(:archived => false).where.not(:last_email_at => nil) }\n  scope :archived, proc { where(:archived => true) }\n  scope :tracer, proc { where(:enable_tracer => true) }\n\n  # Relations.\n  has_many :mail_logs, :dependent => :destroy\n  has_many :tracer_logs, :dependent => :destroy\n  belongs_to :partner_connection, :counter_cache => true\n  alias_method :connection, :partner_connection\n\n  # Validations.\n  validates_presence_of :tag\n  validates_uniqueness_of :tag, :case_sensitive => false,\n                          :scope      => :partner_connection_id,\n                          :conditions => -> { where.not(:archived => true) },\n                          :if => Proc.new { |object| object.tag_changed? }\n\n  validates_uniqueness_of :email, :case_sensitive => false,\n                          :scope      => :partner_connection_id,\n                          :allow_nil  => true,\n                          :conditions => -> { where.not(:archived => true) },\n                          :if => Proc.new { |object| object.email_changed? }\n\n  def imap_provider\n    self.connection.imap_provider\n  end\n\n  # Public: Calculate a timestamped signature. Used to sign redirect\n  # URLs. Returns a hash.\n  def signed_request_params(timestamp = nil)\n    timestamp ||= Time.now.to_i\n    data = \"#{self.id} - #{timestamp} - #{self.connection.partner.api_key}\"\n    {\n      'user_id' => id,\n      'ts'      => timestamp,\n      'sig'     => Digest::SHA1.hexdigest(data).slice(0, 10)\n    }\n  end\n\n  # Public: Verify a timestamp signature.\n  def valid_signature?(params)\n    (Time.at(params['ts'].to_i) > 30.minutes.ago) &&\n      params['sig'] == signed_request_params(params['ts'])['sig']\n  end\n\n  private\n\n  # Private: Automatically set the STI type based on the imap_provider.\n  def fix_type\n    self.type ||= self.partner_connection.imap_provider.class_for(User).to_s\n  end\nend\n"
  },
  {
    "path": "app/processes/common/csv_log.rb",
    "content": "class Common::CsvLog\n  include Common::Stoppable\n  include Common::WrappedThread\n\n  attr_accessor :log_path\n  attr_accessor :log_filehandle\n  attr_accessor :log_queue\n  attr_accessor :log_thread\n\n  def initialize(log_path)\n    init_stoppable\n    self.log_path   = log_path\n    self.log_queue  = Queue.new\n    self.log_thread = wrapped_thread do\n      _thread_runner\n    end\n  end\n\n  def log(*values)\n    self.log_queue << values\n  end\n\n  private\n\n  def _thread_runner\n    self.log_filehandle = File.open(log_path, \"w\")\n    while running?\n      _drain_queue\n      sleep 0.1\n    end\n    _drain_queue\n    _close_file\n  end\n\n  def _drain_queue\n    while true\n      # Don't block, otherwise we can't exit.\n      values = log_queue.pop(true)\n      log_filehandle.write(values.join(\",\") + \"\\n\")\n    end\n  rescue ThreadError => e\n    # Thrown when queue is empty.\n    log_filehandle.flush()\n  end\n\n  def _close_file\n    log_filehandle.close\n  rescue IOError\n    # May fire if we've already closed the stream elsewhere.\n  end\nend\n"
  },
  {
    "path": "app/processes/common/db_connection.rb",
    "content": "module Common::DbConnection\n  def db_config\n    ActiveRecord::Base.configurations[Rails.env] ||\n      Rails.application.config.database_configuration[Rails.env]\n  end\n\n  def set_db_connection_pool_size(size)\n    ActiveRecord::Base.connection_pool.disconnect!\n    ActiveSupport.on_load(:active_record) do\n      config = ActiveRecord::Base.configurations[Rails.env] ||\n               Rails.application.config.database_configuration[Rails.env]\n      config['pool'] = size\n      ActiveRecord::Base.establish_connection(config)\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/common/light_sleep.rb",
    "content": "module Common::LightSleep\n  include Common::Stoppable\n\n  def light_sleep(seconds = nil)\n    now = Time.now\n    while running?\n      break if seconds.present? && ((Time.now - now) >= seconds)\n      sleep 1\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/common/stoppable.rb",
    "content": "module Common::Stoppable\n  def init_stoppable\n    @stop = false\n    @stop_lock = Mutex.new\n  end\n\n  def trap_signals\n    Signal.trap(\"INT\") do self.stop! end\n    Signal.trap(\"TERM\") do self.stop! end\n  end\n\n  def stop!\n    @stop_lock.synchronize do\n      @stop = true\n    end\n  end\n\n  def running?\n    @stop_lock.synchronize do\n      @stop != true\n    end\n  end\n\n  def stopping?\n    @stop_lock.synchronize do\n      @stop == true\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/common/worker_pool.rb",
    "content": "module Common::WorkerPool\n  include Common::Stoppable\n  include Common::WrappedThread\n  include Common::DbConnection\n\n  attr_accessor :worker_rhash\n  attr_accessor :work_queues, :work_queues_lock\n  attr_accessor :worker_threads, :worker_threads_lock\n  attr_accessor :work_queue_latency\n\n  def init_worker_pool\n    self.work_queues = []\n    self.work_queues_lock = Mutex.new\n    self.worker_threads = []\n    self.worker_threads_lock = Mutex.new\n    self.worker_rhash = ImapClient::RendezvousHash.new\n  end\n\n  # Public: Start a number of worker threads and begin processing\n  # scheduled work.\n  def start_worker_pool(num_worker_threads)\n    # Create work queues.\n    work_queues_lock.synchronize do\n      worker_threads_lock.synchronize do\n        num_worker_threads.times do |n|\n          work_queue = Queue.new\n          worker_thread = _start_worker_thread(work_queue)\n          self.work_queues << work_queue\n          self.worker_threads << worker_thread\n        end\n      end\n    end\n\n    tags = num_worker_threads.times.map(&:to_i)\n    self.worker_rhash.site_tags = tags\n  end\n\n  # Public: Schedule a task to be executed on one of the work\n  # queues. If a :hash option is provided, then use this to\n  # consistently send the work to the same worker. This allows us to\n  # effectively \"single thread\" some lines of work.\n  #\n  # s - The command to schedule.\n  # options - Options for the command.\n  #\n  # Returns nothing.\n  def schedule_work(s, options)\n    raise \"No hash specified!\" if options[:hash].nil?\n    index = worker_rhash.hash(options[:hash])\n    options.merge!(:'$action' => s, :'$time' => Time.now)\n    work_queues_lock.synchronize do\n      work_queues[index] << options\n    end\n  end\n\n  # Public: Return the total number of scheduled items in the work queue.\n  def work_queue_length\n    work_queues_lock.synchronize do\n      work_queues.map(&:size).inject(&:+)\n    end\n  end\n\n  # Public: Wait for the worker pool to finish processing all items.\n  def terminate_worker_pool\n    Log.info(\"Waiting for worker threads...\")\n    worker_threads_lock.synchronize do\n      worker_threads.present? && worker_threads.map(&:terminate)\n    end\n  end\n\n  private\n\n  def _start_worker_thread(work_queue)\n    wrapped_thread do\n      ActiveRecord::Base.connection_pool.with_connection do |conn|\n        _worker_thread_runner(work_queue)\n      end\n    end\n  end\n\n  def _worker_thread_runner(work_queue)\n    # Create a work queue.\n    while running?\n      _worker_thread_next_action(work_queue)\n    end\n  end\n\n  def _worker_thread_next_action(queue)\n    # Don't block, otherwise we can't exit.\n    options = queue.pop(true)\n    method = \"action_#{options[:'$action']}\".to_sym\n\n    # Run the action.\n    begin\n      self.send(method.to_sym, options)\n    rescue => e\n      Log.exception(e)\n    end\n\n    # Track the most recent latency.\n    self.work_queue_latency = Time.now - options[:'$time']\n  rescue ThreadError => e\n    # Queue is empty.\n    sleep 0.1\n  end\nend\n"
  },
  {
    "path": "app/processes/common/wrapped_thread.rb",
    "content": "module Common::WrappedThread\n  def wrapped_thread(&block)\n    Thread.new do\n      begin\n        yield\n      rescue => e\n        Log.exception(e)\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_client/daemon.rb",
    "content": "#  ImapClient::Daemon - Main entry point for the IMAP client. Reads\n#  credentials from a database, connects to IMAP servers, listens for\n#  email, generates webhook events.\n#\n#  Contains load-balancing code so that when multiple ImapClient::Daemon\n#  processes are running they claim users evenly. The ImapClient::Daemon\n#  coordinate through the database.\n#\n#  Starts a few different types of threads:\n#\n#  + Heartbeat thread - Publishes our heartbeat to the database. Runs every 10 seconds.\n#  + Discovery thread - Listen for the heartbeats of other ImapClient::Daemon processes. Runs every 30 seconds.\n#  + Claim thread - Claims an even share of users. Runs every 30 seconds.\n#  + Worker threads - A small pool of threads to run CPU intensive operations. (5 by default.)\n#  + User threads - A list of threads created on demand to managed communication with IMAP server. (Limited to 500 by default.)\n\nrequire 'net/imap'\n\nclass ImapClient::Daemon\n  include Common::Stoppable\n  include Common::WorkerPool\n  include Common::LightSleep\n  include Common::WrappedThread\n  include Common::DbConnection\n\n  # Config variables.\n  attr_accessor :stress_test_mode, :chaos_mode, :enable_profiler\n  attr_accessor :num_worker_threads, :max_user_threads, :max_email_size, :tracer_interval, :num_tracers\n\n  # Threads.\n  attr_accessor :heartbeat_thread, :discovery_thread, :claim_thread, :tracer_thread\n\n  # Instance variables.\n  attr_accessor :server_tag, :server_rhash\n\n  # Shared variables.\n  attr_accessor :user_threads, :user_threads_lock\n  attr_accessor :error_counts, :error_counts_lock\n  attr_accessor :tracer_emails_processed\n  attr_accessor :total_emails_processed\n\n  # Stress testing variables.\n  attr_accessor :processed_log\n\n\n  def initialize(options = {})\n    # Settings.\n    self.stress_test_mode   = options.fetch(:stress_test_mode)\n    self.chaos_mode         = options.fetch(:enable_chaos)\n    self.num_worker_threads = options.fetch(:num_worker_threads)\n    self.max_user_threads   = options.fetch(:max_user_threads)\n    self.max_email_size     = options.fetch(:max_email_size)\n    self.tracer_interval    = options.fetch(:tracer_interval)\n    self.num_tracers        = options.fetch(:num_tracers)\n    self.enable_profiler    = options.fetch(:enable_profiler)\n\n    # Initialize mixins.\n    init_stoppable\n    init_worker_pool\n\n    # Load balancing stuff.\n    self.server_tag = SecureRandom.hex(10)\n    self.server_rhash = ImapClient::RendezvousHash.new\n\n    # User stuff.\n    self.user_threads = {}\n    self.user_threads_lock = Mutex.new\n\n    # Error count stuff.\n    self.error_counts = {}\n    self.error_counts_lock = Mutex.new\n\n    # Stats.\n    self.total_emails_processed = 0\n  end\n\n  #\n  # Thread safe methods for `user_threads` object.\n  #\n\n  # Public: Get number of user threads.\n  def user_threads_count\n    user_threads_lock.synchronize do\n      user_threads.count\n    end\n  end\n\n  # Public: Get user thread for a user.\n  def get_user_thread(user_id)\n    user_threads_lock.synchronize do\n      user_threads[user_id]\n    end\n  end\n\n  # Public: Set user thread for a user.\n  def set_user_thread(user_id, user_thread)\n    user_threads_lock.synchronize do\n      user_threads[user_id] = user_thread\n    end\n  end\n\n  # Public: Delete user thread.\n  def delete_user_thread(user_id)\n    user_threads_lock.synchronize do\n      user_threads.delete(user_id)\n    end\n  end\n\n  # Public: Execute a block on all user threads. Block takes user_id,\n  # user_thread parameters.\n  def walk_user_threads\n    user_threads_lock.synchronize do\n      user_threads.each do |user_id, user_thread|\n        yield(user_id, user_thread)\n      end\n    end\n  end\n\n\n  #\n  # Thread safe methods for `error_counts`.\n  #\n\n  # Public: Returns the number of errors for a user.\n  def get_error_count(user_id)\n    error_counts_lock.synchronize do\n      self.error_counts[user_id] ||= 0\n    end\n  end\n\n  # Public: Increment the error count for a user\n  def increment_error_count(user_id)\n    error_counts_lock.synchronize do\n      self.error_counts[user_id] ||= 0\n      self.error_counts[user_id] += 1\n    end\n  end\n\n  # Public:\n  def clear_error_count(user_id)\n    error_counts_lock.synchronize do\n      self.error_counts[user_id] = 0\n    end\n  end\n\n\n  def run\n    trap_signals\n    force_class_loading\n    maybe_start_profiling\n\n    # If stress testing, start a log.\n    if self.stress_test_mode\n      self.processed_log = Common::CsvLog.new(\"./log/stress/processed_emails_#{server_tag}.csv\")\n    end\n\n    # Start our threads. We need one thread for each worker, plus four\n    # additional threads -- one each for the heartbeat, discovery,\n    # claim, and tracer threads.\n    set_db_connection_pool_size(self.num_worker_threads + 5)\n    start_worker_pool(num_worker_threads)\n    start_heartbeat_thread\n    start_discovery_thread\n    start_claim_thread\n    start_tracer_thread\n\n    # Sleep until we are stopped.\n    light_sleep\n  rescue Exception => e\n    Log.error(\"ImapClient::Daemon is stopping because of an exception.\")\n    Log.exception(e)\n    stop!\n  ensure\n    stop!\n    Log.info(\"ImapClient::Daemon is stopping.\")\n    heartbeat_thread && heartbeat_thread.terminate\n    discovery_thread && discovery_thread.terminate\n    claim_thread && claim_thread.terminate\n    terminate_worker_pool\n    terminate_user_threads\n    self.processed_log.stop! if self.processed_log\n    stop_profiling\n  end\n\n\n  private\n\n\n  def force_class_loading\n    # Force ImapDaemonHeartbeat to load before we create any\n    # threads. This fixes a \"Circular dependency detected while\n    # autoloading constant ImapDaemonHeartbeat\" error.\n    ImapDaemonHeartbeat\n    CallNewMailWebhook\n  end\n\n  def start_heartbeat_thread\n    self.heartbeat_thread = Thread.new do\n      ActiveRecord::Base.connection_pool.with_connection do |conn|\n        heartbeat_thread_runner\n      end\n    end\n  end\n\n  def start_discovery_thread\n    self.discovery_thread = Thread.new do\n      ActiveRecord::Base.connection_pool.with_connection do |conn|\n        discovery_thread_runner\n      end\n    end\n\n    # Wait for servers.\n    while running? && server_rhash.size == 0\n      Log.info(\"Discovering other daemons...\")\n      light_sleep 1\n    end\n  end\n\n  def start_claim_thread\n    self.claim_thread = Thread.new do\n      ActiveRecord::Base.connection_pool.with_connection do |conn|\n        claim_thread_runner\n      end\n    end\n  end\n\n  def start_tracer_thread\n    self.tracer_thread = Thread.new do\n      ActiveRecord::Base.connection_pool.with_connection do |conn|\n        tracer_thread_runner\n      end\n    end\n  end\n\n  # Private: Creates/updates an ImapDaemonHeartbeat record in the\n  # database every 10 seconds.\n  def heartbeat_thread_runner\n    heartbeat = ImapDaemonHeartbeat.create(:tag => server_tag)\n    while running?\n      # Update the heartbeat.\n      heartbeat.touch\n\n      # Log Heroku / Librato stats.\n      Log.librato(:measure, 'imap_client.thread.count', Thread.list.count)\n      Log.librato(:measure, 'imap_client.work_queue.length', work_queue_length)\n      Log.librato(:measure, 'imap_client.user_thread.count', user_threads_count)\n      Log.librato(:measure, 'work_queue.latency', work_queue_latency)\n      Log.librato(:sample, 'imap_client.total_emails_processed', total_emails_processed)\n\n      light_sleep 10\n    end\n  rescue Exception => e\n    Log.exception(e)\n    raise e\n  ensure\n    Log.info(\"Stopping heartbeat thread.\")\n    heartbeat.delete if heartbeat\n  end\n\n  # Private: Fetches all recently updated ImapDaemonHeartbeat records\n  # in the database very 30 seconds. Create a new RendezvousHash from\n  # the associated tags.\n  def discovery_thread_runner\n    while running?\n      tags = ImapDaemonHeartbeat.where(\"updated_at >= ?\", 30.seconds.ago).map(&:tag)\n      Log.info(\"There are #{tags.count} daemons running.\")\n\n      self.server_rhash.site_tags = tags\n\n      if server_rhash.size == 0\n        light_sleep 1\n      else\n        light_sleep 10\n      end\n    end\n  rescue Exception => e\n    Log.exception(e)\n    raise e\n  ensure\n    Log.info(\"Stopping discovery thread.\")\n  end\n\n  # Private: Iterate through users and schedule a connect or\n  # disconnect task depending on whether the user is hashed to this\n  # server.\n  def claim_thread_runner\n    while running?\n      User.select(:id, :email, :connected_at, :archived).find_each do |user|\n        if server_rhash.hash(user.id) == server_tag && !user.archived && user.connected_at\n          schedule_work(:connect_user, :hash => user.id, :user_id => user.id)\n        else\n          schedule_work(:disconnect_user, :hash => user.id, :user_id => user.id)\n        end\n\n        # Try not to peg the processor.\n        sleep 0.01\n      end\n      light_sleep 10\n    end\n  rescue Exception => e\n    Log.exception(e)\n    raise e\n  ensure\n    Log.info(\"Stopping claim thread.\")\n  end\n\n  # Private: Schedule a tracer emails to random tracer users.\n  def tracer_thread_runner\n    while running?\n      # Get a random user assigned to this server.\n      user = User.where(:enable_tracer => true, :archived => false).select(:id, :connected_at).all.select do |user|\n        server_rhash.hash(user.id) == server_tag && user.connected_at\n      end.shuffle.first\n\n      # If we found a user, schedule a tracer email.\n      if user\n        user.reload\n        ScheduleTracerEmails.new(user, self.num_tracers).delay.run\n      end\n\n      light_sleep self.tracer_interval\n    end\n  rescue Exception => e\n    Log.exception(e)\n    raise e\n  ensure\n    Log.info(\"Stopping tracer thread.\")\n  end\n\n  # Private: Construct and return user thread options.\n  def user_options\n    @user_options ||= {\n      :max_email_size => self.max_email_size\n    }\n  end\n\n  # Private: Create a new user thread for the specified user.\n  #\n  # options[:user_id] - The user id.\n  def action_connect_user(options)\n    user_id = options[:user_id]\n\n    # Nothing to do if stopped.\n    return if stopping?\n\n    # Are we allowed to create a new user thread?\n    if user_threads_count > max_user_threads\n      Log.error(\"Error: Reached maximum number of users (#{max_user_threads}).\")\n      return\n    end\n\n    # Nothing to do if already a running (or sleeping) thread.\n    user_thread = get_user_thread(user_id)\n    return if user_thread.present? && user_thread.alive?\n\n    # Load the user; preload connection information.\n    user = User.find(user_id)\n    user.connection.imap_provider\n\n    # Start the thread.\n    user_thread = wrapped_thread do\n      Log.info(\"Connecting #{user.email}...\")\n      ImapClient::UserThread.new(self, user, user_options).run\n    end\n    set_user_thread(user_id, user_thread)\n  rescue => e\n    Log.exception(e)\n  end\n\n  # Private: Disconnect a user and destroy the user thread.\n  #\n  # options[:user_id] - The user id.\n  def action_disconnect_user(options)\n    # Nothing to do if no thread.\n    user_id = options[:user_id]\n    return if get_user_thread(user_id).nil?\n\n    # Tell the thread to stop.\n    thread = delete_user_thread(user_id)\n    thread.terminate\n  rescue => e\n    Log.exception(e)\n  end\n\n  # Private: Stop and disconnect all user threads.\n  def terminate_user_threads\n    # Terminate all threads, ignore exceptions.\n    walk_user_threads do |user_id, user_thread|\n      user_thread.terminate rescue nil\n    end\n\n    # Wait for all threads to finish.\n    walk_user_threads do |user_id, user_thread|\n      user_thread.join if user_thread.alive?\n    end\n  end\n\n  # Private: Run a function, then restart a user thread.\n  #\n  # See UserThread#schedule for more details.\n  #\n  # options[:block] - The block to run.\n  # options[:thread] - The thread to restart.\n  def action_callback(options)\n    # Wait until the calling thread goes to sleep.\n    while options[:thread].status == \"run\"\n      sleep 0.1\n    end\n\n    # Run the block.\n    if options[:thread].status == \"sleep\"\n      # Call the callback.\n      options[:block].call\n    end\n  rescue => e\n    Log.exception(e)\n  ensure\n    # Wake up the thread.\n    if options[:thread].status == \"sleep\"\n      options[:thread].run\n    end\n  end\n\n  # Private.\n  def maybe_start_profiling\n    return unless enable_profiler\n    Log.info(\"Starting profiler...\")\n    require 'ruby-prof'\n    RubyProf.start\n  end\n\n  # Private.\n  def stop_profiling\n    return unless enable_profiler\n    Log.info(\"Stopping profiler...\")\n    result = RubyProf.stop\n    printer = RubyProf::CallStackPrinter.new(result)\n    File.open(\"./tmp/profile.html\", 'w') do |file|\n      printer.print(file)\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_client/process_uid.rb",
    "content": "# Private: Read and act on a single email. This is one place where\n# Ruby support for monads would be useful. The challenge is that we\n# have to verify a lot of data in a very specific sequence, and at any\n# time we could either abort (ie: skip the remaining operations) or\n# raise an exception.\n#\n# We build something similar by creating a 'Maybe' control structure\n# where we submit blocks of code to an object. A block is considered\n# successful if it returns true and doesn't throw any exceptions. If a\n# block is not successful, we skip the remaining blocks.\n#\n# Note that every database touch is wrapped in a call to\n# `user_thread.schedule(&block)`. This allows us to avoid creating a\n# separate database connection for each user thread.\nclass ProcessUid\n  attr_accessor :user_thread, :uid\n  attr_accessor :internal_date, :message_size\n  attr_accessor :raw_eml, :envelope\n  attr_accessor :message_id, :sha1\n  attr_accessor :mail_log\n\n  def initialize(user_thread, uid)\n    self.user_thread = user_thread\n    self.uid = uid\n  end\n\n  # Public: Process the email.\n  def run\n    # Run all the steps below. Stop as soon as one of them returns\n    # false or throws an error.\n    true &&\n      fetch_internal_date_and_size  &&\n      check_for_really_old_internal_date  &&\n      check_for_pre_creation_internal_date  &&\n      check_for_relapsed_internal_date  &&\n      check_for_big_messages  &&\n      fetch_uid_envelope_rfc822  &&\n      update_user_mark_email_processed  &&\n      handle_tracer_email  &&\n      check_for_duplicate_message_id  &&\n      check_for_duplicate_sha1  &&\n      create_mail_log  &&\n      deploy_webhook  &&\n      update_daemon_stats\n  ensure\n    clean_up\n  end\n\n  # Private: The User model.\n  def user\n    user_thread.user\n  end\n\n  # Private: The IMAP client instance.\n  def client\n    user_thread.client\n  end\n\n  # Private: The imap_client daemon.\n  def daemon\n    user_thread.daemon\n  end\n\n  private\n\n  def confirm_tracer(tracer_uid)\n    user_thread.schedule do\n      tracer = TracerLog.find_by_uid(tracer_uid) || TracerLog.new(:uid => tracer_uid)\n      tracer.update_attributes!(:detected_at => Time.now)\n    end\n  end\n\n  def fetch_internal_date_and_size\n    responses = Timeout::timeout(30) do\n      client.uid_fetch([uid], [\"INTERNALDATE\", \"RFC822.SIZE\"])\n    end\n    response = responses && responses.first\n\n    # If there was no response, then skip this message.\n    if response.nil?\n      user_thread.update_user(:last_uid => uid)\n      return false\n    end\n\n    # Save the internal_date and message_size for later.\n    self.internal_date = Time.parse(response.attr[\"INTERNALDATE\"])\n    self.message_size  = (response.attr[\"RFC822.SIZE\"] || 0).to_i\n\n    return true\n  rescue Timeout::Error => e\n    # If this email triggered a timeout, then skip it.\n    user_thread.update_user(:last_uid => uid)\n    raise e\n  end\n\n  # Private: Check for a really old date. If it's old, then we should\n  # stop counting on our UID knowledge and go back to loading UIDs by\n  # date.\n  def check_for_really_old_internal_date\n    if internal_date < 4.days.ago\n      Log.librato(:count, \"system.process_uid.really_old_internal_date\", 1)\n      user_thread.update_user(:last_uid => nil, :last_uid_validity => nil)\n      user_thread.stop!\n      return false\n    else\n      return true\n    end\n  end\n\n  # Private: Don't process emails that arrived before this user was\n  # created.\n  def check_for_pre_creation_internal_date\n    if internal_date < user.created_at\n      Log.librato(:count, \"system.process_uid.pre_creation_internal_date\", 1)\n      user_thread.update_user(:last_uid => uid)\n      return false\n    else\n      return true\n    end\n  end\n\n  # Private: Don't process emails that are significantly older than\n  # the last internal date that we've processed.\n  def check_for_relapsed_internal_date\n    if user.last_internal_date && internal_date < (user.last_internal_date - 1.hour)\n      Log.librato(:count, \"system.process_uid.relapsed_internal_date\", 1)\n      user_thread.update_user(:last_uid => uid)\n      return false\n    else\n      return true\n    end\n  end\n\n  # Private: Skip emails that are too big.\n  def check_for_big_messages\n    if message_size > user_thread.options[:max_email_size]\n      Log.librato(:count, \"system.process_uid.big_message\", 1)\n      user_thread.update_user(:last_uid => uid)\n      return false\n    else\n      return true\n    end\n  end\n\n  def fetch_uid_envelope_rfc822\n    # Load the email body.\n    responses = Timeout::timeout(30) do\n      self.client.uid_fetch([uid], [\"UID\", \"ENVELOPE\", \"RFC822\"])\n    end\n    response = responses && responses.first\n\n    # If there was no response, then skip this message.\n    if response.nil?\n      Log.librato(:count, \"system.process_uid.uid_fetch_no_response\", 1)\n      user_thread.update_user(:last_uid => uid)\n      return false\n    end\n\n    # Save the internal_date and message_size for later.\n    self.uid        = response.attr[\"UID\"]\n    self.raw_eml    = to_utf8(response.attr[\"RFC822\"])\n    self.envelope   = response.attr[\"ENVELOPE\"]\n    self.message_id = (envelope.message_id || \"#{user.email} - #{uid} - #{internal_date}\").slice(0, 255)\n\n    return true\n  rescue Timeout::Error => e\n    # If this email triggered a timeout, then skip it.\n    user_thread.update_user(:last_uid => uid)\n    raise e\n  end\n\n  # Private: Update the high-water mark for which emails we've\n  # processed.\n  def update_user_mark_email_processed\n    # Ignore any suspicious looking internal dates. Sometimes\n    # misconfigured email servers means that email arrives from the\n    # future.\n    if internal_date > Time.now\n      Log.librato(:count, \"system.process_uid.fix_suspicious_internal_date\", 1)\n      self.internal_date = user.last_internal_date\n    end\n\n    # Update the user.\n    user_thread.update_user(:last_uid           => uid,\n                            :last_email_at      => Time.now,\n                            :last_internal_date => internal_date)\n    return true\n  end\n\n  # Private: Is this a tracer? If so, update the TracerLog and stop\n  # processing.\n  def handle_tracer_email\n    if m = /^TRACER: (.+)$/.match(envelope.subject)\n      tracer_uid = m[1]\n      confirm_tracer(tracer_uid)\n      user_thread.update_user(:last_uid => uid)\n      daemon.total_emails_processed += 1\n      return false\n    else\n      return true\n    end\n  end\n\n  # Private: Have we already processed this message_id?\n  def check_for_duplicate_message_id\n    old_mail_log = nil\n    user_thread.schedule do\n      old_mail_log = user.mail_logs.find_by_message_id(message_id)\n    end\n\n    if old_mail_log\n      Log.librato(:count, \"system.process_uid.duplicate_message_id\", 1)\n      return false\n    else\n      return true\n    end\n  end\n\n  # Private: Have we already processed this sha1 hash? This helps us\n  # catch rare cases where an email doesn't have a message_id so we\n  # make one up, so the message_id is unique, but the email is a\n  # duplicate. This may be unnecessary.\n  def check_for_duplicate_sha1\n    # Generate the SHA1.\n    self.sha1 = Digest::SHA1.hexdigest(raw_eml)\n\n    old_mail_log = nil\n    user_thread.schedule do\n      old_mail_log = user.mail_logs.find_by_sha1(sha1)\n    end\n\n    if old_mail_log\n      Log.librato(:count, \"system.process_uid.duplicate_sha1\", 1)\n      return false\n    else\n      return true\n    end\n  end\n\n  # Private: Log the mail.\n  def create_mail_log\n    user_thread.schedule do\n      self.mail_log = user.mail_logs.create(:message_id => message_id, :sha1 => sha1)\n    end\n    return true\n  end\n\n  # Private: Deploy the web hook.\n  def deploy_webhook\n    unless daemon.stress_test_mode\n      user_thread.schedule do\n        CallNewMailWebhook.new(mail_log, envelope, raw_eml).delay.run\n      end\n    end\n    return true\n  end\n\n  # Private: Update stats\n  def update_daemon_stats\n    daemon.clear_error_count(user.id)\n    daemon.processed_log &&\n      daemon.processed_log.log(Time.now, user.email, message_id)\n    daemon.total_emails_processed += 1\n    return true\n  end\n\n  # Private: Help the garbage collector know what it can collect.\n  def clean_up\n    self.user_thread = nil\n    self.uid = nil\n    self.internal_date = nil\n    self.raw_eml = nil\n    self.envelope = nil\n    self.message_id = nil\n    self.sha1 = nil\n    self.mail_log = nil\n  end\n\n  # Private: Convert a string UTF-8 format.\n  def to_utf8(s)\n    return nil if s.nil?\n\n    # Attempt to politely transcode the string.\n    s.encode(\"UTF-8\").scrub\n  rescue\n    # If that doesn't work, then overwrite the existing encoding and\n    # clobber any strange characters.\n    s.force_encoding(\"UTF-8\").scrub\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_client/rendezvous_hash.rb",
    "content": "# http://en.wikipedia.org/wiki/Rendezvous_hashing\nclass ImapClient::RendezvousHash\n  attr_accessor :lock\n\n  def initialize\n    @site_tags = []\n    @lock = Mutex.new\n  end\n\n  def site_tags=(site_tags)\n    lock.synchronize do\n      @site_tags = site_tags\n    end\n  end\n\n  # Return the number of sites.\n  def size\n    lock.synchronize do\n      return @site_tags.length\n    end\n  end\n\n  # Return the highest priority item.\n  def hash(object_tag)\n    hashes = self.lock.synchronize do\n      @site_tags.map do |site_tag|\n        h = Digest::SHA1.hexdigest(\"#{site_tag} - #{object_tag}\")\n        [h, site_tag]\n      end\n    end\n\n    priority = hashes.sort\n\n    if priority.length > 0\n      priority[0][1]\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_client/user_thread.rb",
    "content": "#  ImapClient::UserThread - Manages the interactions of a single user\n#  against an IMAP server. Written in a \"crash-only\" style. If\n#  something goes wrong, we tear down the whole thread and start from\n#  scratch.\n#\n#  The basic lifecycle is:\n#\n#  + Connects to the server.\n#  + Catch up on email we may have missed.\n#  + Go into IMAP IDLE mode.\n#  + Pop out of IDLE mode, catch up on emails.\n#  + Repeat until we get a \"terminate\" signal.\n#  + When terminated, or on error, disconnect ourselves.\n\nrequire 'net/imap'\nrequire 'timeout'\n\nclass ImapClient::UserThread\n  include Common::LightSleep\n  include Common::Stoppable\n\n  attr_accessor :daemon, :options\n  attr_accessor :user, :client, :folder_name\n  attr_accessor :uid_validity\n\n  def initialize(daemon, user, options)\n    init_stoppable\n    self.daemon = daemon\n    self.user = user\n    self.options = options\n  end\n\n  # Private: Update a user record in a scheduled way.\n  def update_user(hash)\n    schedule do\n      if !user.update_attributes(hash)\n        Log.error(\"Could not update #{user.email} - #{user.errors.to_h}\")\n        stop!\n      end\n    end\n  end\n\n  def run\n    delay_start\n    connect             if running?\n    authenticate        if running?\n    choose_folder       if running?\n    update_uid_validity if running?\n    main_loop           if running?\n  rescue => e\n    log_exception(e)\n    stat_exception(e)\n    self.daemon.increment_error_count(user.id)\n    stop!\n  ensure\n    stop!\n    daemon.schedule_work(:disconnect_user, :hash => user.id, :user_id => user.id)\n    disconnect\n    Log.info(\"Disconnected #{user.email}.\")\n    clean_up\n  end\n\n  # Private: Schedule a block of code to run in a worker thread\n  # (rather than a user thread).\n  #\n  # We do this in order to prevent ourselves from using too many\n  # database connections, exhausting memory, and redlining the CPU at\n  # startup or at times of lots of email activity. This helps smooth\n  # out the load.\n  #\n  # Without this, we would have all the user threads maintaining\n  # separate database connections and trying to crunch through emails\n  # as quickly as possible at the same time.\n  def schedule(&block)\n    # Schedule the block to run on a worker thread, and put ourselves to sleep.\n    daemon.schedule_work(:callback,\n                         :hash    => user.id,\n                         :user_id => user.id,\n                         :block   => block,\n                         :thread  => Thread.current)\n\n    # Put ourselves to sleep. The worker will call Thread.run to wake us back up.\n    sleep\n  end\n\n  # Private: Log exceptions. Be less verbose if we're stress testing.\n  def log_exception(e)\n    imap_exceptions = [\n      Net::IMAP::Error,\n      Net::IMAP::ResponseParseError,\n      IOError,\n      EOFError,\n      Errno::EPIPE\n    ]\n\n    # Minimally log imap exceptions when stress testing.\n    if imap_exceptions.include?(e.class) && self.daemon.stress_test_mode\n      Log.info(\"#{e.class} - #{e.to_s}\")\n    else\n      Log.info(\"Encountered error for #{user.email}: #{e.class} - #{e.to_s}\")\n      Log.exception(e)\n    end\n  end\n\n  # Private: Log operations metrics. Be less verbose if we're stress testing.\n  def stat_exception(e)\n    return if self.daemon.stress_test_mode\n    category = \"error.\" + e.class.to_s.gsub(\"::\", \"_\")\n    Log.librato(:count, category, 1)\n  end\n\n  private unless Rails.env.test?\n\n  # Private: Exponentially backoff based on the number of errors we\n  # are seeing for a given user. At most, wait 5 minutes before trying\n  # to connect.\n  def delay_start\n    errors  = self.daemon.get_error_count(user.id)\n    seconds = (errors ** 3) - 1\n    seconds = [seconds, 300].min\n    Log.librato(:measure, 'user_thread.delayed_start', seconds) if seconds > 0\n    light_sleep seconds\n  end\n\n  # Private: Connect to the server, set the client.\n  def connect\n    conn_type = user.imap_provider\n    self.client = Net::IMAP.new(conn_type.imap_host,\n                                :port => conn_type.imap_port,\n                                :ssl  => conn_type.imap_use_ssl)\n  end\n\n  # Private: Authenticate a user to the server.\n  def authenticate\n    user.connection.imap_provider.authenticate_imap(client, user)\n    update_user(:last_login_at => Time.now)\n  rescue OAuth::Error,\n         Net::IMAP::NoResponseError,\n         Net::IMAP::ByeResponseError,\n         OAuth2::Error => e\n    # If we encounter an OAuth error during authentication, then the\n    # credentials are probably invalid. We don't want to log every\n    # occurrance of this, and we don't want to archive the user, so\n    # we'll just back off from reconnecting again.\n    stat_exception(e)\n    Log.info(\"Encountered error for #{user.email}: #{e.class} - #{e.to_s}\")\n    self.daemon.increment_error_count(user.id)\n    stop!\n  end\n\n  # Private: Fetch a list of folders, choose the first one that looks\n  # promising.\n  def choose_folder\n    # TODO: This should probably live in the imap_provider model.\n    best_folders = [\n      \"[Gmail]/All Mail\",\n      \"[Google Mail]/All Mail\",\n      \"INBOX\"\n    ]\n\n    # Discover the folder.\n    client.list(\"\", \"*\").each do |folder|\n      if best_folders.include?(folder.name)\n        self.folder_name = folder.name\n        break\n      end\n    end\n\n    # Examine the folder.\n    client.examine(folder_name)\n  end\n\n  # Private: Return true if our knowledge of the server's uid is still\n  # valid. See \"http://tools.ietf.org/html/rfc4549#section-4.1\"\n  def update_uid_validity\n    # Get the latest validity value.\n    response = client.status(folder_name.to_s, attrs=['UIDVALIDITY'])\n    self.uid_validity = response['UIDVALIDITY']\n\n    if user.last_uid_validity.to_s != self.uid_validity.to_s\n      # Update the user with the new validity value, invalidate the\n      # old last_uid value.\n      update_user(:last_uid_validity => self.uid_validity, :last_uid => nil)\n    end\n  end\n\n  # Private: Start a loop that alternates between idling and reading\n  # email.\n  def main_loop\n    while running?\n      verify_uid_validity if running?\n      jumpstart_stalled_account if running?\n\n      # Read emails until we have read everything there is to\n      # read. Then go into idle mode.\n      last_read_count = 9999\n      while running? && last_read_count > 0\n        if user.last_uid.present?\n          last_read_count = read_email_by_uid\n        else\n          last_read_count = read_email_by_date\n        end\n      end\n\n      wait_for_email if running?\n    end\n  end\n\n  # Private: Stop if the uid_validity was changed by someone else.\n  #\n  # Because SuperIMAP tries to avoid locks, there is a chance that two\n  # machines in a cluster may briefly own the same user. If this\n  # happens and the server manages to change the UIDVALIDITY settings,\n  # then there is a chance that one server could change the\n  # `uid_validity` attribute, and the other server could set the\n  # `last_uid` attribute. This would put the user out of sync, we\n  # would begin querying for UIDS that no longer exist, and we'd miss\n  # emails.\n  #\n  # To work around this, we refresh the user object and make sure that\n  # the `uid_validity` field hasn't changed from what we know it to\n  # be. If it has, then we'll stop this instance of the thread.\n  def verify_uid_validity\n    schedule do\n      user.reload\n    end\n\n    stop! if self.uid_validity.present? && (self.uid_validity.to_s != user.last_uid_validity.to_s)\n  end\n\n  # Private: Check for accounts that haven't had an email in 24 hours.\n  # When this happens, start reading emails by date, not UID. This\n  # hopefully guards against accounts getting into a weird state and\n  # getting locked.\n  def jumpstart_stalled_account\n    if user.last_email_at && user.last_email_at < 24.hours.ago\n      update_user(:last_uid => nil)\n    end\n  end\n\n  # Private: Search for new email by uid. See\n  # \"https://tools.ietf.org/html/rfc3501#section-2.3.1.1\"e\n  #\n  # Returns the number of emails read.\n  def read_email_by_uid\n    # Read in batches of 100 emails.\n    batch_size = 100\n    uids = client.uid_search([\"UID\", \"#{user.last_uid + 1}:#{user.last_uid + batch_size}\"])\n\n    uids.each do |uid|\n      break if stopping?\n      process_uid(uid) unless stopping?\n    end\n\n    return uids.count\n  end\n\n  # Private: Search for new email by date. See\n  # \"https://tools.ietf.org/html/rfc3501#section-6.4.4\"\n  #\n  # Returns the number of uids read.\n  def read_email_by_date\n    # Search by date. Unfortunately, IMAP date searching isn't very\n    # granular. To ensure we get all emails we go back two full\n    # days. We filter out duplicates later.\n    date_string = 2.days.ago.strftime(\"%d-%b-%Y\")\n    uids = client.uid_search([\"SINCE\", date_string])\n    uids.each do |uid|\n      break if stopping?\n      process_uid(uid) unless stopping?\n    end\n\n    return uids.count\n  end\n\n  # Private: Put the connection into idle mode, exit when we receive a\n  # new EXISTS message.\n  # See \"https://tools.ietf.org/html/rfc3501#section-7.3.1\"\n  def wait_for_email\n    client.idle do |response|\n      if response &&\n         response.respond_to?(:name) &&\n         response.name == \"EXISTS\"\n        client.idle_done()\n      elsif stopping?\n        client.idle_done()\n      end\n    end\n  rescue Net::IMAP::Error,\n         EOFError => e\n    # Recover gracefully.\n    stat_exception(e)\n    Log.info(\"Encountered error for #{user.email}: #{e.class} - #{e.to_s}\")\n    self.daemon.increment_error_count(user.id)\n    stop!\n  end\n\n  # Private: Read and act on a single email. Calls the ProcessUid\n  # interactor.\n  #\n  # + uid - The UID of the email.\n  def process_uid(uid)\n    ProcessUid.new(self, uid).run\n  rescue Timeout::Error => e\n    # Recover gracefully.\n    stat_exception(e)\n    Log.info(\"Encountered error for #{user.email}: #{e.class} - #{e.to_s}\")\n    self.daemon.increment_error_count(user.id)\n    stop!\n  end\n\n  # Private: Logout the user, disconnect the client.\n  def disconnect\n    begin\n      client && client.logout\n    rescue => e\n      # Ignore errors.\n    end\n\n    begin\n      client && client.disconnect\n    rescue => e\n      # Ignore errors.\n    end\n\n    # The client is no longer connected.\n    self.client = nil\n  end\n\n  # Private: Help the garbage collector know what it can collect.\n  def clean_up\n    self.daemon = nil\n    self.user = nil\n    self.client = nil\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_client.rb",
    "content": "class ImapClient\n  VERSION=\"1.0.0\"\nend\n\nrequire 'imap_client/rendezvous_hash'\nrequire 'imap_client/process_uid'\nrequire 'imap_client/user_thread'\nrequire 'imap_client/daemon'\n"
  },
  {
    "path": "app/processes/imap_test_server/daemon.rb",
    "content": "#  ImapTestServer::Daemon - A test IMAP server that can respond to all\n#  calls made by the ImapClient process. Generates test data and\n#  (muhahaha) deliberately responds to some calls with gibberish in\n#  order to test how well ImapClient recovers.\n#\n#  The daemon has three threads:\n#  + The Connection thread listens for incoming connections.\n#  + The New Mail thread generates new emails to users.\n#  + The Process Sockets (main) thread sits in a tight loop, sending and receiving IMAP commands.\n#\n#  The code is organized as follows:\n#\n#  + The Daemon class contains high level connection logic.\n#  + SocketState holds the state of a socket and contains our IMAP logic.\n#  + Mailboxes holds mail for all users.\n\nrequire 'socket'\n\nclass ImapTestServer::Daemon\n  include Common::Stoppable\n  include Common::LightSleep\n  include Common::WrappedThread\n  include Common::DbConnection\n\n  attr_accessor :port, :enable_chaos, :emails_per_minute, :length_of_test\n  attr_accessor :stats_thread\n  attr_accessor :connection_thread\n  attr_accessor :new_sockets, :sockets, :socket_states\n  attr_accessor :mailboxes\n  attr_accessor :total_emails_generated, :total_emails_fetched\n  attr_accessor :generated_log, :fetched_log, :events_log\n\n  def initialize(options = {})\n    # Initialize mixins.\n    init_stoppable\n\n    # Config stuff.\n    self.port              = options.fetch(:port)\n    self.enable_chaos      = options.fetch(:enable_chaos)\n    self.emails_per_minute = options.fetch(:emails_per_minute)\n    self.length_of_test    = options.fetch(:length_of_test)\n\n    # Socket stuff.\n    self.new_sockets   = Queue.new\n    self.sockets       = []\n    self.socket_states = {}\n\n    # Mailboxes.\n    self.mailboxes = Mailboxes.new()\n\n    # Stats.\n    self.total_emails_generated = 0\n    self.total_emails_fetched   = 0\n  end\n\n  # Public: Start threads and begin servicing connections.\n  def run\n    trap_signals\n\n    self.generated_log = Common::CsvLog.new(\"./log/stress/generated_emails.csv\")\n    self.fetched_log = Common::CsvLog.new(\"./log/stress/fetched_emails.csv\")\n    self.events_log = Common::CsvLog.new(\"./log/stress/events.csv\")\n\n    start_stats_thread\n    start_connection_thread\n    start_new_mail_thread\n    start_process_sockets_thread\n\n    stop_time = self.length_of_test.minutes.from_now\n    while running?\n      if Time.now > stop_time\n        Log.info(\"Test finished! Shutting down.\")\n        stop!\n      end\n      light_sleep 1.0\n    end\n  rescue => e\n    stop!\n    Log.exception(e)\n    raise e\n  ensure\n    stop!\n    connection_thread && connection_thread.terminate\n    sockets.map(&:close)\n    self.generated_log.stop!\n    self.fetched_log.stop!\n    self.events_log.stop!\n    Log.info(\"Generated #{total_emails_generated} emails.\")\n    Log.info(\"Served #{total_emails_fetched} emails.\")\n  end\n\n\n  private\n\n\n  def start_stats_thread\n    self.stats_thread = wrapped_thread do\n      stats_thread_runner\n    end\n  end\n\n  def start_connection_thread\n    self.connection_thread = wrapped_thread do\n      connection_thread_runner\n    end\n  end\n\n  def start_new_mail_thread\n    self.connection_thread = wrapped_thread do\n      new_mail_thread_runner\n    end\n  end\n\n  def stats_thread_runner\n    while running?\n      Log.info(\"Stats (connections = #{sockets.count}, emails_generated = #{total_emails_generated}, emails_fetched = #{total_emails_fetched})\")\n      light_sleep 10\n    end\n  end\n\n  # Private: Accepts incoming connections.\n  def connection_thread_runner\n    Log.info(\"Waiting for connections on port 0.0.0.0:#{port}.\")\n    server = TCPServer.new(\"0.0.0.0\", port)\n    while running?\n      begin\n        socket = server.accept\n        new_sockets << socket\n      rescue IO::EAGAINWaitReadable\n        sleep 0.2\n      rescue => e\n        Log.exception(e)\n      end\n    end\n  rescue => e\n    Log.exception(e)\n  end\n\n  # Private: Sends and receives IMAP commands.\n  def start_process_sockets_thread\n    wrapped_thread do\n      process_sockets_runner\n    end\n  end\n\n  def process_sockets_runner\n    while running?\n      process_new_sockets\n      process_incoming_messages\n      send_exists_messages\n      sleep 0.1\n    end\n  end\n\n  def process_new_sockets\n    while running? && !new_sockets.empty?\n      socket = new_sockets.pop(true)\n      process_new_socket(socket)\n    end\n  end\n\n  def process_new_socket(socket)\n    options = {\n      :enable_chaos => self.enable_chaos\n    }\n    socket_state = ImapTestServer::SocketState.new(self, socket, options)\n    socket_state.handle_connect\n\n    # Add to our list of existing sockets.\n    self.sockets << socket\n    self.socket_states[socket.hash] = socket_state\n  rescue => e\n    Log.exception(e)\n    close_socket(socket)\n  end\n\n  def process_incoming_messages\n    # Which sockets need attention?\n    response = IO.select(sockets, [], [], 0)\n    return if response.nil?\n\n    # Attend to the sockets.\n    read_sockets, _, _ = response\n    read_sockets.each do |socket|\n      process_incoming_message(socket)\n    end\n  end\n\n  def process_incoming_message(socket)\n    command = socket.gets\n    if command.present?\n      socket_state = socket_states[socket.hash]\n      socket_state.handle_command(command)\n    else\n      close_socket(socket)\n    end\n  rescue ImapTestServer::SocketState::NormalDisconnect => e\n    close_socket(socket)\n  rescue ImapTestServer::SocketState::ChaosDisconnect => e\n    close_socket(socket)\n  rescue => e\n    Log.exception(e)\n    close_socket(socket)\n  end\n\n  def send_exists_messages\n    socket_states.values.each do |socket_state|\n      send_exists_message(socket_state)\n    end\n  end\n\n  def send_exists_message(socket_state)\n    socket_state.send_exists_messages\n  rescue => e\n    Log.exception(e)\n    close_socket(socket_state.socket)\n  end\n\n  def close_socket(socket)\n    sockets.delete(socket)\n    socket_states.delete(socket.hash)\n    socket.close()\n  rescue => e\n    Log.exception(e)\n  end\n\n  def new_mail_thread_runner\n    sleep_seconds = 1\n\n    while running?\n      if self.mailboxes.count > 0\n        n = (1.0 * sleep_seconds / 60) * emails_per_minute\n        generate_new_mail(n)\n      end\n      light_sleep sleep_seconds\n    end\n  end\n\n  def generate_new_mail(n)\n    # What's our chance of generating an email for an individual user?\n    prob_of_email = n / self.mailboxes.count\n    self.mailboxes.each do |mailbox|\n      if rand() < prob_of_email\n        self.total_emails_generated += 1\n        mailbox.add_fake_message do |message_id|\n          self.generated_log.log(Time.now, mailbox.username, message_id)\n        end\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_test_server/mailboxes.rb",
    "content": "class ImapTestServer::Mailboxes\n  attr_accessor :mailboxes, :mailboxes_mutex\n\n  def initialize(options = {})\n    self.mailboxes = {}\n    self.mailboxes_mutex = Mutex.new\n  end\n\n  def count\n    return self.mailboxes.count\n  end\n\n  def find(username)\n    self.mailboxes_mutex.synchronize do\n      self.mailboxes[username] ||= Mailbox.new(username)\n    end\n  end\n\n  def each(&block)\n    usernames = self.mailboxes_mutex.synchronize do\n      self.mailboxes.keys.dup\n    end\n\n    usernames.each do |username|\n      yield mailboxes[username]\n    end\n  end\n\n  private\n\n  class Mailbox\n    attr_accessor :username\n    attr_accessor :last_uid, :mails\n    MailStruct = Struct.new(:uid, :date, :message_id)\n\n    def initialize(username)\n      self.username = username\n      self.last_uid = rand(999999)\n      self.mails = []\n    end\n\n    def count\n      return mails.length\n    end\n\n    def add_fake_message\n      self.last_uid += 1\n      message_id = \"message-#{username}-#{last_uid}-#{rand(999999)}@localhost\"\n      self.mails << MailStruct.new(last_uid, Time.now, message_id)\n      yield(message_id)\n    end\n\n    def uid_search(from_uid, to_uid)\n      mails.select do |mail|\n        mail.uid >= from_uid && mail.uid <= to_uid\n      end.map(&:uid)\n    end\n\n    def date_search(since_date)\n      mails.select do |mail|\n        mail.date > since_date\n      end.map(&:uid)\n    end\n\n    def fetch(uid)\n      email = self.username\n      mail = mails.find do |mail|\n        mail.uid == uid\n      end\n\n      Mail.new do\n        from email\n        to email\n        date mail.date\n        message_id mail.message_id\n        subject \"MySubject\"\n        body \"MyBody\"\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_test_server/socket_state.rb",
    "content": "require 'date'\n\nclass ImapTestServer::SocketState\n  NormalDisconnect = Class.new(StandardError)\n  ChaosDisconnect = Class.new(StandardError)\n\n  attr_accessor :daemon, :mailbox, :socket\n  attr_accessor :enable_chaos\n  attr_accessor :username\n  attr_accessor :uid_validity\n  attr_accessor :last_count\n  attr_accessor :idling, :idle_tag\n  attr_accessor :new_email, :inbox\n\n  def initialize(daemon, socket, options)\n    self.daemon = daemon\n    self.socket = socket\n    self.enable_chaos = options[:enable_chaos]\n    self.uid_validity = rand(999)\n    self.idling = false\n    self.last_count = 0\n  end\n\n  # Public: Return true if we are idling.\n  def idling?\n    self.idling\n  end\n\n  # Public: Greet the new connection.\n  def handle_connect()\n    handle_command(\"TAG HELLO\")\n  end\n\n  # Public: Handle the specified IMAP command, respond to the socket.\n  def handle_command(s)\n    tag, verb, args = parse_command(s)\n    method = verb_to_method(verb)\n    self.daemon.events_log.log(Time.now, username, method)\n    send(method, tag, args)\n  end\n\n  def send_exists_messages\n    if self.mailbox && self.last_count < self.mailbox.count\n      respond(\"*\", \"#{self.mailbox.count} EXISTS\")\n      self.last_count = mailbox.count\n    end\n  end\n\n  private\n\n  def parse_command(s)\n    # Get the tag.\n    tag, s = /(.+?)\\s+(.*)/.match(s).captures\n\n    # Special case for an IDLE done command.\n    return [nil, \"DONE\", []] if tag == \"DONE\"\n\n    # Parse the rest of the command.\n    verb, s = /(UID SEARCH|UID FETCH|\\w+)\\s*(.*)/.match(s).captures\n    args = s.split(/\\s+/)\n    [tag, verb, args]\n  end\n\n  # Private: Given an IMAP verb, return a method. This is our chance\n  # to inject some chaos into the system. (Muhahaha.)\n  def verb_to_method(verb)\n    verb = verb.downcase.gsub(/\\s/, \"_\")\n    choices = [[400, \"imap_#{verb}\".to_sym]]\n\n    if self.enable_chaos\n      choices += [\n        [3,  \"imap_#{verb}_chaos\".to_sym],\n        [1,  :imap_chaos_respond_no],\n        [1,  :imap_chaos_respond_bad],\n        [1,  :imap_chaos_gibberish_tagged],\n        [1,  :imap_chaos_gibberish_untagged],\n        [1,  :imap_chaos_soft_disconnect],\n        [1,  :imap_chaos_hard_disconnect],\n      ]\n    end\n\n    choose(choices)\n  end\n\n  # Private: Choose from a list of weighted choices, of the form\n  # [[weight1, choice1], [weight2, choice2], ...]. Weights are\n  # normalized, they do not need to add to 1.0.\n  #\n  # Returns the selected choice.\n  def choose(choices)\n    r = rand()\n    w = 0\n    total_weight = choices.map(&:first).inject(&:+)\n    choices.each do |weight, choice|\n      w += (1.0 * weight / total_weight)\n      return choice if r <= w\n    end\n  end\n\n  # Private: Write a response to the socket.\n  def respond(tag, s)\n    socket.write(\"#{tag} #{s}\\r\\n\")\n    socket.flush\n  end\n\n  # CONNECT\n\n  def imap_hello(tag, args)\n    respond(\"*\", \"OK ImapTestServer ready.\")\n  end\n\n  def imap_hello_chaos(tag, args)\n    respond(\"*\", \"ERROR Not ready.\")\n  end\n\n  # LOGIN Command\n  # https://tools.ietf.org/html/rfc3501#section-6.2.3\n\n  def imap_login(tag, args)\n    self.username = args[0]\n    self.mailbox = self.daemon.mailboxes.find(username)\n    respond(tag, \"OK Logged in.\")\n  end\n\n  def imap_login_chaos(tag, args)\n    respond(tag, \"NO\")\n  end\n\n  # LIST Command\n  # https://tools.ietf.org/html/rfc3501#section-6.3.8\n\n  def imap_list(tag, args)\n    respond(\"*\", %(LIST (\\HasNoChildren) \".\" \"INBOX\"))\n    respond(\"*\", %(LIST (\\HasNoChildren) \".\" \"FOLDER1\"))\n    respond(\"*\", %(LIST (\\HasNoChildren) \".\" \"FOLDER2\"))\n    respond(tag, \"OK LIST Completed\")\n  end\n\n  def imap_list_chaos(tag, args)\n    respond(\"*\", %(LIST (\\HasNoChildren) \".\" \"FOLDER1\"))\n    respond(\"*\", %(LIST (\\HasNoChildren) \".\" \"FOLDER2\"))\n    respond(tag, \"OK LIST Completed\")\n  end\n\n  # EXAMINE Command\n  # https://tools.ietf.org/html/rfc3501#section-6.3.2\n\n  def imap_examine(tag, args)\n    respond(\"*\", %(FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)))\n    respond(\"*\", %(OK [PERMANENTFLAGS ()] Read-only mailbox.))\n    respond(\"*\", %(#{mailbox.count} EXISTS))\n    respond(\"*\", %(OK [UIDVALIDITY #{uid_validity}] UIDs valid))\n    respond(tag, %(OK [READ-ONLY] Select completed.))\n  end\n\n  def imap_examine_chaos(tag, args)\n    self.uid_validity = rand(999)\n    imap_examine(tag, args)\n  end\n\n  # STATUS Command\n  # https://tools.ietf.org/html/rfc3501#section-6.3.10\n\n  def imap_status(tag, args)\n    mailbox_name = args[0]\n    respond(\"*\", %(STATUS #{mailbox_name} (UIDVALIDITY #{uid_validity})))\n    respond(tag, %(OK STATUS completed))\n  end\n\n  def imap_status_chaos(tag, args)\n    self.uid_validity = rand(999)\n    imap_status(tag, args)\n  end\n\n  # UID SEARCH Command\n  # https://tools.ietf.org/html/rfc3501#section-6.4.4\n\n  def imap_uid_search(tag, args)\n    if args.index(\"UID\")\n      imap_uid_search_by_uid(tag, args)\n    elsif args.index(\"SINCE\")\n      imap_uid_search_by_date(tag, args)\n    else\n      raise \"Unhandled search:  #{args}\"\n    end\n  end\n\n  def imap_uid_search_by_uid(tag, args)\n\n    # Parse the search request.\n    from_uid, to_uid = args[args.index(\"UID\") + 1].split(\":\")\n    from_uid = from_uid.to_i - self.uid_validity\n    to_uid = to_uid.to_i - self.uid_validity\n\n    # Get a list of uids, offset by uid validity.\n    uids = self.mailbox.uid_search(from_uid, to_uid).map do |uid|\n      uid + self.uid_validity\n    end\n\n    respond(\"*\", %(SEARCH #{uids.join(' ')}))\n    respond(tag, %(OK SEARCH completed))\n  end\n\n  def imap_uid_search_by_date(tag, args)\n    # Parse the search request.\n    since_date = Time.parse(args[args.index(\"SINCE\") + 1])\n\n    # Make sure we have a valid date.\n    if since_date.nil?\n      raise \"Unhandled date: #{args}\"\n    end\n\n    # Get a list of uids, offset by uid validity.\n    uids = mailbox.date_search(since_date).map do |uid|\n      uid + self.uid_validity\n    end\n\n    respond(\"*\", %(SEARCH #{uids.join(' ')}))\n    respond(tag, %(OK SEARCH completed))\n  end\n\n  def imap_uid_search_chaos(tag, args)\n    imap_uid_search(tag, args)\n  end\n\n  # UID FETCH Command\n  # https://tools.ietf.org/html/rfc3501#section-6.4.5\n  # https://tools.ietf.org/html/rfc3501#section-7.4.2\n\n  def imap_uid_fetch(tag, args)\n    # Looks like this: 1103963 (INTERNALDATE RFC822.SIZE UID)\n    m = /(\\d+)\\s\\((.*)\\)/.match(args.join(' '))\n    uid = m[1].to_i\n    fields = m[2].split\n    mail = mailbox.fetch(uid - self.uid_validity)\n    values = fields.map do |field|\n      case field\n      when \"UID\"\n        [field, as_integer(uid)]\n      when \"INTERNALDATE\"\n        [field, as_date(mail.date)]\n      when \"ENVELOPE\"\n        [field, as_list(\n           as_date(mail.date),\n           as_string(mail.subject),\n           as_address_structure(mail.from),\n           as_address_structure(mail.from),\n           as_address_structure(mail.reply_to),\n           as_address_structure(mail.to),\n           as_string(nil),\n           as_string(nil),\n           as_string(nil),\n           as_string(mail.message_id)\n         )]\n      when \"RFC822.SIZE\"\n        [field, as_integer(mail.encoded.size)]\n      when \"RFC822\"\n        self.daemon.total_emails_fetched += 1\n        self.daemon.fetched_log.log(Time.now, username, mail.message_id)\n        [field, as_multiline_string(mail.encoded)]\n      else\n        raise \"Unknown field: #{field}\"\n      end\n    end\n    values += [\"UID\", as_integer(uid)] unless fields.include?(\"RFC822\")\n    respond(\"*\", \"#{uid} FETCH #{as_list(values)}\")\n    respond(tag, \"OK FETCH complete\")\n  end\n\n  def as_list(*values)\n    s = values.map do |value|\n      if value.instance_of?(Array)\n        value.join(\" \")\n      else\n        value\n      end\n    end.join(' ')\n\n    return \"(#{s})\"\n  end\n\n  def as_address_structure(addresses)\n    # https://tools.ietf.org/html/rfc3501#section-7.4.2\n    return as_string(nil) if addresses.blank?\n\n    values = addresses.map do |address|\n      if !address.instance_of?(Mail::Address)\n        address = Mail::Address.new(address)\n      end\n      as_list(as_string(address.display_name),\n              as_string(nil),\n              as_string(address.local),\n              as_string(address.domain))\n    end\n    as_list(values)\n  end\n\n  def as_date(date)\n    as_string(date.strftime(\"%a, %b %e %Y %H:%M:%S %z (%Z)\"))\n  end\n\n  def as_integer(n)\n    n.to_s\n  end\n\n  def as_string(s)\n    s.nil? ? \"NIL\" : \"\\\"#{s}\\\"\"\n  end\n\n  def as_multiline_string(s)\n    \"{#{s.length}}\\r\\n#{s}\"\n  end\n\n  def imap_uid_fetch_chaos(tag, args)\n    imap_uid_fetch(tag, args)\n  end\n\n  # IDLE Command\n  # http://tools.ietf.org/html/rfc2177\n\n  def imap_idle(tag, args)\n    self.idling = true\n    self.idle_tag = tag\n    respond(\"+\", \"idling\")\n  end\n\n  def imap_idle_chaos(tag, args)\n    imap_idle(tag, args)\n  end\n\n  def imap_done(tag, args)\n    respond(idle_tag, \"OK IDLE terminated\")\n  end\n\n  def imap_done_chaos(tag, args)\n    imap_done(tag, args)\n  end\n\n  # LOGOUT Command\n  # https://tools.ietf.org/html/rfc3501#section-6.1.3\n\n  def imap_logout(tag, args)\n    respond(\"*\", \"BYE ImapTestServer logging out\")\n    respond(tag, \"OK LOGOUT completed\")\n    raise NormalDisconnect.new()\n  end\n\n  def imap_logout_chaos(tag, args)\n    imap_logout(tag, args)\n  end\n\n  # GENERAL CHAOS\n\n  def imap_chaos_respond_no(tag, args)\n    respond(tag, \"BAD\")\n  end\n\n  def imap_chaos_respond_bad(tag, args)\n    respond(tag, \"BAD\")\n  end\n\n  def imap_chaos_gibberish_tagged(tag, args)\n    respond(tag, \"ZZZ\")\n  end\n\n  def imap_chaos_gibberish_untagged(tag, args)\n    respond(\"*\", \"ZZZ\")\n  end\n\n  def imap_chaos_soft_disconnect(tag, args)\n    respond(\"*\", \"BYE\")\n  end\n\n  def imap_chaos_hard_disconnect(tag, args)\n    raise ChaosDisconnect.new(\"Disconnect!\")\n  end\nend\n"
  },
  {
    "path": "app/processes/imap_test_server.rb",
    "content": "class ImapTestServer\n  VERSION=\"1.0.0\"\nend\n\nrequire 'imap_test_server/daemon'\n"
  },
  {
    "path": "app/views/api/v1/connections/index.json.rb",
    "content": "fields = [\n  :imap_provider_code,\n  :users_count\n]\n\n@connections.map do |user|\n  values = fields.map do |field|\n    [field, user.send(field)]\n  end\n  array_to_hash(values)\nend.to_json\n"
  },
  {
    "path": "app/views/api/v1/connections/show.json.rb",
    "content": "fields = [\n  :imap_provider_code,\n  :users_count\n]\nvalues = fields.map do |field|\n  [field, @connection.send(field)]\nend\narray_to_hash(values).to_json\n"
  },
  {
    "path": "app/views/api/v1/users/index.json.rb",
    "content": "fields = [:tag, :email]\n\n@users.map do |user|\n  values = fields.map do |field|\n    [field, user.send(field)]\n  end\n  array_to_hash(values)\nend.to_json\n"
  },
  {
    "path": "app/views/api/v1/users/show.json.rb",
    "content": "{\n  :tag            => @user.tag,\n  :email          => @user.email,\n  :connect_url    => new_users_connect_url(@user.signed_request_params),\n  :disconnect_url => new_users_disconnect_url(@user.signed_request_params),\n  :connected_at   => @user.connected_at\n}.to_json\n"
  },
  {
    "path": "app/views/layouts/application.html.erb",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <title>SuperIMAP</title>\n    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>\n    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>\n    <%= csrf_meta_tags %>\n  </head>\n  <body>\n\n    <p class=\"notice\"><%= notice %></p>\n    <p class=\"alert\"><%= alert %></p>\n\n    <%= yield %>\n\n  </body>\n</html>\n"
  },
  {
    "path": "app/views/layouts/blank.html.erb",
    "content": "<%= yield %>\n"
  },
  {
    "path": "app/views/tracer_mailer/tracer_email.html.erb",
    "content": "TRACER: <%= @uid %>\n"
  },
  {
    "path": "app.json",
    "content": "{\n    \"name\": \"SuperIMAP\",\n    \"description\": \"Monitor inboxes for incoming email, at scale.\",\n    \"repository\": \"https://github.com/rustyio/super-imap\",\n    \"keywords\": [\"IMAP\", \"mail\", \"webhook\", \"client\", \"ruby\"],\n    \"success_url\": \"/admin\",\n    \"scripts\": {\n        \"postdeploy\": \"bundle exec rake db:seed\"\n    },\n    \"addons\": [\n        \"heroku-postgresql\"\n    ],\n    \"env\": {\n        \"ENCRYPTION_KEY\": {\n            \"description\": \"Used to encrypt information in the database.\",\n            \"generator\": \"secret\"\n        },\n        \"SECRET_KEY_BASE\": {\n            \"description\": \"A secret key for verifying the integrity of signed cookies.\",\n            \"generator\": \"secret\"\n        }\n    }\n}\n"
  },
  {
    "path": "bin/bundle",
    "content": "#!/usr/bin/env ruby\nENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)\nload Gem.bin_path('bundler', 'bundle')\n"
  },
  {
    "path": "bin/delayed_job",
    "content": "#!/usr/bin/env ruby\n\nrequire File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))\nrequire 'delayed/command'\nDelayed::Command.new(ARGV).daemonize\n"
  },
  {
    "path": "bin/rails",
    "content": "#!/usr/bin/env ruby\nbegin\n  load File.expand_path(\"../spring\", __FILE__)\nrescue LoadError\nend\nAPP_PATH = File.expand_path('../../config/application',  __FILE__)\nrequire_relative '../config/boot'\nrequire 'rails/commands'\n"
  },
  {
    "path": "bin/rake",
    "content": "#!/usr/bin/env ruby\nbegin\n  load File.expand_path(\"../spring\", __FILE__)\nrescue LoadError\nend\nrequire_relative '../config/boot'\nrequire 'rake'\nRake.application.run\n"
  },
  {
    "path": "bin/spring",
    "content": "#!/usr/bin/env ruby\n\n# This file loads spring without using Bundler, in order to be fast\n# It gets overwritten when you run the `spring binstub` command\n\nunless defined?(Spring)\n  require \"rubygems\"\n  require \"bundler\"\n\n  if match = Bundler.default_lockfile.read.match(/^GEM$.*?^    spring \\((.*?)\\)$.*?^$/m)\n    ENV[\"GEM_PATH\"] = ([Bundler.bundle_path.to_s] + Gem.path).join(File::PATH_SEPARATOR)\n    ENV[\"GEM_HOME\"] = \"\"\n    Gem.paths = ENV\n\n    gem \"spring\", match[1]\n    require \"spring/binstub\"\n  end\nend\n"
  },
  {
    "path": "config/application.rb",
    "content": "require File.expand_path('../boot', __FILE__)\n\nrequire 'rails/all'\n\n# Require the gems listed in Gemfile, including any gems\n# you've limited to :test, :development, or :production.\nBundler.require(*Rails.groups)\n\nmodule SuperIMAP\n  class Application < Rails::Application\n    # Settings in config/environments/* take precedence over those specified here.\n    # Application configuration should go into files in config/initializers\n    # -- all .rb files in that directory are automatically loaded.\n\n    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.\n    # Run \"rake -D time\" for a list of tasks for finding time zone names. Default is UTC.\n    # config.time_zone = 'Central Time (US & Canada)'\n\n    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.\n    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]\n    # config.i18n.default_locale = :de\n\n    config.autoload_paths += Dir[\"#{config.root}/app/interactors\"]\n    config.autoload_paths += Dir[\"#{config.root}/app/processes\"]\n\n    encryption_key = ENV['ENCRYPTION_KEY']\n    if encryption_key.present?\n      config.encryption_cipher = Gibberish::AES.new(encryption_key)\n    else\n      config.encryption_cipher = nil\n    end\n\n    config.log_level = String(ENV['LOG_LEVEL'] || \"info\").upcase\n  end\nend\n"
  },
  {
    "path": "config/boot.rb",
    "content": "# Set up gems listed in the Gemfile.\nENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)\n\nrequire 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])\n"
  },
  {
    "path": "config/database.yml.example",
    "content": "default: &default\n  adapter: postgresql\n  host: localhost\n  pool: 5\n  timeout: 5000\n  user: username\n  password: password\n\ndevelopment:\n  <<: *default\n  database: super_imap_development\n\nstress:\n  <<: *default\n  database: super_imap_stress\n\ntest:\n  <<: *default\n  database: super_imap_test\n"
  },
  {
    "path": "config/environment.rb",
    "content": "# Load the Rails application.\nrequire File.expand_path('../application', __FILE__)\n\n# Initialize the Rails application.\nRails.application.initialize!\n"
  },
  {
    "path": "config/environments/development.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # In the development environment your application's code is reloaded on\n  # every request. This slows down response time but is perfect for development\n  # since you don't have to restart the web server when you make code changes.\n  config.cache_classes = false\n\n  # Do not eager load code on boot.\n  config.eager_load = false\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Don't care if the mailer can't send.\n  config.action_mailer.raise_delivery_errors = false\n\n  # Print deprecation notices to the Rails logger.\n  config.active_support.deprecation = :log\n\n  # Raise an error on page load if there are pending migrations.\n  config.active_record.migration_error = :page_load\n\n  # Debug mode disables concatenation and preprocessing of assets.\n  # This option may cause significant delays in view rendering with a large\n  # number of complex assets.\n  config.assets.debug = true\n\n  # Adds additional error checking when serving assets at runtime.\n  # Checks for improperly declared sprockets dependencies.\n  # Raises helpful error messages.\n  config.assets.raise_runtime_errors = true\n\n  # Raises error for missing translations\n  # config.action_view.raise_on_missing_translations = true\nend\n"
  },
  {
    "path": "config/environments/performance.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # Code is not reloaded between requests.\n  config.cache_classes = true\n\n  # Eager load code on boot. This eager loads most of Rails and\n  # your application in memory, allowing both threaded web servers\n  # and those relying on copy on write to perform better.\n  # Rake tasks automatically ignore this option for performance.\n  config.eager_load = true\n\n  # Full error reports are disabled and caching is turned on.\n  config.consider_all_requests_local       = false\n  config.action_controller.perform_caching = true\n\n  # Enable Rack::Cache to put a simple HTTP cache in front of your application\n  # Add `rack-cache` to your Gemfile before enabling this.\n  # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.\n  # config.action_dispatch.rack_cache = true\n\n  # Disable Rails's static asset server (Apache or nginx will already do this).\n  config.serve_static_assets = false\n\n  # Compress JavaScripts and CSS.\n  config.assets.js_compressor = :uglifier\n  # config.assets.css_compressor = :sass\n\n  # Do not fallback to assets pipeline if a precompiled asset is missed.\n  config.assets.compile = false\n\n  # Generate digests for assets URLs.\n  config.assets.digest = true\n\n  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb\n\n  # Specifies the header that your server uses for sending files.\n  # config.action_dispatch.x_sendfile_header = \"X-Sendfile\" # for apache\n  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx\n\n  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.\n  # config.force_ssl = true\n\n  # Set to :debug to see everything in the log.\n  config.log_level = :info\n\n  # Prepend all log lines with the following tags.\n  # config.log_tags = [ :subdomain, :uuid ]\n\n  # Use a different logger for distributed setups.\n  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)\n\n  # Use a different cache store in production.\n  # config.cache_store = :mem_cache_store\n\n  # Enable serving of images, stylesheets, and JavaScripts from an asset server.\n  # config.action_controller.asset_host = \"http://assets.example.com\"\n\n  # Ignore bad email addresses and do not raise email delivery errors.\n  # Set this to true and configure the email server for immediate delivery to raise delivery errors.\n  # config.action_mailer.raise_delivery_errors = false\n\n  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to\n  # the I18n.default_locale when a translation cannot be found).\n  config.i18n.fallbacks = true\n\n  # Send deprecation notices to registered listeners.\n  config.active_support.deprecation = :notify\n\n  # Disable automatic flushing of the log to improve performance.\n  # config.autoflush_log = false\n\n  # Use default logging formatter so that PID and timestamp are not suppressed.\n  config.log_formatter = ::Logger::Formatter.new\n\n  # Do not dump schema after migrations.\n  config.active_record.dump_schema_after_migration = false\nend\n"
  },
  {
    "path": "config/environments/production.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # Code is not reloaded between requests.\n  config.cache_classes = true\n\n  # Eager load code on boot. This eager loads most of Rails and\n  # your application in memory, allowing both threaded web servers\n  # and those relying on copy on write to perform better.\n  # Rake tasks automatically ignore this option for performance.\n  config.eager_load = true\n\n  # Full error reports are disabled and caching is turned on.\n  config.consider_all_requests_local       = false\n  config.action_controller.perform_caching = true\n\n  # Enable Rack::Cache to put a simple HTTP cache in front of your application\n  # Add `rack-cache` to your Gemfile before enabling this.\n  # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.\n  # config.action_dispatch.rack_cache = true\n\n  # Disable Rails's static asset server (Apache or nginx will already do this).\n  config.serve_static_assets = false\n\n  # Compress JavaScripts and CSS.\n  config.assets.js_compressor = :uglifier\n  # config.assets.css_compressor = :sass\n\n  # Do not fallback to assets pipeline if a precompiled asset is missed.\n  config.assets.compile = false\n\n  # Generate digests for assets URLs.\n  config.assets.digest = true\n\n  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb\n\n  # Specifies the header that your server uses for sending files.\n  # config.action_dispatch.x_sendfile_header = \"X-Sendfile\" # for apache\n  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx\n\n  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.\n  # config.force_ssl = true\n\n  # Set to :debug to see everything in the log.\n  config.log_level = :info\n\n  # Prepend all log lines with the following tags.\n  # config.log_tags = [ :subdomain, :uuid ]\n\n  # Use a different logger for distributed setups.\n  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)\n\n  # Use a different cache store in production.\n  # config.cache_store = :mem_cache_store\n\n  # Enable serving of images, stylesheets, and JavaScripts from an asset server.\n  # config.action_controller.asset_host = \"http://assets.example.com\"\n\n  # Ignore bad email addresses and do not raise email delivery errors.\n  # Set this to true and configure the email server for immediate delivery to raise delivery errors.\n  # config.action_mailer.raise_delivery_errors = false\n\n  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to\n  # the I18n.default_locale when a translation cannot be found).\n  config.i18n.fallbacks = true\n\n  # Send deprecation notices to registered listeners.\n  config.active_support.deprecation = :notify\n\n  # Disable automatic flushing of the log to improve performance.\n  # config.autoflush_log = false\n\n  # Use default logging formatter so that PID and timestamp are not suppressed.\n  config.log_formatter = ::Logger::Formatter.new\n\n  # Do not dump schema after migrations.\n  config.active_record.dump_schema_after_migration = false\n\n  if config.encryption_cipher.nil?\n    raise \"Must set ENCRYPTION_KEY environment variable.\"\n  end\nend\n"
  },
  {
    "path": "config/environments/stress.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # In the development environment your application's code is reloaded on\n  # every request. This slows down response time but is perfect for development\n  # since you don't have to restart the web server when you make code changes.\n  config.cache_classes = false\n\n  # Do not eager load code on boot.\n  config.eager_load = false\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Don't care if the mailer can't send.\n  config.action_mailer.raise_delivery_errors = false\n\n  # Print deprecation notices to the Rails logger.\n  config.active_support.deprecation = :log\n\n  # Raise an error on page load if there are pending migrations.\n  config.active_record.migration_error = :page_load\n\n  # Debug mode disables concatenation and preprocessing of assets.\n  # This option may cause significant delays in view rendering with a large\n  # number of complex assets.\n  config.assets.debug = true\n\n  # Adds additional error checking when serving assets at runtime.\n  # Checks for improperly declared sprockets dependencies.\n  # Raises helpful error messages.\n  config.assets.raise_runtime_errors = true\n\n  # Raises error for missing translations\n  # config.action_view.raise_on_missing_translations = true\nend\n"
  },
  {
    "path": "config/environments/test.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # The test environment is used exclusively to run your application's\n  # test suite. You never need to work with it otherwise. Remember that\n  # your test database is \"scratch space\" for the test suite and is wiped\n  # and recreated between test runs. Don't rely on the data there!\n  config.cache_classes = true\n\n  # Do not eager load code on boot. This avoids loading your whole application\n  # just for the purpose of running a single test. If you are using a tool that\n  # preloads Rails for running tests, you may have to set it to true.\n  config.eager_load = false\n\n  # Configure static asset server for tests with Cache-Control for performance.\n  config.serve_static_assets  = true\n  config.static_cache_control = 'public, max-age=3600'\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Raise exceptions instead of rendering exception templates.\n  config.action_dispatch.show_exceptions = false\n\n  # Disable request forgery protection in test environment.\n  config.action_controller.allow_forgery_protection = false\n\n  # Tell Action Mailer not to deliver emails to the real world.\n  # The :test delivery method accumulates sent emails in the\n  # ActionMailer::Base.deliveries array.\n  config.action_mailer.delivery_method = :test\n\n  # Print deprecation notices to the stderr.\n  config.active_support.deprecation = :stderr\n\n  # Raises error for missing translations\n  # config.action_view.raise_on_missing_translations = true\nend\n"
  },
  {
    "path": "config/initializers/active_admin.rb",
    "content": "# coding: utf-8\nActiveAdmin.setup do |config|\n\n  # == Site Title\n  #\n  # Set the title that is displayed on the main layout\n  # for each of the active admin pages.\n  #\n  config.site_title = \"SuperIMAP\"\n\n  # Set the link url for the title. For example, to take\n  # users to your main site. Defaults to no link.\n  #\n  # config.site_title_link = \"/\"\n\n  # Set an optional image to be displayed for the header\n  # instead of a string (overrides :site_title)\n  #\n  # Note: Aim for an image that's 21px high so it fits in the header.\n  #\n  # config.site_title_image = \"logo.png\"\n\n  # == Default Namespace\n  #\n  # Set the default namespace each administration resource\n  # will be added to.\n  #\n  # eg:\n  #   config.default_namespace = :hello_world\n  #\n  # This will create resources in the HelloWorld module and\n  # will namespace routes to /hello_world/*\n  #\n  # To set no namespace by default, use:\n  #   config.default_namespace = false\n  #\n  # Default:\n  # config.default_namespace = :admin\n  #\n  # You can customize the settings for each namespace by using\n  # a namespace block. For example, to change the site title\n  # within a namespace:\n  #\n  #   config.namespace :admin do |admin|\n  #     admin.site_title = \"Custom Admin Title\"\n  #   end\n  #\n  # This will ONLY change the title for the admin section. Other\n  # namespaces will continue to use the main \"site_title\" configuration.\n\n  # == User Authentication\n  #\n  # Active Admin will automatically call an authentication\n  # method in a before filter of all controller actions to\n  # ensure that there is a currently logged in admin user.\n  #\n  # This setting changes the method which Active Admin calls\n  # within the application controller.\n  config.authentication_method = :authenticate_admin_user!\n\n  # == User Authorization\n  #\n  # Active Admin will automatically call an authorization\n  # method in a before filter of all controller actions to\n  # ensure that there is a user with proper rights. You can use\n  # CanCanAdapter or make your own. Please refer to documentation.\n  # config.authorization_adapter = ActiveAdmin::CanCanAdapter\n\n  # You can customize your CanCan Ability class name here.\n  # config.cancan_ability_class = \"Ability\"\n\n  # You can specify a method to be called on unauthorized access.\n  # This is necessary in order to prevent a redirect loop which happens\n  # because, by default, user gets redirected to Dashboard. If user\n  # doesn't have access to Dashboard, he'll end up in a redirect loop.\n  # Method provided here should be defined in application_controller.rb.\n  # config.on_unauthorized_access = :access_denied\n\n  # == Current User\n  #\n  # Active Admin will associate actions with the current\n  # user performing them.\n  #\n  # This setting changes the method which Active Admin calls\n  # (within the application controller) to return the currently logged in user.\n  config.current_user_method = :current_admin_user\n\n\n  # == Logging Out\n  #\n  # Active Admin displays a logout link on each screen. These\n  # settings configure the location and method used for the link.\n  #\n  # This setting changes the path where the link points to. If it's\n  # a string, the strings is used as the path. If it's a Symbol, we\n  # will call the method to return the path.\n  #\n  # Default:\n  config.logout_link_path = :destroy_admin_user_session_path\n\n  # This setting changes the http method used when rendering the\n  # link. For example :get, :delete, :put, etc..\n  #\n  # Default:\n  # config.logout_link_method = :get\n\n\n  # == Root\n  #\n  # Set the action to call for the root path. You can set different\n  # roots for each namespace.\n  #\n  # Default:\n  config.root_to = 'partners#index'\n\n\n  # == Admin Comments\n  #\n  # This allows your users to comment on any resource registered with Active Admin.\n  #\n  # You can completely disable comments:\n  config.allow_comments = false\n  #\n  # You can disable the menu item for the comments index page:\n  # config.show_comments_in_menu = false\n  #\n  # You can change the name under which comments are registered:\n  # config.comments_registration_name = 'AdminComment'\n\n\n  # == Batch Actions\n  #\n  # Enable and disable Batch Actions\n  #\n  config.batch_actions = false\n\n\n  # == Controller Filters\n  #\n  # You can add before, after and around filters to all of your\n  # Active Admin resources and pages from here.\n  #\n  # config.before_filter :do_something_awesome\n\n\n  # == Setting a Favicon\n  #\n  # config.favicon = '/assets/favicon.ico'\n\n\n  # == Removing Breadcrumbs\n  #\n  # Breadcrumbs are enabled by default. You can customize them for individual\n  # resources or you can disable them globally from here.\n  #\n  # config.breadcrumb = false\n\n\n  # == Register Stylesheets & Javascripts\n  #\n  # We recommend using the built in Active Admin layout and loading\n  # up your own stylesheets / javascripts to customize the look\n  # and feel.\n  #\n  # To load a stylesheet:\n  #   config.register_stylesheet 'my_stylesheet.css'\n  #\n  # You can provide an options hash for more control, which is passed along to stylesheet_link_tag():\n  #   config.register_stylesheet 'my_print_stylesheet.css', :media => :print\n  #\n  # To load a javascript file:\n  #   config.register_javascript 'my_javascript.js'\n\n\n  # == CSV options\n  #\n  # Set the CSV builder separator\n  # config.csv_options = { :col_sep => ';' }\n  #\n  # Force the use of quotes\n  # config.csv_options = { :force_quotes => true }\n\n\n  # == Menu System\n  #\n  # You can add a navigation menu to be used in your application, or configure a provided menu\n  #\n  # To change the default utility navigation to show a link to your website & a logout btn\n  #\n  #   config.namespace :admin do |admin|\n  #     admin.build_menu :utility_navigation do |menu|\n  #       menu.add label: \"My Great Website\", url: \"http://www.mygreatwebsite.com\", html_options: { target: :blank }\n  #       admin.add_logout_button_to_menu menu\n  #     end\n  #   end\n  #\n  # If you wanted to add a static menu item to the default menu provided:\n  #\n  #   config.namespace :admin do |admin|\n  #     admin.build_menu :default do |menu|\n  #       menu.add label: \"My Great Website\", url: \"http://www.mygreatwebsite.com\", html_options: { target: :blank }\n  #     end\n  #   end\n\n  # == Download Links\n  #\n  # You can disable download links on resource listing pages,\n  # or customize the formats shown per namespace/globally\n  #\n  # To disable/customize for the :admin namespace:\n  #\n  config.namespace :admin do |admin|\n\n    # Disable the links entirely\n    admin.download_links = false\n\n    # # Only show XML & PDF options\n    # admin.download_links = [:xml, :pdf]\n\n    # # Enable/disable the links based on block\n    # #   (for example, with cancan)\n    # admin.download_links = proc { can?(:view_download_links) }\n\n  end\n\n\n  # == Pagination\n  #\n  # Pagination is enabled by default for all resources.\n  # You can control the default per page count for all resources here.\n  #\n  # config.default_per_page = 30\n\n\n  # == Filters\n  #\n  # By default the index screen includes a “Filters” sidebar on the right\n  # hand side with a filter for each attribute of the registered model.\n  # You can enable or disable them for all resources here.\n  #\n  # config.filters = true\n\nend\n"
  },
  {
    "path": "config/initializers/airbrake.rb",
    "content": "if defined?(Airbrake) && ENV['AIRBRAKE_KEY']\n  Airbrake.configure do |config|\n    config.api_key = ENV['AIRBRAKE_KEY']\n  end\nend\n"
  },
  {
    "path": "config/initializers/assets.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Version of your assets, change this if you want to expire all your assets.\nRails.application.config.assets.version = '1.0'\n\n# Precompile additional assets.\n# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.\n# Rails.application.config.assets.precompile += %w( search.js )\n"
  },
  {
    "path": "config/initializers/backtrace_silencers.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.\n# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }\n\n# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.\n# Rails.backtrace_cleaner.remove_silencers!\n"
  },
  {
    "path": "config/initializers/cookies_serializer.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\nRails.application.config.action_dispatch.cookies_serializer = :json"
  },
  {
    "path": "config/initializers/delayed_job.rb",
    "content": "# config/initializers/delayed_job.rb\n\n# Update settings.\nDelayed::Worker.destroy_failed_jobs = false\nDelayed::Worker.read_ahead          = 10\nDelayed::Worker.default_priority    = 10\nDelayed::Worker.max_run_time        = 20.minutes\nDelayed::Worker.default_queue_name  = \"worker\"\nDelayed::Worker.max_attempts        = 6\n\nif !Delayed::Worker.instance_methods.include?(:handle_failed_job)\n  raise \"Could not update Delayed::Worker!\"\nend\n\n# Patch to log errors.\nclass Delayed::Worker\n  alias_method :original_handle_failed_job, :handle_failed_job\n\n  def handle_failed_job(job, error)\n    begin\n      # Send an alert.\n      Log.exception(error)\n    rescue => e\n      # Shouldn't get here, but if it does, at least log it.\n      Log.exception(e)\n    end\n\n    # Handle as usual.\n    original_handle_failed_job(job, error)\n  end\nend\n"
  },
  {
    "path": "config/initializers/devise.rb",
    "content": "# Use this hook to configure devise mailer, warden hooks and so forth.\n# Many of these configuration options can be set straight in your model.\nDevise.setup do |config|\n  # The secret key used by Devise. Devise uses this key to generate\n  # random tokens. Changing this key will render invalid all existing\n  # confirmation, reset password and unlock tokens in the database.\n  config.secret_key = ENV['SECRET_KEY_BASE'] || Rails.env\n\n  # ==> Mailer Configuration\n  # Configure the e-mail address which will be shown in Devise::Mailer,\n  # note that it will be overwritten if you use your own mailer class\n  # with default \"from\" parameter.\n  # config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'\n\n  # Configure the class responsible to send e-mails.\n  # config.mailer = 'Devise::Mailer'\n\n  # ==> ORM configuration\n  # Load and configure the ORM. Supports :active_record (default) and\n  # :mongoid (bson_ext recommended) by default. Other ORMs may be\n  # available as additional gems.\n  require 'devise/orm/active_record'\n\n  # ==> Configuration for any authentication mechanism\n  # Configure which keys are used when authenticating a user. The default is\n  # just :email. You can configure it to use [:username, :subdomain], so for\n  # authenticating a user, both parameters are required. Remember that those\n  # parameters are used only when authenticating and not when retrieving from\n  # session. If you need permissions, you should implement that in a before filter.\n  # You can also supply a hash where the value is a boolean determining whether\n  # or not authentication should be aborted when the value is not present.\n  # config.authentication_keys = [ :email ]\n\n  # Configure parameters from the request object used for authentication. Each entry\n  # given should be a request method and it will automatically be passed to the\n  # find_for_authentication method and considered in your model lookup. For instance,\n  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.\n  # The same considerations mentioned for authentication_keys also apply to request_keys.\n  # config.request_keys = []\n\n  # Configure which authentication keys should be case-insensitive.\n  # These keys will be downcased upon creating or modifying a user and when used\n  # to authenticate or find a user. Default is :email.\n  config.case_insensitive_keys = [ :email ]\n\n  # Configure which authentication keys should have whitespace stripped.\n  # These keys will have whitespace before and after removed upon creating or\n  # modifying a user and when used to authenticate or find a user. Default is :email.\n  config.strip_whitespace_keys = [ :email ]\n\n  # Tell if authentication through request.params is enabled. True by default.\n  # It can be set to an array that will enable params authentication only for the\n  # given strategies, for example, `config.params_authenticatable = [:database]` will\n  # enable it only for database (email + password) authentication.\n  # config.params_authenticatable = true\n\n  # Tell if authentication through HTTP Auth is enabled. False by default.\n  # It can be set to an array that will enable http authentication only for the\n  # given strategies, for example, `config.http_authenticatable = [:database]` will\n  # enable it only for database authentication. The supported strategies are:\n  # :database      = Support basic authentication with authentication key + password\n  # config.http_authenticatable = false\n\n  # If 401 status code should be returned for AJAX requests. True by default.\n  # config.http_authenticatable_on_xhr = true\n\n  # The realm used in Http Basic Authentication. 'Application' by default.\n  # config.http_authentication_realm = 'Application'\n\n  # It will change confirmation, password recovery and other workflows\n  # to behave the same regardless if the e-mail provided was right or wrong.\n  # Does not affect registerable.\n  # config.paranoid = true\n\n  # By default Devise will store the user in session. You can skip storage for\n  # particular strategies by setting this option.\n  # Notice that if you are skipping storage for all authentication paths, you\n  # may want to disable generating routes to Devise's sessions controller by\n  # passing skip: :sessions to `devise_for` in your config/routes.rb\n  config.skip_session_storage = [:http_auth]\n\n  # By default, Devise cleans up the CSRF token on authentication to\n  # avoid CSRF token fixation attacks. This means that, when using AJAX\n  # requests for sign in and sign up, you need to get a new CSRF token\n  # from the server. You can disable this option at your own risk.\n  # config.clean_up_csrf_token_on_authentication = true\n\n  # ==> Configuration for :database_authenticatable\n  # For bcrypt, this is the cost for hashing the password and defaults to 10. If\n  # using other encryptors, it sets how many times you want the password re-encrypted.\n  #\n  # Limiting the stretches to just one in testing will increase the performance of\n  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use\n  # a value less than 10 in other environments. Note that, for bcrypt (the default\n  # encryptor), the cost increases exponentially with the number of stretches (e.g.\n  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).\n  config.stretches = Rails.env.test? ? 1 : 10\n\n  # Setup a pepper to generate the encrypted password.\n  # config.pepper = 'd8e8f6d62a78b830c1d1521b0f06d0dc4b4b6795fb27ca47daf1c7e7e03d47ca02abcb2587c823fa7f2fcf272e01cd702cd0fcb5ae33a44fa20c00b5912e9c15'\n\n  # ==> Configuration for :confirmable\n  # A period that the user is allowed to access the website even without\n  # confirming their account. For instance, if set to 2.days, the user will be\n  # able to access the website for two days without confirming their account,\n  # access will be blocked just in the third day. Default is 0.days, meaning\n  # the user cannot access the website without confirming their account.\n  # config.allow_unconfirmed_access_for = 2.days\n\n  # A period that the user is allowed to confirm their account before their\n  # token becomes invalid. For example, if set to 3.days, the user can confirm\n  # their account within 3 days after the mail was sent, but on the fourth day\n  # their account can't be confirmed with the token any more.\n  # Default is nil, meaning there is no restriction on how long a user can take\n  # before confirming their account.\n  # config.confirm_within = 3.days\n\n  # If true, requires any email changes to be confirmed (exactly the same way as\n  # initial account confirmation) to be applied. Requires additional unconfirmed_email\n  # db field (see migrations). Until confirmed, new email is stored in\n  # unconfirmed_email column, and copied to email column on successful confirmation.\n  config.reconfirmable = true\n\n  # Defines which key will be used when confirming an account\n  # config.confirmation_keys = [ :email ]\n\n  # ==> Configuration for :rememberable\n  # The time the user will be remembered without asking for credentials again.\n  # config.remember_for = 2.weeks\n\n  # Invalidates all the remember me tokens when the user signs out.\n  config.expire_all_remember_me_on_sign_out = true\n\n  # If true, extends the user's remember period when remembered via cookie.\n  # config.extend_remember_period = false\n\n  # Options to be passed to the created cookie. For instance, you can set\n  # secure: true in order to force SSL only cookies.\n  # config.rememberable_options = {}\n\n  # ==> Configuration for :validatable\n  # Range for password length.\n  config.password_length = 8..128\n\n  # Email regex used to validate email formats. It simply asserts that\n  # one (and only one) @ exists in the given string. This is mainly\n  # to give user feedback and not to assert the e-mail validity.\n  # config.email_regexp = /\\A[^@]+@[^@]+\\z/\n\n  # ==> Configuration for :timeoutable\n  # The time you want to timeout the user session without activity. After this\n  # time the user will be asked for credentials again. Default is 30 minutes.\n  config.timeout_in = 30.minutes\n\n  # If true, expires auth token on session timeout.\n  config.expire_auth_token_on_timeout = true\n\n  # ==> Configuration for :lockable\n  # Defines which strategy will be used to lock an account.\n  # :failed_attempts = Locks an account after a number of failed attempts to sign in.\n  # :none            = No lock strategy. You should handle locking by yourself.\n  # config.lock_strategy = :failed_attempts\n\n  # Defines which key will be used when locking and unlocking an account\n  # config.unlock_keys = [ :email ]\n\n  # Defines which strategy will be used to unlock an account.\n  # :email = Sends an unlock link to the user email\n  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)\n  # :both  = Enables both strategies\n  # :none  = No unlock strategy. You should handle unlocking by yourself.\n  config.unlock_strategy = :time\n\n  # Number of authentication tries before locking an account if lock_strategy\n  # is failed attempts.\n  config.maximum_attempts = 3\n\n  # Time interval to unlock the account if :time is enabled as unlock_strategy.\n  config.unlock_in = 1.hour\n\n  # Warn on the last attempt before the account is locked.\n  config.last_attempt_warning = true\n\n  # ==> Configuration for :recoverable\n  #\n  # Defines which key will be used when recovering the password for an account\n  # config.reset_password_keys = [ :email ]\n\n  # Time interval you can reset your password with a reset password key.\n  # Don't put a too small interval or your users won't have the time to\n  # change their passwords.\n  config.reset_password_within = 6.hours\n\n  # ==> Configuration for :encryptable\n  # Allow you to use another encryption algorithm besides bcrypt (default). You can use\n  # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,\n  # :authlogic_sha512 (then you should set stretches above to 20 for default behavior)\n  # and :restful_authentication_sha1 (then you should set stretches to 10, and copy\n  # REST_AUTH_SITE_KEY to pepper).\n  #\n  # Require the `devise-encryptable` gem when using anything other than bcrypt\n  # config.encryptor = :sha512\n\n  # ==> Scopes configuration\n  # Turn scoped views on. Before rendering \"sessions/new\", it will first check for\n  # \"users/sessions/new\". It's turned off by default because it's slower if you\n  # are using only default views.\n  # config.scoped_views = false\n\n  # Configure the default scope given to Warden. By default it's the first\n  # devise role declared in your routes (usually :user).\n  # config.default_scope = :user\n\n  # Set this configuration to false if you want /users/sign_out to sign out\n  # only the current scope. By default, Devise signs out all scopes.\n  # config.sign_out_all_scopes = true\n\n  # ==> Navigation configuration\n  # Lists the formats that should be treated as navigational. Formats like\n  # :html, should redirect to the sign in page when the user does not have\n  # access, but formats like :xml or :json, should return 401.\n  #\n  # If you have any extra navigational formats, like :iphone or :mobile, you\n  # should add them to the navigational formats lists.\n  #\n  # The \"*/*\" below is required to match Internet Explorer requests.\n  # config.navigational_formats = ['*/*', :html]\n\n  # The default HTTP method used to sign out a resource. Default is :delete.\n  config.sign_out_via = :delete\n\n  # ==> OmniAuth\n  # Add a new OmniAuth provider. Check the wiki for more information on setting\n  # up on your models and hooks.\n  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'\n\n  # ==> Warden configuration\n  # If you want to use other strategies, that are not supported by Devise, or\n  # change the failure app, you can configure them inside the config.warden block.\n  #\n  # config.warden do |manager|\n  #   manager.intercept_401 = false\n  #   manager.default_strategies(scope: :user).unshift :some_external_strategy\n  # end\n\n  # ==> Mountable engine configurations\n  # When using Devise inside an engine, let's call it `MyEngine`, and this engine\n  # is mountable, there are some extra configurations to be taken into account.\n  # The following options are available, assuming the engine is mounted as:\n  #\n  #     mount MyEngine, at: '/my_engine'\n  #\n  # The router that invoked `devise_for`, in the example above, would be:\n  # config.router_name = :my_engine\n  #\n  # When using omniauth, Devise cannot automatically set Omniauth path,\n  # so you need to do it manually. For the users scope, it would be:\n  # config.omniauth_path_prefix = '/my_engine/users/auth'\nend\n"
  },
  {
    "path": "config/initializers/filter_parameter_logging.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Configure sensitive parameters which will be filtered from the log file.\nRails.application.config.filter_parameters += [:password]\n"
  },
  {
    "path": "config/initializers/inflections.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Add new inflection rules using the following format. Inflections\n# are locale specific, and you may define rules for as many different\n# locales as you wish. All of these examples are active by default:\n# ActiveSupport::Inflector.inflections(:en) do |inflect|\n#   inflect.plural /^(ox)$/i, '\\1en'\n#   inflect.singular /^(ox)en/i, '\\1'\n#   inflect.irregular 'person', 'people'\n#   inflect.uncountable %w( fish sheep )\n# end\n\n# These inflection rules are supported but not enabled by default:\n# ActiveSupport::Inflector.inflections(:en) do |inflect|\n#   inflect.acronym 'RESTful'\n# end\n"
  },
  {
    "path": "config/initializers/log.rb",
    "content": "class MyLogger\n  def initialize\n  end\n\n  def exception(exception)\n    msg = \"#{exception.class} (#{exception.message}):\\n    \" +\n          clean_backtrace(exception).join(\"\\n    \")\n    self.error(msg)\n\n    # Trigger an exception email...\n    if defined?(Airbrake)\n      Airbrake.notify(exception)\n    end\n  rescue => e\n    print e.to_s\n  end\n\n  def clean_backtrace(exception)\n    if backtrace = exception.backtrace\n      if defined?(RAILS_ROOT)\n        return backtrace.map { |line| line.sub RAILS_ROOT, '' }\n      else\n        return backtrace\n      end\n    else\n      return []\n    end\n  end\n\n  def librato(mode, key, value)\n    dyno_name = ENV['DYNO']\n\n    if dyno_name\n      info(\"source=#{dyno_name} #{mode}\\##{key}=#{value}\")\n    else\n      info(\"#{mode}\\##{key}=#{value}\")\n    end\n  end\n\n  private\n\n  def method_missing(method, *args, &block)\n    Rails.logger.send(method, *args, &block)\n  end\nend\n\nLog = MyLogger.new()\n"
  },
  {
    "path": "config/initializers/mime_types.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Add new mime types for use in respond_to blocks:\n# Mime::Type.register \"text/richtext\", :rtf\n"
  },
  {
    "path": "config/initializers/ruby_template_handler.rb",
    "content": "# handler = ->(template) { template.source }\nActionView::Template.register_template_handler(:rb, :source.to_proc)\n"
  },
  {
    "path": "config/initializers/session_store.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\nRails.application.config.session_store :cookie_store, key: \"_SuperIMAP_session_#{Rails.env}\"\n"
  },
  {
    "path": "config/initializers/wrap_parameters.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# This file contains settings for ActionController::ParamsWrapper which\n# is enabled by default.\n\n# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.\nActiveSupport.on_load(:action_controller) do\n  wrap_parameters format: [:json] if respond_to?(:wrap_parameters)\nend\n\n# To enable root element in JSON for ActiveRecord objects.\n# ActiveSupport.on_load(:active_record) do\n#  self.include_root_in_json = true\n# end\n"
  },
  {
    "path": "config/locales/devise.en.yml",
    "content": "# Additional translations at https://github.com/plataformatec/devise/wiki/I18n\n\nen:\n  devise:\n    confirmations:\n      confirmed: \"Your email address has been successfully confirmed.\"\n      send_instructions: \"You will receive an email with instructions for how to confirm your email address in a few minutes.\"\n      send_paranoid_instructions: \"If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes.\"\n    failure:\n      already_authenticated: \"You are already signed in.\"\n      inactive: \"Your account is not activated yet.\"\n      invalid: \"Invalid %{authentication_keys} or password.\"\n      locked: \"Your account is locked.\"\n      last_attempt: \"You have one more attempt before your account is locked.\"\n      not_found_in_database: \"Invalid %{authentication_keys} or password.\"\n      timeout: \"Your session expired. Please sign in again to continue.\"\n      unauthenticated: \"You need to sign in before continuing.\"\n      unconfirmed: \"You have to confirm your email address before continuing.\"\n    mailer:\n      confirmation_instructions:\n        subject: \"Confirmation instructions\"\n      reset_password_instructions:\n        subject: \"Reset password instructions\"\n      unlock_instructions:\n        subject: \"Unlock instructions\"\n    omniauth_callbacks:\n      failure: \"Could not authenticate you from %{kind} because \\\"%{reason}\\\".\"\n      success: \"Successfully authenticated from %{kind} account.\"\n    passwords:\n      no_token: \"You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided.\"\n      send_instructions: \"You will receive an email with instructions on how to reset your password in a few minutes.\"\n      send_paranoid_instructions: \"If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes.\"\n      updated: \"Your password has been changed successfully. You are now signed in.\"\n      updated_not_active: \"Your password has been changed successfully.\"\n    registrations:\n      destroyed: \"Bye! Your account has been successfully cancelled. We hope to see you again soon.\"\n      signed_up: \"Welcome! You have signed up successfully.\"\n      signed_up_but_inactive: \"You have signed up successfully. However, we could not sign you in because your account is not yet activated.\"\n      signed_up_but_locked: \"You have signed up successfully. However, we could not sign you in because your account is locked.\"\n      signed_up_but_unconfirmed: \"A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.\"\n      update_needs_confirmation: \"You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address.\"\n      updated: \"Your account has been updated successfully.\"\n    sessions:\n      signed_in: \"Signed in successfully.\"\n      signed_out: \"Signed out successfully.\"\n      already_signed_out: \"Signed out successfully.\"\n    unlocks:\n      send_instructions: \"You will receive an email with instructions for how to unlock your account in a few minutes.\"\n      send_paranoid_instructions: \"If your account exists, you will receive an email with instructions for how to unlock it in a few minutes.\"\n      unlocked: \"Your account has been unlocked successfully. Please sign in to continue.\"\n  errors:\n    messages:\n      already_confirmed: \"was already confirmed, please try signing in\"\n      confirmation_period_expired: \"needs to be confirmed within %{period}, please request a new one\"\n      expired: \"has expired, please request a new one\"\n      not_found: \"not found\"\n      not_locked: \"was not locked\"\n      not_saved:\n        one: \"1 error prohibited this %{resource} from being saved:\"\n        other: \"%{count} errors prohibited this %{resource} from being saved:\"\n"
  },
  {
    "path": "config/locales/en.yml",
    "content": "# Files in the config/locales directory are used for internationalization\n# and are automatically loaded by Rails. If you want to use locales other\n# than English, add the necessary files in this directory.\n#\n# To use the locales, use `I18n.t`:\n#\n#     I18n.t 'hello'\n#\n# In views, this is aliased to just `t`:\n#\n#     <%= t('hello') %>\n#\n# To use a different locale, set it with `I18n.locale`:\n#\n#     I18n.locale = :es\n#\n# This would use the information in config/locales/es.yml.\n#\n# To learn more, please read the Rails Internationalization guide\n# available at http://guides.rubyonrails.org/i18n.html.\n\nen:\n  hello: \"Hello world\"\n"
  },
  {
    "path": "config/newrelic.yml",
    "content": "#\n# This file configures the New Relic Agent.  New Relic monitors\n# Ruby, Java, .NET, PHP, and Python applications with deep visibility and low overhead.\n# For more information, visit www.newrelic.com.\n#\n# Generated September 02, 2013\n#\n# This configuration file is custom generated for app17845580@heroku.com\n\n\n# Here are the settings that are common to all environments\ncommon: &default_settings\n  # ============================== LICENSE KEY ===============================\n  license_key: '<%= ENV[\"NEW_RELIC_LICENSE_KEY\"] %>'\n\n  # Agent Enabled (Ruby/Rails Only)\n  # Use this setting to force the agent to run or not run.\n  # Default is 'auto' which means the agent will install and run only\n  # if a valid dispatcher such as Mongrel is running.  This prevents\n  # it from running with Rake or the console.  Set to false to\n  # completely turn the agent off regardless of the other settings.\n  # Valid values are true, false and auto.\n  #\n  # agent_enabled: auto\n\n  # Application Name Set this to be the name of your application as\n  # you'd like it show up in New Relic. The service will then auto-map\n  # instances of your application into an \"application\" on your\n  # dashboard page. If you want to map this instance into multiple\n  # apps, like \"AJAX Requests\" and \"All UI\" then specify a semicolon\n  # separated list of up to three distinct names, or a yaml list.\n  # Defaults to the capitalized RAILS_ENV or RACK_ENV (i.e.,\n  # Production, Staging, etc)\n  #\n  # Example:\n  #\n  #   app_name:\n  #       - Ajax Service\n  #       - All Services\n  #\n  app_name: My Application\n\n  # When \"true\", the agent collects performance data about your\n  # application and reports this data to the New Relic service at\n  # newrelic.com. This global switch is normally overridden for each\n  # environment below. (formerly called 'enabled')\n  monitor_mode: true\n\n  # Developer mode should be off in every environment but\n  # development as it has very high overhead in memory.\n  developer_mode: false\n\n  # The newrelic agent generates its own log file to keep its logging\n  # information separate from that of your application. Specify its\n  # log level here.\n  log_level: info\n\n  # Optionally set the path to the log file This is expanded from the\n  # root directory (may be relative or absolute, e.g. 'log/' or\n  # '/var/log/') The agent will attempt to create this directory if it\n  # does not exist.\n  # log_file_path: 'log'\n\n  # Optionally set the name of the log file, defaults to 'newrelic_agent.log'\n  # log_file_name: 'newrelic_agent.log'\n\n  # The newrelic agent communicates with the service via https by default.  This\n  # prevents eavesdropping on the performance metrics transmitted by the agent.\n  # The encryption required by SSL introduces a nominal amount of CPU overhead,\n  # which is performed asynchronously in a background thread.  If you'd prefer\n  # to send your metrics over http uncomment the following line.\n  # ssl: false\n\n  #============================== Browser Monitoring ===============================\n  # New Relic Real User Monitoring gives you insight into the performance real users are\n  # experiencing with your website. This is accomplished by measuring the time it takes for\n  # your users' browsers to download and render your web pages by injecting a small amount\n  # of JavaScript code into the header and footer of each page.\n  browser_monitoring:\n      # By default the agent automatically injects the monitoring JavaScript\n      # into web pages. Set this attribute to false to turn off this behavior.\n      auto_instrument: true\n\n  # Proxy settings for connecting to the New Relic server.\n  #\n  # If a proxy is used, the host setting is required.  Other settings\n  # are optional. Default port is 8080.\n  #\n  # proxy_host: hostname\n  # proxy_port: 8080\n  # proxy_user:\n  # proxy_pass:\n\n  # The agent can optionally log all data it sends to New Relic servers to a\n  # separate log file for human inspection and auditing purposes. To enable this\n  # feature, change 'enabled' below to true.\n  # See: https://newrelic.com/docs/ruby/audit-log\n  audit_log:\n    enabled: false\n\n  # Tells transaction tracer and error collector (when enabled)\n  # whether or not to capture HTTP params.  When true, frameworks can\n  # exclude HTTP parameters from being captured.\n  # Rails: the RoR filter_parameter_logging excludes parameters\n  # Java: create a config setting called \"ignored_params\" and set it to\n  #     a comma separated list of HTTP parameter names.\n  #     ex: ignored_params: credit_card, ssn, password\n  capture_params: false\n\n  # Transaction tracer captures deep information about slow\n  # transactions and sends this to the New Relic service once a\n  # minute. Included in the transaction is the exact call sequence of\n  # the transactions including any SQL statements issued.\n  transaction_tracer:\n\n    # Transaction tracer is enabled by default. Set this to false to\n    # turn it off. This feature is only available at the Professional\n    # and above product levels.\n    enabled: true\n\n    # Threshold in seconds for when to collect a transaction\n    # trace. When the response time of a controller action exceeds\n    # this threshold, a transaction trace will be recorded and sent to\n    # New Relic. Valid values are any float value, or (default) \"apdex_f\",\n    # which will use the threshold for an dissatisfying Apdex\n    # controller action - four times the Apdex T value.\n    transaction_threshold: apdex_f\n\n    # When transaction tracer is on, SQL statements can optionally be\n    # recorded. The recorder has three modes, \"off\" which sends no\n    # SQL, \"raw\" which sends the SQL statement in its original form,\n    # and \"obfuscated\", which strips out numeric and string literals.\n    record_sql: obfuscated\n\n    # Threshold in seconds for when to collect stack trace for a SQL\n    # call. In other words, when SQL statements exceed this threshold,\n    # then capture and send to New Relic the current stack trace. This is\n    # helpful for pinpointing where long SQL calls originate from.\n    stack_trace_threshold: 0.500\n\n    # Determines whether the agent will capture query plans for slow\n    # SQL queries.  Only supported in mysql and postgres.  Should be\n    # set to false when using other adapters.\n    # explain_enabled: true\n\n    # Threshold for query execution time below which query plans will\n    # not be captured.  Relevant only when `explain_enabled` is true.\n    # explain_threshold: 0.5\n\n  # Error collector captures information about uncaught exceptions and\n  # sends them to New Relic for viewing\n  error_collector:\n\n    # Error collector is enabled by default. Set this to false to turn\n    # it off. This feature is only available at the Professional and above\n    # product levels.\n    enabled: true\n\n    # Rails Only - tells error collector whether or not to capture a\n    # source snippet around the place of the error when errors are View\n    # related.\n    capture_source: true\n\n    # To stop specific errors from reporting to New Relic, set this property\n    # to comma-separated values.  Default is to ignore routing errors,\n    # which are how 404's get triggered.\n    ignore_errors: \"ActionController::RoutingError,Sinatra::NotFound\"\n\n  # If you're interested in capturing memcache keys as though they\n  # were SQL uncomment this flag. Note that this does increase\n  # overhead slightly on every memcached call, and can have security\n  # implications if your memcached keys are sensitive\n  # capture_memcache_keys: true\n\n# Application Environments\n# ------------------------------------------\n# Environment-specific settings are in this section.\n# For Rails applications, RAILS_ENV is used to determine the environment.\n# For Java applications, pass -Dnewrelic.environment <environment> to set\n# the environment.\n\n# NOTE if your application has other named environments, you should\n# provide newrelic configuration settings for these environments here.\n\ndevelopment:\n  <<: *default_settings\n  # Turn off communication to New Relic service in development mode (also\n  # 'enabled').\n  # NOTE: for initial evaluation purposes, you may want to temporarily\n  # turn the agent on in development mode.\n  monitor_mode: false\n\n  # Rails Only - when running in Developer Mode, the New Relic Agent will\n  # present performance information on the last 100 transactions you have\n  # executed since starting the mongrel.\n  # NOTE: There is substantial overhead when running in developer mode.\n  # Do not use for production or load testing.\n  developer_mode: false\n\n  # Enable textmate links\n  # textmate: true\n\ntest:\n  <<: *default_settings\n  # It almost never makes sense to turn on the agent when running\n  # unit, functional or integration tests or the like.\n  monitor_mode: false\n\n# Turn on the agent in production for 24x7 monitoring. NewRelic\n# testing shows an average performance impact of < 5 ms per\n# transaction, you can leave this on all the time without\n# incurring any user-visible performance degradation.\nproduction:\n  <<: *default_settings\n  monitor_mode: true\n  app_name: 'SuperIMAP - Production'\n\n# Many applications have a staging environment which behaves\n# identically to production. Support for that environment is provided\n# here.  By default, the staging environment has the agent turned on.\nstaging:\n  <<: *default_settings\n  monitor_mode: true\n  app_name: 'SuperIMAP - Staging'\n"
  },
  {
    "path": "config/routes.rb",
    "content": "Rails.application.routes.draw do\n  devise_for :admin_users, ActiveAdmin::Devise.config\n  ActiveAdmin.routes(self)\n\n  namespace :api do\n    namespace :v1 do\n      resources :connections, { :param => :imap_provider_code } do\n        resources :users, { :param => :tag }\n      end\n    end\n  end\n\n  namespace :users do\n    resource :connect, :only => [:new] do\n      get :callback\n    end\n\n    resource :disconnect, :only => [:new] do\n      get :callback\n    end\n  end\n\n  post 'webhook_test/new_mail'\n  post 'webhook_test/user_connected'\n  post 'webhook_test/user_disconnected'\nend\n"
  },
  {
    "path": "config/secrets.yml",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Your secret key is used for verifying the integrity of signed cookies.\n# If you change this key, all old signed cookies will become invalid!\n\n# Make sure the secret is at least 30 characters and all random,\n# no regular words or you'll be exposed to dictionary attacks.\n# You can use `rake secret` to generate a secure secret key.\n\n# Make sure the secrets in this file are kept private\n# if you're sharing your code publicly.\n\ndevelopment:\n  secret_key_base: 67e673bc90fb6b678536387f99d16c785fe68efb21fbc292e2e28230f1c3e1299702b50e6259c62ca1475f6a974ed10eea98b07f3039a15417f4252612ac0553\n\ntest:\n  secret_key_base: 7d7386508cd60715b05c1e8c62d755dd3b3cb4057f257c7759422c6877ea4d951e88951cd8685c50fea3996b6962bdaced05436cd8fa541eba5ab61b702d6b27\n\n# Do not keep production secrets in the repository,\n# instead read values from the environment.\nproduction:\n  secret_key_base: <%= ENV[\"SECRET_KEY_BASE\"] %>\n"
  },
  {
    "path": "config/unicorn.rb",
    "content": "# config/unicorn.rb\n\nworker_processes Integer(ENV['WEB_CONCURRENCY'] || 2)\ntimeout Integer(ENV['WEB_TIMEOUT'] || 30)\npreload_app true\n\nbefore_fork do |server, worker|\n  Signal.trap 'TERM' do\n    puts 'Unicorn master intercepting TERM and sending myself QUIT instead'\n    Process.kill 'QUIT', Process.pid\n  end\n\n  if defined?(ActiveRecord::Base)\n    ActiveRecord::Base.connection.disconnect!\n  end\nend\n\nafter_fork do |server, worker|\n  Signal.trap 'TERM' do\n    puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT'\n  end\n\n  if defined?(ActiveRecord::Base)\n    ActiveRecord::Base.establish_connection\n  end\nend\n"
  },
  {
    "path": "config.ru",
    "content": "# This file is used by Rack-based servers to start the application.\n\nrequire ::File.expand_path('../config/environment',  __FILE__)\nrun Rails.application\n"
  },
  {
    "path": "db/migrate/20141029214610_devise_create_admin_users.rb",
    "content": "class DeviseCreateAdminUsers < ActiveRecord::Migration\n  def migrate(direction)\n    super\n    # Create a default user\n    AdminUser.create!(email: 'admin@example.com', password: 'password', password_confirmation: 'password') if direction == :up\n  end\n\n  def change\n    create_table(:admin_users) do |t|\n      ## Database authenticatable\n      t.string :email,              null: false, default: \"\"\n      t.string :encrypted_password, null: false, default: \"\"\n\n      ## Recoverable\n      t.string   :reset_password_token\n      t.datetime :reset_password_sent_at\n\n      ## Rememberable\n      t.datetime :remember_created_at\n\n      ## Trackable\n      t.integer  :sign_in_count, default: 0, null: false\n      t.datetime :current_sign_in_at\n      t.datetime :last_sign_in_at\n      t.string   :current_sign_in_ip\n      t.string   :last_sign_in_ip\n\n      ## Confirmable\n      # t.string   :confirmation_token\n      # t.datetime :confirmed_at\n      # t.datetime :confirmation_sent_at\n      # t.string   :unconfirmed_email # Only if using reconfirmable\n\n      ## Lockable\n      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts\n      # t.string   :unlock_token # Only if unlock strategy is :email or :both\n      # t.datetime :locked_at\n\n\n      t.timestamps\n    end\n\n    add_index :admin_users, :email,                unique: true\n    add_index :admin_users, :reset_password_token, unique: true\n    # add_index :admin_users, :confirmation_token,   unique: true\n    # add_index :admin_users, :unlock_token,         unique: true\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141029214612_create_active_admin_comments.rb",
    "content": "class CreateActiveAdminComments < ActiveRecord::Migration\n  def self.up\n    create_table :active_admin_comments do |t|\n      t.string :namespace\n      t.text   :body\n      t.string :resource_id,   null: false\n      t.string :resource_type, null: false\n      t.references :author, polymorphic: true\n      t.timestamps\n    end\n    add_index :active_admin_comments, [:namespace]\n    add_index :active_admin_comments, [:author_type, :author_id]\n    add_index :active_admin_comments, [:resource_type, :resource_id]\n  end\n\n  def self.down\n    drop_table :active_admin_comments\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141029215033_create_partners.rb",
    "content": "class CreatePartners < ActiveRecord::Migration\n  def change\n    create_table :partners do |t|\n      t.string :api_key, :index => true\n      t.string :name\n      t.string :success_webhook\n      t.string :failure_webhook\n      t.integer :partner_connections_count, :default => 0\n\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141029215101_create_mail_logs.rb",
    "content": "class CreateMailLogs < ActiveRecord::Migration\n  def change\n    create_table :mail_logs do |t|\n      t.references :user, index: true\n      t.string :md5, :limit => 32, index: true\n      t.string :message_id\n      t.integer :transmit_logs_count, :default => 0\n\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141029215105_create_transmit_logs.rb",
    "content": "class CreateTransmitLogs < ActiveRecord::Migration\n  def change\n    create_table :transmit_logs do |t|\n      t.references :mail_log, index: true\n      t.integer :response_code\n      t.string :response_body, :limit => 1024\n\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141031010321_create_imap_providers.rb",
    "content": "class CreateImapProviders < ActiveRecord::Migration\n  def change\n    create_table :imap_providers do |t|\n      t.string :code\n      t.string :title\n      t.integer :partner_connections_count\n      t.string :host\n      t.integer :port\n      t.boolean :use_ssl\n      t.string :oauth1_access_token_path\n      t.string :oauth1_authorize_path\n      t.string :oauth1_request_token_path\n      t.string :oauth1_scope\n      t.string :oauth1_site\n      t.string :oauth2_grant_type\n      t.string :oauth2_scope\n      t.string :oauth2_site\n      t.string :oauth2_token_method\n      t.string :oauth2_token_url\n\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141031010353_create_partner_connections.rb",
    "content": "class CreatePartnerConnections < ActiveRecord::Migration\n  def change\n    create_table :partner_connections do |t|\n      t.references :partner, index: true\n      t.references :imap_provider, index: true\n      t.integer :users_count, :default => 0\n      t.string :oauth1_consumer_key\n      t.string :oauth1_consumer_secret\n      t.string :oauth2_client_id\n      t.string :oauth2_client_secret\n\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141031010433_create_users.rb",
    "content": "class CreateUsers < ActiveRecord::Migration\n  def change\n    create_table :users do |t|\n      t.references :partner_connection, index: true\n      t.string :email\n      t.string :tag\n      t.integer :mail_logs_count, :default => 0\n      t.datetime :last_connected_at\n      t.datetime :last_email_at\n      t.integer :last_uid\n      t.string :last_uid_validity\n      t.datetime :last_internal_date\n      t.string :login_username\n      t.string :login_password\n      t.string :oauth1_token\n      t.string :oauth1_token_secret\n      t.string :oauth2_refresh_token\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141104202256_create_imap_daemon_heartbeats.rb",
    "content": "class CreateImapDaemonHeartbeats < ActiveRecord::Migration\n  def change\n    create_table :imap_daemon_heartbeats do |t|\n      t.string :tag\n\n      t.timestamps\n    end\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141111204248_add_archived_to_users.rb",
    "content": "class AddArchivedToUsers < ActiveRecord::Migration\n  def change\n    add_column :users, :archived, :boolean, :default => false\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141113163147_add_type_to_users_and_imap_providers.rb",
    "content": "class AddTypeToUsersAndImapProviders < ActiveRecord::Migration\n  def change\n    add_column :imap_providers, :type, :string\n    add_column :users, :type, :string\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141114233206_add_locked_at_to_admin_user.rb",
    "content": "class AddLockedAtToAdminUser < ActiveRecord::Migration\n  def change\n    add_column :admin_users, :locked_at, :datetime\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141118170010_add_type_to_partner_connection.rb",
    "content": "class AddTypeToPartnerConnection < ActiveRecord::Migration\n  def change\n    add_column :partner_connections, :type, :string\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141121152941_add_oauth2_fields_to_imap_provider.rb",
    "content": "class AddOauth2FieldsToImapProvider < ActiveRecord::Migration\n  def change\n    add_column :imap_providers, :oauth2_authorize_url, :string\n    add_column :imap_providers, :oauth2_response_type, :string\n    add_column :imap_providers, :oauth2_access_type, :string\n    add_column :imap_providers, :oauth2_approval_prompt, :string\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141121182537_add_redirect_urls_to_partner.rb",
    "content": "class AddRedirectUrlsToPartner < ActiveRecord::Migration\n  def change\n    add_column :partners, :success_url, :string\n    add_column :partners, :failure_url, :string\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141121184010_rename_fields.rb",
    "content": "class RenameFields < ActiveRecord::Migration\n  def change\n    remove_column :users, :last_connected_at, :datetime\n    add_column :users, :connected_at, :datetime\n    add_column :users, :last_login_at, :datetime\n    remove_column :mail_logs, :md5, :string\n    add_column :mail_logs, :sha1, :string, :limit => 40, :index => true\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141205024759_rename_partner_webhook_columns.rb",
    "content": "class RenamePartnerWebhookColumns < ActiveRecord::Migration\n  def change\n    rename_column :partners, :success_webhook, :new_mail_webhook\n    remove_column :partners, :failure_webhook\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141207191800_add_webhooks_to_partner.rb",
    "content": "class AddWebhooksToPartner < ActiveRecord::Migration\n  def change\n    add_column :partners, :user_connected_webhook, :string\n    add_column :partners, :user_disconnected_webhook, :string\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141207200312_create_delayed_jobs.rb",
    "content": "class CreateDelayedJobs < ActiveRecord::Migration\n  def self.up\n    create_table :delayed_jobs, :force => true do |table|\n      table.integer :priority, :default => 0, :null => false # Allows some jobs to jump to the front of the queue\n      table.integer :attempts, :default => 0, :null => false # Provides for retries, but still fail eventually.\n      table.text :handler, :null => false                    # YAML-encoded string of the object that will do work\n      table.text :last_error                                 # reason for last failure (See Note below)\n      table.datetime :run_at                                 # When to run. Could be Time.zone.now for immediately, or sometime in the future.\n      table.datetime :locked_at                              # Set when a client is working on this object\n      table.datetime :failed_at                              # Set when all retries have failed (actually, by default, the record is deleted instead)\n      table.string :locked_by                                # Who is working on this object (if locked)\n      table.string :queue                                    # The name of the queue this job is in\n      table.timestamps\n    end\n\n    add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority'\n  end\n\n  def self.down\n    drop_table :delayed_jobs\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141215194630_add_tracer_to_users.rb",
    "content": "class AddTracerToUsers < ActiveRecord::Migration\n  def change\n    add_column :users, :enable_tracer, :boolean, :default => false\n    # add_index :users, :enable_tracer\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141215194652_create_tracer_logs.rb",
    "content": "class CreateTracerLogs < ActiveRecord::Migration\n  def change\n    create_table :tracer_logs do |t|\n      t.references :user, index: true\n      t.string :uid, :limit => 20\n      t.datetime :detected_at\n\n      t.timestamps\n    end\n\n    add_index :tracer_logs, :uid\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141215194754_add_smtp_settings_to_imap_provider.rb",
    "content": "class AddSmtpSettingsToImapProvider < ActiveRecord::Migration\n  def change\n    rename_column :imap_providers, :host, :imap_host\n    rename_column :imap_providers, :port, :imap_port\n    rename_column :imap_providers, :use_ssl, :imap_use_ssl\n    add_column :imap_providers, :smtp_host, :string\n    add_column :imap_providers, :smtp_port, :integer\n    add_column :imap_providers, :smtp_domain, :string\n    add_column :imap_providers, :smtp_enable_starttls_auto, :boolean\n  end\nend\n"
  },
  {
    "path": "db/migrate/20141215212628_remove_oauth1_fields.rb",
    "content": "class RemoveOauth1Fields < ActiveRecord::Migration\n  def change\n    remove_column :imap_providers, :oauth1_access_token_path\n    remove_column :imap_providers, :oauth1_authorize_path\n    remove_column :imap_providers, :oauth1_request_token_path\n    remove_column :imap_providers, :oauth1_scope\n    remove_column :imap_providers, :oauth1_site\n    remove_column :partner_connections, :oauth1_consumer_key\n    remove_column :partner_connections, :oauth1_consumer_secret\n    remove_columns :users, :oauth1_token\n    remove_columns :users, :oauth1_token_secret\n  end\nend\n"
  },
  {
    "path": "db/migrate/20150119185401_encrypt_existing_data.rb",
    "content": "class EncryptExistingData < ActiveRecord::Migration\n  def up\n    # Update Oauth2::PartnerConnection entries.\n    connections = PartnerConnection.where(:type => \"Oauth2::PartnerConnection\")\n    connections.each do |connection|\n      connection.oauth2_client_secret = connection.oauth2_client_secret_secure\n      connection.save!\n    end\n\n    # Update Oauth2::User entries.\n    users = User.where(:type => \"Oauth2::User\")\n    users.each_index do |index|\n      user = users[index]\n      print \"(#{index + 1}/#{users.length}) #{user.email}\\n\"\n      user.oauth2_refresh_token = user.oauth2_refresh_token_secure\n      user.save!\n    end\n\n    # Update Plain::User entries.\n    users = User.where(:type => \"Plain::User\")\n    users.each_index do |index|\n      user = users[index]\n      print \"(#{index + 1}/#{users.length}) #{user.email}\\n\"\n      user.login_password = user.login_password_secure\n      user.save!\n    end\n  end\n\n  def down\n  end\nend\n"
  },
  {
    "path": "db/migrate/20150611134232_add_more_indexes_to_mail_logs.rb",
    "content": "class AddMoreIndexesToMailLogs < ActiveRecord::Migration\n  def up\n    add_index :mail_logs, [:user_id, :message_id]\n    add_index :mail_logs, [:user_id, :sha1]\n  end\n\n  def down\n  end\nend\n"
  },
  {
    "path": "db/schema.rb",
    "content": "# encoding: UTF-8\n# This file is auto-generated from the current state of the database. Instead\n# of editing this file, please use the migrations feature of Active Record to\n# incrementally modify your database, and then regenerate this schema definition.\n#\n# Note that this schema.rb definition is the authoritative source for your\n# database schema. If you need to create the application database on another\n# system, you should be using db:schema:load, not running all the migrations\n# from scratch. The latter is a flawed and unsustainable approach (the more migrations\n# you'll amass, the slower it'll run and the greater likelihood for issues).\n#\n# It's strongly recommended that you check this file into your version control system.\n\nActiveRecord::Schema.define(version: 20150611134232) do\n\n  # These are extensions that must be enabled in order to support this database\n  enable_extension \"plpgsql\"\n  enable_extension \"pg_stat_statements\"\n\n  create_table \"active_admin_comments\", force: true do |t|\n    t.string   \"namespace\"\n    t.text     \"body\"\n    t.string   \"resource_id\",   null: false\n    t.string   \"resource_type\", null: false\n    t.integer  \"author_id\"\n    t.string   \"author_type\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n  end\n\n  add_index \"active_admin_comments\", [\"author_type\", \"author_id\"], name: \"index_active_admin_comments_on_author_type_and_author_id\", using: :btree\n  add_index \"active_admin_comments\", [\"namespace\"], name: \"index_active_admin_comments_on_namespace\", using: :btree\n  add_index \"active_admin_comments\", [\"resource_type\", \"resource_id\"], name: \"index_active_admin_comments_on_resource_type_and_resource_id\", using: :btree\n\n  create_table \"admin_users\", force: true do |t|\n    t.string   \"email\",                  default: \"\", null: false\n    t.string   \"encrypted_password\",     default: \"\", null: false\n    t.string   \"reset_password_token\"\n    t.datetime \"reset_password_sent_at\"\n    t.datetime \"remember_created_at\"\n    t.integer  \"sign_in_count\",          default: 0,  null: false\n    t.datetime \"current_sign_in_at\"\n    t.datetime \"last_sign_in_at\"\n    t.string   \"current_sign_in_ip\"\n    t.string   \"last_sign_in_ip\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.datetime \"locked_at\"\n  end\n\n  add_index \"admin_users\", [\"email\"], name: \"index_admin_users_on_email\", unique: true, using: :btree\n  add_index \"admin_users\", [\"reset_password_token\"], name: \"index_admin_users_on_reset_password_token\", unique: true, using: :btree\n\n  create_table \"delayed_jobs\", force: true do |t|\n    t.integer  \"priority\",   default: 0, null: false\n    t.integer  \"attempts\",   default: 0, null: false\n    t.text     \"handler\",                null: false\n    t.text     \"last_error\"\n    t.datetime \"run_at\"\n    t.datetime \"locked_at\"\n    t.datetime \"failed_at\"\n    t.string   \"locked_by\"\n    t.string   \"queue\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n  end\n\n  add_index \"delayed_jobs\", [\"priority\", \"run_at\"], name: \"delayed_jobs_priority\", using: :btree\n\n  create_table \"imap_daemon_heartbeats\", force: true do |t|\n    t.string   \"tag\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n  end\n\n  create_table \"imap_providers\", force: true do |t|\n    t.string   \"code\"\n    t.string   \"title\"\n    t.integer  \"partner_connections_count\"\n    t.string   \"imap_host\"\n    t.integer  \"imap_port\"\n    t.boolean  \"imap_use_ssl\"\n    t.string   \"oauth2_grant_type\"\n    t.string   \"oauth2_scope\"\n    t.string   \"oauth2_site\"\n    t.string   \"oauth2_token_method\"\n    t.string   \"oauth2_token_url\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.string   \"type\"\n    t.string   \"oauth2_authorize_url\"\n    t.string   \"oauth2_response_type\"\n    t.string   \"oauth2_access_type\"\n    t.string   \"oauth2_approval_prompt\"\n    t.string   \"smtp_host\"\n    t.integer  \"smtp_port\"\n    t.string   \"smtp_domain\"\n    t.boolean  \"smtp_enable_starttls_auto\"\n  end\n\n  create_table \"mail_logs\", force: true do |t|\n    t.integer  \"user_id\"\n    t.string   \"message_id\"\n    t.integer  \"transmit_logs_count\",            default: 0\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.string   \"sha1\",                limit: 40\n  end\n\n  add_index \"mail_logs\", [\"user_id\", \"message_id\"], name: \"index_mail_logs_on_user_id_and_message_id\", using: :btree\n  add_index \"mail_logs\", [\"user_id\", \"sha1\"], name: \"index_mail_logs_on_user_id_and_sha1\", using: :btree\n  add_index \"mail_logs\", [\"user_id\"], name: \"index_mail_logs_on_user_id\", using: :btree\n\n  create_table \"partner_connections\", force: true do |t|\n    t.integer  \"partner_id\"\n    t.integer  \"imap_provider_id\"\n    t.integer  \"users_count\",          default: 0\n    t.string   \"oauth2_client_id\"\n    t.string   \"oauth2_client_secret\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.string   \"type\"\n  end\n\n  add_index \"partner_connections\", [\"imap_provider_id\"], name: \"index_partner_connections_on_imap_provider_id\", using: :btree\n  add_index \"partner_connections\", [\"partner_id\"], name: \"index_partner_connections_on_partner_id\", using: :btree\n\n  create_table \"partners\", force: true do |t|\n    t.string   \"api_key\"\n    t.string   \"name\"\n    t.string   \"new_mail_webhook\"\n    t.integer  \"partner_connections_count\", default: 0\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.string   \"success_url\"\n    t.string   \"failure_url\"\n    t.string   \"user_connected_webhook\"\n    t.string   \"user_disconnected_webhook\"\n  end\n\n  create_table \"tracer_logs\", force: true do |t|\n    t.integer  \"user_id\"\n    t.string   \"uid\",         limit: 20\n    t.datetime \"detected_at\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n  end\n\n  add_index \"tracer_logs\", [\"uid\"], name: \"index_tracer_logs_on_uid\", using: :btree\n  add_index \"tracer_logs\", [\"user_id\"], name: \"index_tracer_logs_on_user_id\", using: :btree\n\n  create_table \"transmit_logs\", force: true do |t|\n    t.integer  \"mail_log_id\"\n    t.integer  \"response_code\"\n    t.string   \"response_body\", limit: 1024\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n  end\n\n  add_index \"transmit_logs\", [\"mail_log_id\"], name: \"index_transmit_logs_on_mail_log_id\", using: :btree\n\n  create_table \"users\", force: true do |t|\n    t.integer  \"partner_connection_id\"\n    t.string   \"email\"\n    t.string   \"tag\"\n    t.integer  \"mail_logs_count\",       default: 0\n    t.datetime \"last_email_at\"\n    t.integer  \"last_uid\"\n    t.string   \"last_uid_validity\"\n    t.datetime \"last_internal_date\"\n    t.string   \"login_username\"\n    t.string   \"login_password\"\n    t.string   \"oauth2_refresh_token\"\n    t.datetime \"created_at\"\n    t.datetime \"updated_at\"\n    t.boolean  \"archived\",              default: false\n    t.string   \"type\"\n    t.datetime \"connected_at\"\n    t.datetime \"last_login_at\"\n    t.boolean  \"enable_tracer\",         default: false\n  end\n\n  add_index \"users\", [\"partner_connection_id\"], name: \"index_users_on_partner_connection_id\", using: :btree\n\nend\n"
  },
  {
    "path": "db/seeds-development.rb",
    "content": "AdminUser.new(:email => \"admin@example.com\", :password => \"password\").save\n\nplain_provider = Plain::ImapProvider.create(\n  :code         => 'PLAIN',\n  :title        => \"Fake IMAP\",\n  :imap_host    => \"localhost\",\n  :imap_port    => 10143,\n  :imap_use_ssl => false)\n\nOauth2::ImapProvider.create!(\n  :code                      => 'GMAIL_OAUTH2',\n  :title                     => \"Google Mail - OAuth 2.0\",\n  :imap_host                 => \"imap.gmail.com\",\n  :imap_port                 => 993,\n  :imap_use_ssl              => true,\n  :smtp_host                 => \"smtp.gmail.com\",\n  :smtp_port                 => 587,\n  :smtp_domain               => \"gmail.com\",\n  :smtp_enable_starttls_auto => true,\n  :oauth2_site               => \"https://accounts.google.com\",\n  :oauth2_token_method       => \"post\",\n  :oauth2_grant_type         => \"refresh_token\",\n  :oauth2_scope              => \"https://www.googleapis.com/auth/userinfo.email https://mail.google.com/\",\n  :oauth2_token_url          => \"/o/oauth2/token\",\n  :oauth2_authorize_url      => \"/o/oauth2/auth\",\n  :oauth2_response_type      => \"code\",\n  :oauth2_access_type        => \"offline\",\n  :oauth2_approval_prompt    => \"force\")\n\ndef create_transmit_log(mail_log, n)\n  mail_log.transmit_logs.create(:response_code => 200, :response_body => \"Response #{n}\")\nend\n\ndef create_mail_log(user, n)\n  user.mail_logs.create!(:message_id => \"abc#{n}\").tap do |mail_log|\n    create_transmit_log(mail_log, 1)\n    create_transmit_log(mail_log, 2)\n    create_transmit_log(mail_log, 3)\n  end\nend\n\ndef create_user(connection, n)\n  connection.users.create!(\n    :tag            => \"User #{n}\",\n    :email          => \"user#{n}@localhost\",\n    :login_username => \"user#{n}@localhost\",\n    :login_password => \"password\").tap do |user|\n    create_mail_log(user, 1)\n    create_mail_log(user, 2)\n    create_mail_log(user, 3)\n  end\nend\n\ndef create_partner_connection(partner, imap_provider)\n  partner.connections.create!(:imap_provider_id => imap_provider.id).tap do |connection|\n    5.times.each do |n|\n      create_user(connection, n)\n    end\n  end\nend\n\nPartner.create!(\n  :name                      => \"Partner\",\n  :new_mail_webhook          => \"http://localhost:5000/webhook_test/new_mail\",\n  :user_connected_webhook    => \"http://localhost:5000/webhook_test/user_connected\",\n  :user_disconnected_webhook => \"http://localhost:5000/webhook_test/user_disconnected\",\n  :success_url               => \"/success.html\",\n  :failure_url               => \"/failure.html\").tap do |partner|\n  create_partner_connection(partner, plain_provider)\nend\n"
  },
  {
    "path": "db/seeds-production.rb",
    "content": "Oauth2::ImapProvider.create!(\n  :code                      => 'GMAIL_OAUTH2',\n  :title                     => \"Google Mail - OAuth 2.0\",\n  :imap_host                 => \"imap.gmail.com\",\n  :imap_port                 => 993,\n  :imap_use_ssl              => true,\n  :smtp_host                 => \"smtp.gmail.com\",\n  :smtp_port                 => 587,\n  :smtp_domain               => \"gmail.com\",\n  :smtp_enable_starttls_auto => true,\n  :oauth2_site               => \"https://accounts.google.com\",\n  :oauth2_token_url          => \"/o/oauth2/token\",\n  :oauth2_token_method       => \"post\",\n  :oauth2_grant_type         => \"refresh_token\",\n  :oauth2_scope              => \"https://www.googleapis.com/auth/userinfo.email https://mail.google.com/\",\n  :oauth2_token_url          => \"/o/oauth2/token\",\n  :oauth2_authorize_url      => \"/o/oauth2/auth\",\n  :oauth2_response_type      => \"code\",\n  :oauth2_access_type        => \"offline\",\n  :oauth2_approval_prompt    => \"force\")\n\nAdminUser.new(:email => \"admin@example.com\", :password => \"password\").save\n"
  },
  {
    "path": "db/seeds-stress.rb",
    "content": "AdminUser.new(:email => \"admin@example.com\", :password => \"password\").save\n\nimap_provider = Plain::ImapProvider.create!(\n  :code         => 'PLAIN',\n  :title        => \"Fake IMAP\",\n  :imap_host    => \"127.0.0.1\",\n  :imap_port    => 10143,\n  :imap_use_ssl => false)\n\ndef create_user(connection, n)\n  connection.users.create!(\n    :tag            => \"User #{n}\",\n    :email          => \"user#{n}@localhost\",\n    :login_username => \"user#{n}@localhost\",\n    :login_password => \"password\",\n    :connected_at   => Time.now)\nend\n\ndef create_partner_connection(partner, imap_provider)\n  partner.connections.create!(:imap_provider_id => imap_provider.id).tap do |connection|\n    1000.times.each do |n|\n      create_user(connection, n)\n    end\n  end\nend\n\nPartner.create!(\n  :name            => \"Partner\",\n  :new_mail_webhook => \"ignored\",\n  :success_url     => \"ignored\",\n  :failure_url     => \"ignored\").tap do |partner|\n  create_partner_connection(partner, imap_provider)\nend\n"
  },
  {
    "path": "db/seeds-test.rb",
    "content": "AdminUser.new(:email => \"admin@example.com\", :password => \"password\").save\n\nplain_provider = Plain::ImapProvider.create!(\n  :code         => 'PLAIN',\n  :title        => \"Fake IMAP\",\n  :imap_host    => \"localhost\",\n  :imap_port    => 10143,\n  :imap_use_ssl => false)\n\ndef create_transmit_log(mail_log, n)\n  mail_log.transmit_logs.create!(:response_code => 200, :response_body => \"Response #{n}\")\nend\n\ndef create_mail_log(user, n)\n  user.mail_logs.create!(:message_id => \"abc#{n}\").tap do |mail_log|\n    create_transmit_log(mail_log, 1)\n    create_transmit_log(mail_log, 2)\n    create_transmit_log(mail_log, 3)\n  end\nend\n\ndef create_user(connection, n)\n  connection.users.create!(\n    :tag            => \"User #{n}\",\n    :email          => \"user#{n}@localhost\",\n    :login_username => \"user#{n}@localhost\",\n    :login_password => \"password\").tap do |user|\n    create_mail_log(user, 1)\n    create_mail_log(user, 2)\n    create_mail_log(user, 3)\n  end\nend\n\ndef create_partner_connection(partner, imap_provider)\n  connection = partner.connections.create!(:imap_provider_id => imap_provider.id).tap do |connection|\n    5.times.each do |n|\n      create_user(connection, n)\n    end\n  end\nend\n\nPartner.create!(\n  :name            => \"Partner\",\n  :new_mail_webhook => \"ignored\",\n  :success_url     => \"ignored\",\n  :failure_url     => \"ignored\").tap do |partner|\n  create_partner_connection(partner, plain_provider)\nend\n"
  },
  {
    "path": "db/seeds.rb",
    "content": "require_relative \"./seeds-#{Rails.env}.rb\"\n"
  },
  {
    "path": "lib/assets/.keep",
    "content": ""
  },
  {
    "path": "lib/tasks/.keep",
    "content": ""
  },
  {
    "path": "lib/tasks/imap.rake",
    "content": "namespace :imap do\n  task :client => :environment do\n    Log.info(\"Starting an IMAP Client process...\")\n\n    # Read environment variables.\n    config = {}\n    config[:stress_test_mode]   = (ENV['STRESS_TEST_MODE'] == \"true\")\n    config[:num_worker_threads] = (ENV['NUM_WORKER_THREADS'] || 5).to_i\n    config[:max_user_threads]   = (ENV['MAX_USER_THREADS']   || 500).to_i\n    config[:max_email_size]     = (ENV['MAX_EMAIL_SIZE']     || (1024 * 1024)).to_i\n    config[:tracer_interval]    = (ENV['TRACER_INTERVAL']    || 10 * 60).to_i\n    config[:num_tracers]        = (ENV['NUM_TRACERS']        || 3).to_i\n    config[:enable_chaos]       = (ENV['ENABLE_CHAOS']       || \"true\") == \"true\"\n    config[:enable_profiler]    = (ENV['ENABLE_PROFILER']    || \"false\") == \"true\"\n\n    require 'imap_client'\n    ImapClient::Daemon.new(config).run\n  end\n\n  task :test_server => :environment do\n    Log.info(\"Starting an IMAP Test Server process...\")\n    ImapDaemonHeartbeat.destroy_all\n\n    # Read environment variables.\n    config = {}\n    config[:port]              = ImapProvider.first.imap_port\n    config[:length_of_test]    = (ENV['LENGTH_OF_TEST']    || 1).to_i\n    config[:emails_per_minute] = (ENV['EMAILS_PER_MINUTE'] || 500).to_i\n    config[:enable_chaos]      = (ENV['ENABLE_CHAOS']      || \"true\") == \"true\"\n\n    require 'imap_test_server'\n    ImapTestServer::Daemon.new(config).run\n  end\nend\n"
  },
  {
    "path": "lib/xoauth2_authenticator.rb",
    "content": "require 'net/imap'\n\nclass Net::IMAP\n  class XOAuth2Authenticator\n    def initialize(email_address, access_token)\n      @email_address = email_address\n      @access_token = access_token\n    end\n\n    def process(s)\n      \"user=#{@email_address}\\x01auth=Bearer #{@access_token}\\x01\\x01\"\n    end\n  end\n\n  add_authenticator 'XOAUTH2', XOAuth2Authenticator\nend\n\nclass Net::SMTP\n  def auth_xoauth2(email_address, access_token)\n    res = critical {\n      auth_string = \"user=#{email_address}\\x01auth=Bearer #{access_token}\\x01\\x01\"\n      get_response('AUTH XOAUTH2 ' + base64_encode(auth_string))\n    }\n    check_auth_response res\n    res\n  end\nend\n"
  },
  {
    "path": "log/.keep",
    "content": ""
  },
  {
    "path": "public/404.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The page you were looking for doesn't exist (404)</title>\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n    margin: 0;\n  }\n\n  div.dialog {\n    width: 95%;\n    max-width: 33em;\n    margin: 4em auto 0;\n  }\n\n  div.dialog > div {\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 12% 0;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  div.dialog > p {\n    margin: 0 0 1em;\n    padding: 1em;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/404.html -->\n  <div class=\"dialog\">\n    <div>\n      <h1>The page you were looking for doesn't exist.</h1>\n      <p>You may have mistyped the address or the page may have moved.</p>\n    </div>\n    <p>If you are the application owner check the logs for more information.</p>\n  </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/422.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The change you wanted was rejected (422)</title>\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n    margin: 0;\n  }\n\n  div.dialog {\n    width: 95%;\n    max-width: 33em;\n    margin: 4em auto 0;\n  }\n\n  div.dialog > div {\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 12% 0;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  div.dialog > p {\n    margin: 0 0 1em;\n    padding: 1em;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/422.html -->\n  <div class=\"dialog\">\n    <div>\n      <h1>The change you wanted was rejected.</h1>\n      <p>Maybe you tried to change something you didn't have access to.</p>\n    </div>\n    <p>If you are the application owner check the logs for more information.</p>\n  </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/500.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>We're sorry, but something went wrong (500)</title>\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n    margin: 0;\n  }\n\n  div.dialog {\n    width: 95%;\n    max-width: 33em;\n    margin: 4em auto 0;\n  }\n\n  div.dialog > div {\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 12% 0;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  div.dialog > p {\n    margin: 0 0 1em;\n    padding: 1em;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/500.html -->\n  <div class=\"dialog\">\n    <div>\n      <h1>We're sorry, but something went wrong.</h1>\n    </div>\n    <p>If you are the application owner check the logs for more information.</p>\n  </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/failure.html",
    "content": "FAILURE\n"
  },
  {
    "path": "public/index.html",
    "content": "<script>\n    document.location.href = \"/\" + \"admin\";\n</script>\n"
  },
  {
    "path": "public/robots.txt",
    "content": "# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file\n#\n# To ban all spiders from the entire site uncomment the next two lines:\n# User-agent: *\n# Disallow: /\n"
  },
  {
    "path": "public/success.html",
    "content": "SUCCESS\n"
  },
  {
    "path": "script/analyze-stress-test.R",
    "content": "#!/usr/bin/env Rscript\n\nlibrary(ggplot2)\n\n###\n### READ DATA\n###\n\n## Read CSV files.\ncat(\"Reading CSV files.\")\ngenerated <- read.csv('./log/stress/generated_emails.csv')\nfetched <- read.csv('./log/stress/fetched_emails.csv')\nevents <- read.csv('./log/stress/events.csv')\n\n## There are multiple processed files, one for each server.\npaths <- list.files(path = \"./log/stress/\",\n                    pattern = \"processed_emails_.*.csv\",\n                    full.names = TRUE)\nprocessed <- do.call(rbind, lapply(paths, FUN=function(path) {\n    df <- read.csv(path)\n    names(df) <- c(\"time\", \"email\", \"message.id\")\n    df$time <- as.POSIXct(df$time)\n    return(df)\n}))\nprocessed <- processed[order(processed$time), ]\n\n## Rename columns.\nnames(generated) <- c(\"time\", \"email\", \"message.id\")\nnames(fetched) <- c(\"time\", \"email\", \"message.id\")\nnames(processed) <- c(\"time\", \"email\", \"message.id\")\nnames(events) <- c(\"time\", \"email\", \"event\")\n\n## Normalize column values.\ngenerated$time <- as.POSIXct(generated$time)\nfetched$time <- as.POSIXct(fetched$time)\nprocessed$time <- as.POSIXct(processed$time)\nevents$time <- as.POSIXct(events$time)\n\n## Split out chaotic events.\nchaotic.events <- events[grepl(\"chaos\", events$event),]\n\n## Hack, make sure we have at least one chaotic event, otherwise we'll\n## get errors.\nif (nrow(chaotic.events) == 0) {\n    chaotic.events <- data.frame(time=min(generated$time), email=NA, event=NA, total=NA)\n}\n\n## Add count columns.\ngenerated$count <- 1\nfetched$count <- 1\nprocessed$count <- 1\nchaotic.events$count <- 1\n\n## Add total columns.\ngenerated$total <- cumsum(generated$count)\nfetched$total <- cumsum(fetched$count)\nprocessed$total <- cumsum(processed$count)\nchaotic.events$total <- cumsum(chaotic.events$count)\n\n\n###\n### SAVE A PLOT\n###\n\ncat(\"Generating plots.\\n\")\n\nx.limits <- c(min(generated$time), max(processed$time))\n\ntitle = \"# of Emails Generated, Fetched, & Processed Over Time\"\np1 <- ggplot() +\n    ggtitle(title) +\n    xlab(\"Time\") +\n    ylab(\"Count\") +\n    xlim(x.limits) +\n    guides(color = guide_legend(title = NULL)) +\n    geom_line(aes(generated$time, generated$total, col=\"Generated\")) +\n    geom_line(aes(fetched$time, fetched$total, col=\"Fetched\")) +\n    geom_line(aes(processed$time, processed$total, col=\"Processed\")) +\n    geom_line(aes(chaotic.events$time, chaotic.events$total, col=\"Chaos\")) +\n    theme(legend.position = \"left\")\n\ntitle = \"Chaotic Events\"\np2 <- ggplot() +\n    ggtitle(title) +\n    xlab(\"Time\") +\n    ylab(\"Chaotic Events\") +\n    xlim(x.limits) +\n    geom_point(aes(chaotic.events$time, chaotic.events$event))\n\n## Save the plots.\ncat(\"Saving plots.\\n\")\npdf(\"./tmp/stress-test-results.pdf\")\nprint(p1)\nprint(p2)\ndev.off()\n"
  },
  {
    "path": "script/stress-test",
    "content": "#!/usr/bin/env bash\n\nulimit -n 2048\n\n[ -z \"$LENGTH_OF_TEST\" ]         && LENGTH_OF_TEST=\"1\"\n[ -z \"$EMAILS_PER_MINUTE\" ]      && EMAILS_PER_MINUTE=\"500\"\n[ -z \"$ENABLE_CHAOS\" ]           && ENABLE_CHAOS=\"true\"\n[ -z \"$ENABLE_PROFILER\" ]        && ENABLE_PROFILER=\"false\"\n[ -z \"$RUBY_PROF_MEASURE_MODE\" ] && RUBY_PROF_MEASURE_MODE=\"process\"\n\nclear\n\necho\necho \"Did you set up database? Postgres works best, and you need to run this:\"\necho \"$ RAILS_ENV=stress rake db:drop db:create db:setup db:seed\"\necho\necho \"The goal of this stress test is to ensure that:\"\necho\necho \"1. CPU load remains stable.\"\necho \"2. Memory remains stable.\"\necho \"3. IO handles are properly closed.\"\necho \"4. The system actually reads all of the email.\"\necho\necho \"Use system tools to monitor #1, #2, and #3.\"\necho \"View 'stress-test-results.pdf' for #4.\"\necho\necho \"By design, the stress test generates bad IMAP responses.\"\necho \"These will look like exceptions in the imap_client process.\"\necho \"Do not be alarmed; you can ignore the errors.\"\necho\necho \"Some useful environment variables to set:\"\necho\necho \"+ LENGTH_OF_TEST         - Total number of minutes to run test. [$LENGTH_OF_TEST]\"\necho \"+ EMAILS_PER_MINUTE      - Rate of fake email generation. [$EMAILS_PER_MINUTE]\"\necho \"+ ENABLE_CHAOS           - 'true' if we should generate bad IMAP responses. [$ENABLE_CHAOS]\"\necho \"+ ENABLE_PROFILER        - 'true' to start the ruby-prof profiler. [$ENABLE_PROFILER]\"\necho \"+ RUBY_PROF_MEASURE_MODE - What should ruby-prof measure? [$RUBY_PROF_MEASURE_MODE]\"\necho \"                         - Can be 'wall', 'process', 'cpu', 'allocations', 'memory', 'gc_time', or 'gc_runs'\"\necho \"                         - See https://github.com/ruby-prof/ruby-prof\"\necho\necho \"Press enter to continue, Control-C to exit.\"\nread\n\necho \"Beginning stress test. Please wait.\"\n\n# Remove old log files.\nrm ./log/stress/*\n\n# Begin the stress test.\nRAILS_ENV=stress foreman s -f Procfile.stress-test\n\n# Generate some plots.\nRscript script/analyze-stress-test.R\n\necho\necho \"Stress test results are in 'tmp/stress-test-results.pdf'.\"\necho \"If enabled, profiler results are in 'tmp/profile.html'.\"\necho\n"
  },
  {
    "path": "test/controllers/.keep",
    "content": ""
  },
  {
    "path": "test/controllers/api/v1/connections_controller_test.rb",
    "content": "require 'test_helper'\n\nclass Api::V1::ConnectionsControllerTest < ActionController::TestCase\n  setup do\n    @partner = Partner.first\n    @connection = @partner.connections.first\n  end\n\n  test \"index\" do\n    get(:index, :api_key => @partner.api_key)\n    assert_response :success\n  end\n\n  test \"create\" do\n    code = @connection.imap_provider_code\n    @connection.delete\n    post(:create, :api_key => @partner.api_key, :imap_provider_code => code)\n    assert_response :success\n  end\n\n  test \"create without code\" do\n    post(:create, :api_key => @partner.api_key)\n    assert_response :not_found\n  end\n\n  test \"update\" do\n    post(:update, :api_key => @partner.api_key, :imap_provider_code => @connection.imap_provider_code)\n    assert_response :success\n  end\n\n  test \"show\" do\n    get(:show, :api_key => @partner.api_key, :imap_provider_code => @connection.imap_provider_code)\n    assert_response :success\n  end\n\n  test \"destroy\" do\n    delete(:destroy, :api_key => @partner.api_key, :imap_provider_code => @connection.imap_provider_code)\n    assert_response :success\n  end\nend\n"
  },
  {
    "path": "test/controllers/api/v1/users_controller_test.rb",
    "content": "require 'test_helper'\n\nclass Api::V1::UsersControllerTest < ActionController::TestCase\n  setup do\n    @partner = Partner.first\n    @connection = @partner.connections.first\n    @code = @connection.imap_provider_code\n    @user = @connection.users.first\n    @data = {\n      :api_key => @partner.api_key,\n      :connection_imap_provider_code => @code\n    }\n  end\n\n  test \"index\" do\n    get(:index, @data)\n    assert_response :success\n  end\n\n  test \"create\" do\n    post(:create, @data.merge(:tag => \"TAG\", :email => \"EMAIL\",\n                              :login_username => \"LOGIN_USERNAME\",\n                              :login_password => \"LOGIN_PASSWORD\"))\n    assert_response :success\n\n    user = User.find_by_tag(\"TAG\")\n    assert_equal \"LOGIN_USERNAME\", user.login_username\n    assert_equal \"LOGIN_PASSWORD\", user.login_password_secure\n  end\n\n  test \"create without tag and email\" do\n    post(:create, @data)\n    assert_response :bad_request\n  end\n\n  test \"update\" do\n    post(:update, @data.merge(:tag => @user.tag, :login_username => \"NEW_USERNAME\"))\n    assert_response :success\n    assert \"NEW_USERNAME\", @user.reload.login_username\n  end\n\n  test \"show\" do\n    get(:show, @data.merge(:tag => @user.tag))\n    assert_response :success\n  end\n\n  test \"destroy\" do\n    delete(:destroy, @data.merge(:tag => @user.tag))\n    assert_response :success\n    assert @user.reload.archived\n  end\nend\n"
  },
  {
    "path": "test/fixtures/.keep",
    "content": ""
  },
  {
    "path": "test/fixtures/imap_daemon_heartbeats.yml",
    "content": "# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  tag: MyString\n\ntwo:\n  tag: MyString\n"
  },
  {
    "path": "test/fixtures/tracer_logs.yml",
    "content": "# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  user_id: \n  uid: MyString\n  detected_at: 2014-12-15 14:46:52\n\ntwo:\n  user_id: \n  uid: MyString\n  detected_at: 2014-12-15 14:46:52\n"
  },
  {
    "path": "test/helpers/.keep",
    "content": ""
  },
  {
    "path": "test/imap/rendezvous_hash_test.rb",
    "content": "require 'imap_client'\nrequire 'test_helper'\n\nclass RendezvousHashTest < ActiveSupport::TestCase\n  test \"Hashing\" do\n    site_tags = [\"site 1\", \"site 2\", \"site 3\"]\n    r = ImapClient::RendezvousHash.new\n    r.site_tags = site_tags\n    assert site_tags.include?(r.hash(\"A\"))\n    assert_equal r.hash(\"A\"), r.hash(\"A\")\n    assert_not_equal r.hash(\"A\"), r.hash(\"B\")\n  end\nend\n"
  },
  {
    "path": "test/integration/.keep",
    "content": ""
  },
  {
    "path": "test/mailers/.keep",
    "content": ""
  },
  {
    "path": "test/mailers/previews/tracer_mailer_preview.rb",
    "content": "# Preview all emails at http://localhost:3000/rails/mailers/tracer_mailer\nclass TracerMailerPreview < ActionMailer::Preview\n\nend\n"
  },
  {
    "path": "test/mailers/tracer_mailer_test.rb",
    "content": "require 'test_helper'\n\nclass TracerMailerTest < ActionMailer::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/.keep",
    "content": ""
  },
  {
    "path": "test/models/admin_user_test.rb",
    "content": "require 'test_helper'\n\nclass AdminUserTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/imap_daemon_heartbeat_test.rb",
    "content": "require 'test_helper'\n\nclass ImapDaemonHeartbeatTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/imap_provider_test.rb",
    "content": "require 'test_helper'\n\nclass ImapProviderTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/mail_log_test.rb",
    "content": "require 'test_helper'\n\nclass MailLogTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/partner_connection_test.rb",
    "content": "require 'test_helper'\n\nclass PartnerConnectionTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/partner_credential_test.rb",
    "content": "require 'test_helper'\n\nclass PartnerCredentialTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/partner_test.rb",
    "content": "require 'test_helper'\n\nclass PartnerTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/tracer_log_test.rb",
    "content": "require 'test_helper'\n\nclass TracerLogTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/transmit_log_test.rb",
    "content": "require 'test_helper'\n\nclass TransmitLogTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/models/user_test.rb",
    "content": "require 'test_helper'\n\nclass UserTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "test/test_helper.rb",
    "content": "ENV['RAILS_ENV'] ||= 'test'\nrequire File.expand_path('../../config/environment', __FILE__)\nrequire 'rails/test_help'\n\nclass ActiveSupport::TestCase\n  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.\n  fixtures :all\n\n  # Add more helper methods to be used by all tests here...\nend\n"
  },
  {
    "path": "vendor/assets/javascripts/.keep",
    "content": ""
  },
  {
    "path": "vendor/assets/stylesheets/.keep",
    "content": ""
  }
]