federal_offense 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (37) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +107 -0
  4. data/Rakefile +34 -0
  5. data/app/assets/config/federal_offense_manifest.js +2 -0
  6. data/app/assets/javascripts/federal_offense/application.js +7 -0
  7. data/app/assets/javascripts/federal_offense/cable.js +18 -0
  8. data/app/assets/javascripts/federal_offense/vendor/action_cable.js +601 -0
  9. data/app/assets/stylesheets/federal_offense/application.css +33 -0
  10. data/app/assets/stylesheets/federal_offense/components/article.css +5 -0
  11. data/app/assets/stylesheets/federal_offense/components/aside.css +9 -0
  12. data/app/assets/stylesheets/federal_offense/components/empty.css +27 -0
  13. data/app/assets/stylesheets/federal_offense/components/link.css +4 -0
  14. data/app/assets/stylesheets/federal_offense/components/list.css +87 -0
  15. data/app/assets/stylesheets/federal_offense/components/main.css +9 -0
  16. data/app/assets/stylesheets/federal_offense/components/message.css +13 -0
  17. data/app/assets/stylesheets/federal_offense/components/nav.css +30 -0
  18. data/app/assets/stylesheets/federal_offense/components/section.css +6 -0
  19. data/app/assets/stylesheets/federal_offense/components/table.css +18 -0
  20. data/app/channels/federal_offense/application_cable/channel.rb +8 -0
  21. data/app/channels/federal_offense/application_cable/connection.rb +8 -0
  22. data/app/channels/federal_offense/inbox_channel.rb +16 -0
  23. data/app/controllers/federal_offense/application_controller.rb +6 -0
  24. data/app/controllers/federal_offense/messages_controller.rb +55 -0
  25. data/app/helpers/federal_offense/application_helper.rb +10 -0
  26. data/app/models/federal_offense/message.rb +141 -0
  27. data/app/views/federal_offense/messages/index.html.erb +6 -0
  28. data/app/views/federal_offense/messages/show.html.erb +30 -0
  29. data/app/views/layouts/federal_offense/application.html.erb +96 -0
  30. data/config/locales/en.yml +18 -0
  31. data/config/routes.rb +17 -0
  32. data/lib/federal_offense.rb +11 -0
  33. data/lib/federal_offense/engine.rb +57 -0
  34. data/lib/federal_offense/interceptor.rb +10 -0
  35. data/lib/federal_offense/version.rb +5 -0
  36. data/lib/tasks/federal_offense_tasks.rake +9 -0
  37. metadata +283 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 72a753592cc61bfb16aa40f12c821def2d9a5b19d1420d6656d023f50528765a
4
+ data.tar.gz: 31da2e309fc35f087665fbc3e347b26a1434f9baf157c955cb961f7f904ea969
5
+ SHA512:
6
+ metadata.gz: 7ad12b89234faad79ecf3858b3faef262cca1b3ff571404a6d4db3e87335010589d1d48f53d8790d4cf5afea4dae8f162e2fdeaf3713616417d80558f5c8ba42
7
+ data.tar.gz: 1340009c960bd94aee253855c7d7b5d3e972b8ccbcdc9d40f39295a24ffd2077559bb5d9df92c44894313133c51a58e5aa3be4ba509031f4c5a700150ebdbb2e
@@ -0,0 +1,20 @@
1
+ Copyright 2020 Flip Sasser
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,107 @@
1
+ # Federal Offense
2
+
3
+ Federal Offense intercepts outbound emails in Rails and allows you to preview them in your browser. It's like Rails mailer previews, but it doesn't make you write code. It's like Mailcatcher, but doesn't install Eventmachine and can be run inside a Docker container without problems.
4
+
5
+ <div style="margin: 1em 3em;">
6
+
7
+ ![Screenshot of Federal Offense inbox](https://github.com/flipsasser/federal_offense/blob/master/screenshot.png?raw=true)
8
+
9
+ </div>
10
+
11
+ ### Table of contents
12
+
13
+ aka "Proof that I love you"
14
+
15
+ 1. [Installation](#installation)
16
+ 2. [Usage](#usage)
17
+ 3. [Reason this Exists](#why-does-this-exist)
18
+ 4. [Switching from Mailcatcher](#switching-from-mailcatcher)
19
+ 5. [OH MY GOD THIS SECTION IS SO IMPORTANT WHY IS IT NEAR THE END OF THE README](#production-warning-for-the-love-of-god-heed-mine-words)
20
+ 6. [Contributing](#contributing)
21
+ 7. [Leesawns](#license)
22
+
23
+ ## Installation
24
+
25
+ Federal Offense assumes you're on the latest Rails (Rails 6). It does this because I'm using the latest Rails (Rails 6).
26
+
27
+ I am in no way opposed to it working for olders Railses (Rails not-6), but I don't really know why you'd bother. Then again, nothing it uses is new. Whatever. Your call. I'd love a pull request. I'd love just to chat, to be honest. It's lonely in quarantine.
28
+
29
+ Aaaaaaanyway, add it to your Gemfile **in the development environment**:
30
+
31
+ ```ruby
32
+ group :development do
33
+ gem "federal_offense"
34
+ end
35
+ ```
36
+
37
+ Also I've seen people do this; I don't love it for maintenance reasons but you're welcome to do, like, whatever you want:
38
+
39
+ ```ruby
40
+ gem "federal_offense", group: :development
41
+ ```
42
+
43
+ Right, now run `bundle install`. Obviously. You knew that.
44
+
45
+ ## Usage
46
+
47
+ Okay! Let's talk about using the thing, shall we?
48
+
49
+ Once you've [installed it](#Installation), the only thing you *must* do is add it to your routes:
50
+
51
+ ```ruby
52
+ Rails.application.routes.draw do
53
+ resources :doodads
54
+ mount FederalOffense::Engine => "/deliveries" if Rails.env.development? # This is the super important part
55
+ end
56
+ ```
57
+
58
+ After that, when your dev server is running, you can access every outbound email by visiting [`http://localhost:3000/deliveries`](http://localhost:3000/deliveries). So generate an email and refresh that URL.
59
+
60
+ ### ActionCable
61
+
62
+ Just so's you know, if your app uses ActionCable, Federal Offense will try to use it, too. The end result is an inbox that auto-updates as emails come in. It will piggyback on your app's `cable.yml` configuration, which I figure is safe in development. If you're a real grump, you can copy `config/cable.yml` to `config/federal_offense_cable.yml` and add your own stuff there.
63
+
64
+ Anyhoo, that's that.
65
+
66
+ ### Caching
67
+
68
+ Federal Offense caches all of your email as JSON in `tmp/federal_offense`. You may want to blast that out periodically. One option is to run
69
+
70
+ ```sh
71
+ rails federal_offense:clear_inbox
72
+ ```
73
+
74
+ ...which will, you know, get rid of those pesky files. Maybe I'll add some auto-cache-clearing in the future; I dunno, I'm sleepy.
75
+
76
+ ## Why does this exist????
77
+
78
+ This is here because, FFS, previewing email in Rails is important. Since time immemorial, Mailcatcher has been the gold standard - and it very much still is, *especially* if you're not using Rails (but if you're not using Rails, you can **very, very, VERY safely close this browser tab** because I am adding no value to your life whatsoever).
79
+
80
+ **HOWEVER,** it's a real PITA to point a Docker instance to a Mailcatcher SMTP server. So I did this instead. Enjoy. Or don't; I don't actually care.
81
+
82
+ ## Switching from Mailcatcher
83
+
84
+ If you've been using Mailcatcher and want to stop, which for the record I think Mailcatcher is an absolutely amazing library that has made my life infinitely better for years and should by all means continue to be used by you and everyone else you know, including the people you know who don't know how to write code or what Mailcatcher or SMTP is, which is probably most of them, you should know that FederalOffense **does not spin up an SMTP server.**
85
+
86
+ What this means for you, practically, is that you may have done one, possibly, two things. Those things are:
87
+
88
+ 1. Set `raise_delivery_errors` to `true` somewhere in your environments (presumably `config/environments/development.rb`). If that's the case, **you may want to switch that back off if you're pointing to a Mailcatcher SMTP server you no longer intend to use, which again, use Mailcatcher it's freakin awesome, even though this gem was specifically designed to replace it which doesn't mean I don't absolutely love that gem or the people who made it.**
89
+ 2. Configured `smtp_settings` to point to Mailcatcher, also probably in `config/environments/development.rb`. If that's the case, you can maybe delete that? I dunno. Your call.
90
+
91
+ Anyhoo. The important thing is **Federal Offense will not boot an SMTP server so if you turn Mailcatcher off and keep pointing to its (now-disappeared) SMTP endpoint, you will be disappointed**.
92
+
93
+ ## PRODUCTION WARNING FOR THE LOVE OF GOD HEED MINE WORDS
94
+
95
+ As I've covered exhaustively thus far, this is a Rails engine which makes **all of the email** your app generates **available** at a **publicly accessible URL.** What this means for you is, **NEVER EVER EVER EVER EVER EVER EVER EVER EVER** let this thing leak out into production.
96
+
97
+ 1. **ALWAYS** ensure it lives in the `development` group of your Gemfile.
98
+ 2. **ALWAYS** add an `if defined?(FederalOffense)` or `if Rails.env.development?` guard before you mount it in `routes.rb`
99
+ 3. **NEVER** come crying to me when you deploy it to production and, yup, it hits an `abort` tripwire that I added to ensure you don't accidently expose all of your app's private communication to the universe. I mean, I'm all about radical transparency but like... don't be silly.
100
+
101
+ ## Contributing
102
+
103
+ Create a pull request. This is a simple little library with ~~no test coverage~~ some test coverage (gosh). Oh I should write tests. I normally do. I just, you know... didn't this time.
104
+
105
+ ## License
106
+
107
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ require "bundler/setup"
5
+ rescue LoadError
6
+ puts "You must `gem install bundler` and `bundle install` to run rake tasks"
7
+ end
8
+
9
+ require "rdoc/task"
10
+
11
+ RDoc::Task.new(:rdoc) do |rdoc|
12
+ rdoc.rdoc_dir = "rdoc"
13
+ rdoc.title = "FederalOffense"
14
+ rdoc.options << "--line-numbers"
15
+ rdoc.rdoc_files.include("README.md")
16
+ rdoc.rdoc_files.include("lib/**/*.rb")
17
+ end
18
+
19
+ APP_RAKEFILE = File.expand_path("spec/dummy/Rakefile", __dir__)
20
+ load "rails/tasks/engine.rake"
21
+
22
+ load "rails/tasks/statistics.rake"
23
+
24
+ require "bundler/gem_tasks"
25
+
26
+ # require "rake/testtask"
27
+
28
+ # Rake::TestTask.new(:test) do |t|
29
+ # t.libs << "spec"
30
+ # t.pattern = "spec/**/*_test.rb"
31
+ # t.verbose = false
32
+ # end
33
+
34
+ # task default: :test
@@ -0,0 +1,2 @@
1
+ //= link_directory ../javascripts/federal_offense .js
2
+ //= link_directory ../stylesheets/federal_offense .css
@@ -0,0 +1,7 @@
1
+ //= require rails-ujs
2
+
3
+ document.querySelectorAll("a[disabled]").forEach(function(link) {
4
+ link.addEventListener("click", function(event) {
5
+ event.preventDefault()
6
+ })
7
+ })
@@ -0,0 +1,18 @@
1
+ //= require ./vendor/action_cable
2
+
3
+ const consumer = ActionCable.createConsumer()
4
+ consumer.subscriptions.create("FederalOffense::InboxChannel", {
5
+ connected: () => {
6
+ /* NOOP */
7
+ },
8
+ disconnected: () => {
9
+ /* NOOP */
10
+ },
11
+ received(data) {
12
+ if (data.reload) {
13
+ window.location.reload()
14
+ } else if (data.location) {
15
+ window.location = data.location
16
+ }
17
+ },
18
+ })
@@ -0,0 +1,601 @@
1
+ (function() {
2
+ var context = this;
3
+
4
+ (function() {
5
+ (function() {
6
+ var slice = [].slice;
7
+
8
+ this.ActionCable = {
9
+ INTERNAL: {
10
+ "message_types": {
11
+ "welcome": "welcome",
12
+ "ping": "ping",
13
+ "confirmation": "confirm_subscription",
14
+ "rejection": "reject_subscription"
15
+ },
16
+ "default_mount_path": "/cable",
17
+ "protocols": ["actioncable-v1-json", "actioncable-unsupported"]
18
+ },
19
+ WebSocket: window.WebSocket,
20
+ logger: window.console,
21
+ createConsumer: function(url) {
22
+ var ref;
23
+ if (url == null) {
24
+ url = (ref = this.getConfig("url")) != null ? ref : this.INTERNAL.default_mount_path;
25
+ }
26
+ return new ActionCable.Consumer(this.createWebSocketURL(url));
27
+ },
28
+ getConfig: function(name) {
29
+ var element;
30
+ element = document.head.querySelector("meta[name='action-cable-" + name + "']");
31
+ return element != null ? element.getAttribute("content") : void 0;
32
+ },
33
+ createWebSocketURL: function(url) {
34
+ var a;
35
+ if (url && !/^wss?:/i.test(url)) {
36
+ a = document.createElement("a");
37
+ a.href = url;
38
+ a.href = a.href;
39
+ a.protocol = a.protocol.replace("http", "ws");
40
+ return a.href;
41
+ } else {
42
+ return url;
43
+ }
44
+ },
45
+ startDebugging: function() {
46
+ return this.debugging = true;
47
+ },
48
+ stopDebugging: function() {
49
+ return this.debugging = null;
50
+ },
51
+ log: function() {
52
+ var messages, ref;
53
+ messages = 1 <= arguments.length ? slice.call(arguments, 0) : [];
54
+ if (this.debugging) {
55
+ messages.push(Date.now());
56
+ return (ref = this.logger).log.apply(ref, ["[ActionCable]"].concat(slice.call(messages)));
57
+ }
58
+ }
59
+ };
60
+
61
+ }).call(this);
62
+ }).call(context);
63
+
64
+ var ActionCable = context.ActionCable;
65
+
66
+ (function() {
67
+ (function() {
68
+ var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
69
+
70
+ ActionCable.ConnectionMonitor = (function() {
71
+ var clamp, now, secondsSince;
72
+
73
+ ConnectionMonitor.pollInterval = {
74
+ min: 3,
75
+ max: 30
76
+ };
77
+
78
+ ConnectionMonitor.staleThreshold = 6;
79
+
80
+ function ConnectionMonitor(connection) {
81
+ this.connection = connection;
82
+ this.visibilityDidChange = bind(this.visibilityDidChange, this);
83
+ this.reconnectAttempts = 0;
84
+ }
85
+
86
+ ConnectionMonitor.prototype.start = function() {
87
+ if (!this.isRunning()) {
88
+ this.startedAt = now();
89
+ delete this.stoppedAt;
90
+ this.startPolling();
91
+ document.addEventListener("visibilitychange", this.visibilityDidChange);
92
+ return ActionCable.log("ConnectionMonitor started. pollInterval = " + (this.getPollInterval()) + " ms");
93
+ }
94
+ };
95
+
96
+ ConnectionMonitor.prototype.stop = function() {
97
+ if (this.isRunning()) {
98
+ this.stoppedAt = now();
99
+ this.stopPolling();
100
+ document.removeEventListener("visibilitychange", this.visibilityDidChange);
101
+ return ActionCable.log("ConnectionMonitor stopped");
102
+ }
103
+ };
104
+
105
+ ConnectionMonitor.prototype.isRunning = function() {
106
+ return (this.startedAt != null) && (this.stoppedAt == null);
107
+ };
108
+
109
+ ConnectionMonitor.prototype.recordPing = function() {
110
+ return this.pingedAt = now();
111
+ };
112
+
113
+ ConnectionMonitor.prototype.recordConnect = function() {
114
+ this.reconnectAttempts = 0;
115
+ this.recordPing();
116
+ delete this.disconnectedAt;
117
+ return ActionCable.log("ConnectionMonitor recorded connect");
118
+ };
119
+
120
+ ConnectionMonitor.prototype.recordDisconnect = function() {
121
+ this.disconnectedAt = now();
122
+ return ActionCable.log("ConnectionMonitor recorded disconnect");
123
+ };
124
+
125
+ ConnectionMonitor.prototype.startPolling = function() {
126
+ this.stopPolling();
127
+ return this.poll();
128
+ };
129
+
130
+ ConnectionMonitor.prototype.stopPolling = function() {
131
+ return clearTimeout(this.pollTimeout);
132
+ };
133
+
134
+ ConnectionMonitor.prototype.poll = function() {
135
+ return this.pollTimeout = setTimeout((function(_this) {
136
+ return function() {
137
+ _this.reconnectIfStale();
138
+ return _this.poll();
139
+ };
140
+ })(this), this.getPollInterval());
141
+ };
142
+
143
+ ConnectionMonitor.prototype.getPollInterval = function() {
144
+ var interval, max, min, ref;
145
+ ref = this.constructor.pollInterval, min = ref.min, max = ref.max;
146
+ interval = 5 * Math.log(this.reconnectAttempts + 1);
147
+ return Math.round(clamp(interval, min, max) * 1000);
148
+ };
149
+
150
+ ConnectionMonitor.prototype.reconnectIfStale = function() {
151
+ if (this.connectionIsStale()) {
152
+ ActionCable.log("ConnectionMonitor detected stale connection. reconnectAttempts = " + this.reconnectAttempts + ", pollInterval = " + (this.getPollInterval()) + " ms, time disconnected = " + (secondsSince(this.disconnectedAt)) + " s, stale threshold = " + this.constructor.staleThreshold + " s");
153
+ this.reconnectAttempts++;
154
+ if (this.disconnectedRecently()) {
155
+ return ActionCable.log("ConnectionMonitor skipping reopening recent disconnect");
156
+ } else {
157
+ ActionCable.log("ConnectionMonitor reopening");
158
+ return this.connection.reopen();
159
+ }
160
+ }
161
+ };
162
+
163
+ ConnectionMonitor.prototype.connectionIsStale = function() {
164
+ var ref;
165
+ return secondsSince((ref = this.pingedAt) != null ? ref : this.startedAt) > this.constructor.staleThreshold;
166
+ };
167
+
168
+ ConnectionMonitor.prototype.disconnectedRecently = function() {
169
+ return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;
170
+ };
171
+
172
+ ConnectionMonitor.prototype.visibilityDidChange = function() {
173
+ if (document.visibilityState === "visible") {
174
+ return setTimeout((function(_this) {
175
+ return function() {
176
+ if (_this.connectionIsStale() || !_this.connection.isOpen()) {
177
+ ActionCable.log("ConnectionMonitor reopening stale connection on visibilitychange. visbilityState = " + document.visibilityState);
178
+ return _this.connection.reopen();
179
+ }
180
+ };
181
+ })(this), 200);
182
+ }
183
+ };
184
+
185
+ now = function() {
186
+ return new Date().getTime();
187
+ };
188
+
189
+ secondsSince = function(time) {
190
+ return (now() - time) / 1000;
191
+ };
192
+
193
+ clamp = function(number, min, max) {
194
+ return Math.max(min, Math.min(max, number));
195
+ };
196
+
197
+ return ConnectionMonitor;
198
+
199
+ })();
200
+
201
+ }).call(this);
202
+ (function() {
203
+ var i, message_types, protocols, ref, supportedProtocols, unsupportedProtocol,
204
+ slice = [].slice,
205
+ bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
206
+ indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
207
+
208
+ ref = ActionCable.INTERNAL, message_types = ref.message_types, protocols = ref.protocols;
209
+
210
+ supportedProtocols = 2 <= protocols.length ? slice.call(protocols, 0, i = protocols.length - 1) : (i = 0, []), unsupportedProtocol = protocols[i++];
211
+
212
+ ActionCable.Connection = (function() {
213
+ Connection.reopenDelay = 500;
214
+
215
+ function Connection(consumer) {
216
+ this.consumer = consumer;
217
+ this.open = bind(this.open, this);
218
+ this.subscriptions = this.consumer.subscriptions;
219
+ this.monitor = new ActionCable.ConnectionMonitor(this);
220
+ this.disconnected = true;
221
+ }
222
+
223
+ Connection.prototype.send = function(data) {
224
+ if (this.isOpen()) {
225
+ this.webSocket.send(JSON.stringify(data));
226
+ return true;
227
+ } else {
228
+ return false;
229
+ }
230
+ };
231
+
232
+ Connection.prototype.open = function() {
233
+ if (this.isActive()) {
234
+ ActionCable.log("Attempted to open WebSocket, but existing socket is " + (this.getState()));
235
+ return false;
236
+ } else {
237
+ ActionCable.log("Opening WebSocket, current state is " + (this.getState()) + ", subprotocols: " + protocols);
238
+ if (this.webSocket != null) {
239
+ this.uninstallEventHandlers();
240
+ }
241
+ this.webSocket = new ActionCable.WebSocket(this.consumer.url, protocols);
242
+ this.installEventHandlers();
243
+ this.monitor.start();
244
+ return true;
245
+ }
246
+ };
247
+
248
+ Connection.prototype.close = function(arg) {
249
+ var allowReconnect, ref1;
250
+ allowReconnect = (arg != null ? arg : {
251
+ allowReconnect: true
252
+ }).allowReconnect;
253
+ if (!allowReconnect) {
254
+ this.monitor.stop();
255
+ }
256
+ if (this.isActive()) {
257
+ return (ref1 = this.webSocket) != null ? ref1.close() : void 0;
258
+ }
259
+ };
260
+
261
+ Connection.prototype.reopen = function() {
262
+ var error;
263
+ ActionCable.log("Reopening WebSocket, current state is " + (this.getState()));
264
+ if (this.isActive()) {
265
+ try {
266
+ return this.close();
267
+ } catch (error1) {
268
+ error = error1;
269
+ return ActionCable.log("Failed to reopen WebSocket", error);
270
+ } finally {
271
+ ActionCable.log("Reopening WebSocket in " + this.constructor.reopenDelay + "ms");
272
+ setTimeout(this.open, this.constructor.reopenDelay);
273
+ }
274
+ } else {
275
+ return this.open();
276
+ }
277
+ };
278
+
279
+ Connection.prototype.getProtocol = function() {
280
+ var ref1;
281
+ return (ref1 = this.webSocket) != null ? ref1.protocol : void 0;
282
+ };
283
+
284
+ Connection.prototype.isOpen = function() {
285
+ return this.isState("open");
286
+ };
287
+
288
+ Connection.prototype.isActive = function() {
289
+ return this.isState("open", "connecting");
290
+ };
291
+
292
+ Connection.prototype.isProtocolSupported = function() {
293
+ var ref1;
294
+ return ref1 = this.getProtocol(), indexOf.call(supportedProtocols, ref1) >= 0;
295
+ };
296
+
297
+ Connection.prototype.isState = function() {
298
+ var ref1, states;
299
+ states = 1 <= arguments.length ? slice.call(arguments, 0) : [];
300
+ return ref1 = this.getState(), indexOf.call(states, ref1) >= 0;
301
+ };
302
+
303
+ Connection.prototype.getState = function() {
304
+ var ref1, state, value;
305
+ for (state in WebSocket) {
306
+ value = WebSocket[state];
307
+ if (value === ((ref1 = this.webSocket) != null ? ref1.readyState : void 0)) {
308
+ return state.toLowerCase();
309
+ }
310
+ }
311
+ return null;
312
+ };
313
+
314
+ Connection.prototype.installEventHandlers = function() {
315
+ var eventName, handler;
316
+ for (eventName in this.events) {
317
+ handler = this.events[eventName].bind(this);
318
+ this.webSocket["on" + eventName] = handler;
319
+ }
320
+ };
321
+
322
+ Connection.prototype.uninstallEventHandlers = function() {
323
+ var eventName;
324
+ for (eventName in this.events) {
325
+ this.webSocket["on" + eventName] = function() {};
326
+ }
327
+ };
328
+
329
+ Connection.prototype.events = {
330
+ message: function(event) {
331
+ var identifier, message, ref1, type;
332
+ if (!this.isProtocolSupported()) {
333
+ return;
334
+ }
335
+ ref1 = JSON.parse(event.data), identifier = ref1.identifier, message = ref1.message, type = ref1.type;
336
+ switch (type) {
337
+ case message_types.welcome:
338
+ this.monitor.recordConnect();
339
+ return this.subscriptions.reload();
340
+ case message_types.ping:
341
+ return this.monitor.recordPing();
342
+ case message_types.confirmation:
343
+ return this.subscriptions.notify(identifier, "connected");
344
+ case message_types.rejection:
345
+ return this.subscriptions.reject(identifier);
346
+ default:
347
+ return this.subscriptions.notify(identifier, "received", message);
348
+ }
349
+ },
350
+ open: function() {
351
+ ActionCable.log("WebSocket onopen event, using '" + (this.getProtocol()) + "' subprotocol");
352
+ this.disconnected = false;
353
+ if (!this.isProtocolSupported()) {
354
+ ActionCable.log("Protocol is unsupported. Stopping monitor and disconnecting.");
355
+ return this.close({
356
+ allowReconnect: false
357
+ });
358
+ }
359
+ },
360
+ close: function(event) {
361
+ ActionCable.log("WebSocket onclose event");
362
+ if (this.disconnected) {
363
+ return;
364
+ }
365
+ this.disconnected = true;
366
+ this.monitor.recordDisconnect();
367
+ return this.subscriptions.notifyAll("disconnected", {
368
+ willAttemptReconnect: this.monitor.isRunning()
369
+ });
370
+ },
371
+ error: function() {
372
+ return ActionCable.log("WebSocket onerror event");
373
+ }
374
+ };
375
+
376
+ return Connection;
377
+
378
+ })();
379
+
380
+ }).call(this);
381
+ (function() {
382
+ var slice = [].slice;
383
+
384
+ ActionCable.Subscriptions = (function() {
385
+ function Subscriptions(consumer) {
386
+ this.consumer = consumer;
387
+ this.subscriptions = [];
388
+ }
389
+
390
+ Subscriptions.prototype.create = function(channelName, mixin) {
391
+ var channel, params, subscription;
392
+ channel = channelName;
393
+ params = typeof channel === "object" ? channel : {
394
+ channel: channel
395
+ };
396
+ subscription = new ActionCable.Subscription(this.consumer, params, mixin);
397
+ return this.add(subscription);
398
+ };
399
+
400
+ Subscriptions.prototype.add = function(subscription) {
401
+ this.subscriptions.push(subscription);
402
+ this.consumer.ensureActiveConnection();
403
+ this.notify(subscription, "initialized");
404
+ this.sendCommand(subscription, "subscribe");
405
+ return subscription;
406
+ };
407
+
408
+ Subscriptions.prototype.remove = function(subscription) {
409
+ this.forget(subscription);
410
+ if (!this.findAll(subscription.identifier).length) {
411
+ this.sendCommand(subscription, "unsubscribe");
412
+ }
413
+ return subscription;
414
+ };
415
+
416
+ Subscriptions.prototype.reject = function(identifier) {
417
+ var i, len, ref, results, subscription;
418
+ ref = this.findAll(identifier);
419
+ results = [];
420
+ for (i = 0, len = ref.length; i < len; i++) {
421
+ subscription = ref[i];
422
+ this.forget(subscription);
423
+ this.notify(subscription, "rejected");
424
+ results.push(subscription);
425
+ }
426
+ return results;
427
+ };
428
+
429
+ Subscriptions.prototype.forget = function(subscription) {
430
+ var s;
431
+ this.subscriptions = (function() {
432
+ var i, len, ref, results;
433
+ ref = this.subscriptions;
434
+ results = [];
435
+ for (i = 0, len = ref.length; i < len; i++) {
436
+ s = ref[i];
437
+ if (s !== subscription) {
438
+ results.push(s);
439
+ }
440
+ }
441
+ return results;
442
+ }).call(this);
443
+ return subscription;
444
+ };
445
+
446
+ Subscriptions.prototype.findAll = function(identifier) {
447
+ var i, len, ref, results, s;
448
+ ref = this.subscriptions;
449
+ results = [];
450
+ for (i = 0, len = ref.length; i < len; i++) {
451
+ s = ref[i];
452
+ if (s.identifier === identifier) {
453
+ results.push(s);
454
+ }
455
+ }
456
+ return results;
457
+ };
458
+
459
+ Subscriptions.prototype.reload = function() {
460
+ var i, len, ref, results, subscription;
461
+ ref = this.subscriptions;
462
+ results = [];
463
+ for (i = 0, len = ref.length; i < len; i++) {
464
+ subscription = ref[i];
465
+ results.push(this.sendCommand(subscription, "subscribe"));
466
+ }
467
+ return results;
468
+ };
469
+
470
+ Subscriptions.prototype.notifyAll = function() {
471
+ var args, callbackName, i, len, ref, results, subscription;
472
+ callbackName = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
473
+ ref = this.subscriptions;
474
+ results = [];
475
+ for (i = 0, len = ref.length; i < len; i++) {
476
+ subscription = ref[i];
477
+ results.push(this.notify.apply(this, [subscription, callbackName].concat(slice.call(args))));
478
+ }
479
+ return results;
480
+ };
481
+
482
+ Subscriptions.prototype.notify = function() {
483
+ var args, callbackName, i, len, results, subscription, subscriptions;
484
+ subscription = arguments[0], callbackName = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
485
+ if (typeof subscription === "string") {
486
+ subscriptions = this.findAll(subscription);
487
+ } else {
488
+ subscriptions = [subscription];
489
+ }
490
+ results = [];
491
+ for (i = 0, len = subscriptions.length; i < len; i++) {
492
+ subscription = subscriptions[i];
493
+ results.push(typeof subscription[callbackName] === "function" ? subscription[callbackName].apply(subscription, args) : void 0);
494
+ }
495
+ return results;
496
+ };
497
+
498
+ Subscriptions.prototype.sendCommand = function(subscription, command) {
499
+ var identifier;
500
+ identifier = subscription.identifier;
501
+ return this.consumer.send({
502
+ command: command,
503
+ identifier: identifier
504
+ });
505
+ };
506
+
507
+ return Subscriptions;
508
+
509
+ })();
510
+
511
+ }).call(this);
512
+ (function() {
513
+ ActionCable.Subscription = (function() {
514
+ var extend;
515
+
516
+ function Subscription(consumer, params, mixin) {
517
+ this.consumer = consumer;
518
+ if (params == null) {
519
+ params = {};
520
+ }
521
+ this.identifier = JSON.stringify(params);
522
+ extend(this, mixin);
523
+ }
524
+
525
+ Subscription.prototype.perform = function(action, data) {
526
+ if (data == null) {
527
+ data = {};
528
+ }
529
+ data.action = action;
530
+ return this.send(data);
531
+ };
532
+
533
+ Subscription.prototype.send = function(data) {
534
+ return this.consumer.send({
535
+ command: "message",
536
+ identifier: this.identifier,
537
+ data: JSON.stringify(data)
538
+ });
539
+ };
540
+
541
+ Subscription.prototype.unsubscribe = function() {
542
+ return this.consumer.subscriptions.remove(this);
543
+ };
544
+
545
+ extend = function(object, properties) {
546
+ var key, value;
547
+ if (properties != null) {
548
+ for (key in properties) {
549
+ value = properties[key];
550
+ object[key] = value;
551
+ }
552
+ }
553
+ return object;
554
+ };
555
+
556
+ return Subscription;
557
+
558
+ })();
559
+
560
+ }).call(this);
561
+ (function() {
562
+ ActionCable.Consumer = (function() {
563
+ function Consumer(url) {
564
+ this.url = url;
565
+ this.subscriptions = new ActionCable.Subscriptions(this);
566
+ this.connection = new ActionCable.Connection(this);
567
+ }
568
+
569
+ Consumer.prototype.send = function(data) {
570
+ return this.connection.send(data);
571
+ };
572
+
573
+ Consumer.prototype.connect = function() {
574
+ return this.connection.open();
575
+ };
576
+
577
+ Consumer.prototype.disconnect = function() {
578
+ return this.connection.close({
579
+ allowReconnect: false
580
+ });
581
+ };
582
+
583
+ Consumer.prototype.ensureActiveConnection = function() {
584
+ if (!this.connection.isActive()) {
585
+ return this.connection.open();
586
+ }
587
+ };
588
+
589
+ return Consumer;
590
+
591
+ })();
592
+
593
+ }).call(this);
594
+ }).call(this);
595
+
596
+ if (typeof module === "object" && module.exports) {
597
+ module.exports = ActionCable;
598
+ } else if (typeof define === "function" && define.amd) {
599
+ define(ActionCable);
600
+ }
601
+ }).call(this);