ws_chatter 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (51) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/Rakefile +34 -0
  4. data/lib/assets/javascripts/ws_chatter.js.coffee +23 -0
  5. data/lib/rails/generators/ws_chatter/install_generator.rb +79 -0
  6. data/lib/rails/generators/ws_chatter/templates/message.rb +6 -0
  7. data/lib/rails/generators/ws_chatter/templates/messages_migration.rb +14 -0
  8. data/lib/rails/generators/ws_chatter/templates/users_migration.rb +5 -0
  9. data/lib/rails/generators/ws_chatter/templates/ws_chatter.rb +5 -0
  10. data/lib/tasks/ws_chatter_tasks.rake +4 -0
  11. data/lib/ws_chatter.rb +18 -0
  12. data/lib/ws_chatter/engine.rb +7 -0
  13. data/lib/ws_chatter/version.rb +3 -0
  14. data/lib/ws_chatter/ws_chatter_middleware.rb +114 -0
  15. data/test/dummy/README.rdoc +28 -0
  16. data/test/dummy/Rakefile +6 -0
  17. data/test/dummy/app/assets/javascripts/application.js +13 -0
  18. data/test/dummy/app/assets/stylesheets/application.css +15 -0
  19. data/test/dummy/app/controllers/application_controller.rb +5 -0
  20. data/test/dummy/app/helpers/application_helper.rb +2 -0
  21. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  22. data/test/dummy/bin/bundle +3 -0
  23. data/test/dummy/bin/rails +4 -0
  24. data/test/dummy/bin/rake +4 -0
  25. data/test/dummy/bin/setup +29 -0
  26. data/test/dummy/config.ru +4 -0
  27. data/test/dummy/config/application.rb +26 -0
  28. data/test/dummy/config/boot.rb +5 -0
  29. data/test/dummy/config/database.yml +25 -0
  30. data/test/dummy/config/environment.rb +5 -0
  31. data/test/dummy/config/environments/development.rb +41 -0
  32. data/test/dummy/config/environments/production.rb +79 -0
  33. data/test/dummy/config/environments/test.rb +42 -0
  34. data/test/dummy/config/initializers/assets.rb +11 -0
  35. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  36. data/test/dummy/config/initializers/cookies_serializer.rb +3 -0
  37. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  38. data/test/dummy/config/initializers/inflections.rb +16 -0
  39. data/test/dummy/config/initializers/mime_types.rb +4 -0
  40. data/test/dummy/config/initializers/session_store.rb +3 -0
  41. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  42. data/test/dummy/config/locales/en.yml +23 -0
  43. data/test/dummy/config/routes.rb +56 -0
  44. data/test/dummy/config/secrets.yml +22 -0
  45. data/test/dummy/public/404.html +67 -0
  46. data/test/dummy/public/422.html +67 -0
  47. data/test/dummy/public/500.html +66 -0
  48. data/test/dummy/public/favicon.ico +0 -0
  49. data/test/test_helper.rb +20 -0
  50. data/test/ws_chatter_test.rb +7 -0
  51. metadata +200 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2f7ad3f543bb9a07ea5672267a0dc411f295d4d1
4
+ data.tar.gz: f7fa59445c51c6e466be3624344177b7da5de280
5
+ SHA512:
6
+ metadata.gz: 75154305e8ddcd8218371a4515acc4406ece1526a592ce3cd2a9b8e44c5a770ab1c950b49c3917a141ea9f34f708b333052141a50a2495fce4c1abbfaa7130b7
7
+ data.tar.gz: 9299f042e729e7761d633f6a980830ea88625f00d8409e5f08b8ac680a787293ae1dfb17feabd7b99312e29134aba9e13e17b7492f7164c3b9f767cad43879e5
@@ -0,0 +1,20 @@
1
+ Copyright 2015 codebaker95
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,34 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'WsChatter'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.rdoc')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+
18
+
19
+
20
+
21
+
22
+ Bundler::GemHelper.install_tasks
23
+
24
+ require 'rake/testtask'
25
+
26
+ Rake::TestTask.new(:test) do |t|
27
+ t.libs << 'lib'
28
+ t.libs << 'test'
29
+ t.pattern = 'test/**/*_test.rb'
30
+ t.verbose = false
31
+ end
32
+
33
+
34
+ task default: :test
@@ -0,0 +1,23 @@
1
+ class @WsChatter
2
+ constructor: (onmessage, onconnection) ->
3
+ @ws = new WebSocket "ws://#{location.host}"
4
+ @ws.onmessage = (event) ->
5
+ data = JSON.parse(event.data)
6
+ if data.type is "message"
7
+ onmessage data.user_id, data.message, data.time
8
+ else if data.type is "connection"
9
+ onconnection data.user_id, data.online
10
+
11
+ send: (user_id, message) ->
12
+ @ws.send JSON.stringify
13
+ type: "message"
14
+ user_id: user_id
15
+ message: message
16
+
17
+ read: (user_id) ->
18
+ @ws.send JSON.stringify
19
+ type: "read"
20
+ user_id: user_id
21
+
22
+ close: ->
23
+ @ws.close()
@@ -0,0 +1,79 @@
1
+ require 'rails/generators/active_record/migration'
2
+
3
+ module WsChatter
4
+ class InstallGenerator < Rails::Generators::Base
5
+ include ActiveRecord::Generators::Migration
6
+
7
+ source_root File.expand_path("../templates", __FILE__)
8
+
9
+ desc "Installs ws_chatter in the rails app"
10
+
11
+ class_option :scope, type: :string, default: "user", desc: "Name of the (existing) model for users"
12
+ class_option :status_column, type: :string, default: "online", desc: "Name of the status column for the user model"
13
+ class_option :messages, type: :string, default: "message", desc: "Name of the messages model"
14
+
15
+ def inject_ws_chatter
16
+ if File.exist?(manifest)
17
+ comment_prefix = File.extname(manifest) == ".coffee" ? "#" : "//"
18
+ require_ws_chatter = "#{comment_prefix}= require ws_chatter\n"
19
+
20
+ manifest_contents = File.read(manifest)
21
+
22
+ if manifest_contents.include? 'require turbolinks'
23
+ inject_into_file manifest, require_ws_chatter, after: "#{comment_prefix}= require turbolinks\n"
24
+ elsif manifest_contents.include? 'require_tree'
25
+ inject_into_file manifest, require_ws_chatter, before: "#{comment_prefix}= require_tree"
26
+ end
27
+ end
28
+ end
29
+
30
+ def copy_initializer
31
+ template "ws_chatter.rb", "config/initializers/ws_chatter.rb"
32
+ end
33
+
34
+ def copy_users_migration
35
+ migration_template "users_migration.rb", "db/migrate/add_#{status_column}_to_#{table_name}.rb"
36
+ end
37
+
38
+ def copy_messages_migration
39
+ migration_template "messages_migration.rb", "db/migrate/create_#{messages_table}.rb"
40
+ end
41
+
42
+ def copy_messages_model
43
+ template "message.rb", "app/models/#{messages}.rb"
44
+ end
45
+
46
+ private
47
+ def scope
48
+ @scope ||= options[:scope].underscore
49
+ end
50
+
51
+ def table_name
52
+ @table_name ||= scope.pluralize
53
+ end
54
+
55
+ def model_name
56
+ @model_name ||= scope.camelize
57
+ end
58
+
59
+ def status_column
60
+ @status_column ||= options[:status_column].underscore
61
+ end
62
+
63
+ def messages
64
+ @messages ||= options[:messages].underscore
65
+ end
66
+
67
+ def messages_table
68
+ @messages_table ||= messages.pluralize
69
+ end
70
+
71
+ def messages_model
72
+ @messages_model ||= messages.camelize
73
+ end
74
+
75
+ def manifest
76
+ Dir[File.join(destination_root, "app/assets/javascripts/application.*")][0]
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,6 @@
1
+ class <%= messages_model %> < ActiveRecord::Base
2
+ belongs_to :sender, class_name: "<%= model_name %>"
3
+ belongs_to :recipient, class_name: "<%= model_name %>"
4
+
5
+ validates :body, presence: true
6
+ end
@@ -0,0 +1,14 @@
1
+ class Create<%= messages_table.camelize %> < ActiveRecord::Migration
2
+ def change
3
+ create_table :<%= messages_table %> do |t|
4
+ t.integer :sender_id
5
+ t.integer :recipient_id
6
+ t.text :body
7
+ t.boolean :unread, default: true
8
+
9
+ t.timestamps null: false
10
+ end
11
+ add_index :<%= messages_table %>, :sender_id
12
+ add_index :<%= messages_table %>, :recipient_id
13
+ end
14
+ end
@@ -0,0 +1,5 @@
1
+ class Add<%= status_column.camelize %>To<%= table_name.camelize %> < ActiveRecord::Migration
2
+ def change
3
+ add_column :<%= table_name %>, :<%= status_column %>, :boolean, default: false
4
+ end
5
+ end
@@ -0,0 +1,5 @@
1
+ WsChatter.setup do |config|
2
+ config.scope = :<%= scope %>
3
+ config.status_column = :<%= status_column %>
4
+ config.messages_model = "<%= messages_model %>"
5
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :ws_chatter do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,18 @@
1
+ require "configurations"
2
+ require "ws_chatter/engine"
3
+ require "ws_chatter/ws_chatter_middleware"
4
+
5
+ module WsChatter
6
+ include Configurations
7
+
8
+ class << self
9
+ alias_method :setup, :configure
10
+ alias_method :config, :configuration
11
+ end
12
+
13
+ configuration_defaults do |config|
14
+ config.scope = :user
15
+ config.status_column = :online
16
+ config.messages_model = "Messages"
17
+ end
18
+ end
@@ -0,0 +1,7 @@
1
+ module WsChatter
2
+ class Engine < Rails::Engine
3
+ initializer "ws_chatter.add_middleware" do |app|
4
+ app.middleware.use WsChatter::WsChatterMiddleware
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,3 @@
1
+ module WsChatter
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,114 @@
1
+ require "erb"
2
+ require "json"
3
+ require "faye/websocket"
4
+
5
+ module WsChatter
6
+ class WsChatterMiddleware
7
+ KEEPALIVE_TIME = 15
8
+
9
+ def initialize(app)
10
+ @app = app
11
+ @clients = []
12
+ @scope = WsChatter.config.scope
13
+ @status_column = WsChatter.config.status_column
14
+ @messages_model = WsChatter.config.messages_model.constantize
15
+ @users_model = @scope.to_s.camelize.constantize
16
+ end
17
+
18
+ def call(env)
19
+ if Faye::WebSocket.websocket?(env)
20
+ ws = Faye::WebSocket.new(env, nil, ping: KEEPALIVE_TIME)
21
+
22
+ user = authenticate(env)
23
+ if !user
24
+ ws.close
25
+ return ws.rack_response
26
+ end
27
+
28
+ ws.on :open do
29
+ puts " WsChatter: New connection from user: \e[1m#{user.username}\e[22m"
30
+ add_client(user, ws)
31
+ end
32
+
33
+ ws.on :message do |event|
34
+ data = parse_message(event.data)
35
+ case data["type"]
36
+ when "read" then read_messages(data["user_id"], user)
37
+ when "message" then send_message(data, user)
38
+ end
39
+ end
40
+
41
+ ws.on :close do |event|
42
+ puts " WsChatter: Closed connection with user: \e[1m#{user.username}\e[22m (code: #{event.code})"
43
+ remove_client(user, ws)
44
+ end
45
+
46
+ ws.rack_response
47
+ else
48
+ @app.call(env)
49
+ end
50
+ end
51
+
52
+ private
53
+ def authenticate(env)
54
+ env["warden"].authenticate(scope: @scope) if env["warden"]
55
+ end
56
+
57
+ def parse_message(message)
58
+ data = JSON.parse(message)
59
+ data.each {|key, value| data[key] = ERB::Util.html_escape(value)}
60
+ data
61
+ end
62
+
63
+ def send_to(user_id, message)
64
+ @clients.each do |client|
65
+ if client.id == user_id
66
+ client.send(message)
67
+ end
68
+ end
69
+ end
70
+
71
+ def send_to_all(message)
72
+ @clients.each { |client| client.send(message)}
73
+ end
74
+
75
+ def add_client(user, ws)
76
+ @clients << Client.new(user, ws)
77
+ set_status(user, true)
78
+ end
79
+
80
+ def remove_client(user, ws)
81
+ @clients.delete_if { |client| client.connection == ws }
82
+ set_status(user, false) if @clients.none? { |client| client.id == user.id }
83
+ end
84
+
85
+ def set_status(user, status)
86
+ user.update(@status_column => status)
87
+ send_to_all(type: "connection", user_id: user.id, online: status)
88
+ end
89
+
90
+ def send_message(data, user)
91
+ data["user_id"] = data["user_id"].to_i
92
+ msg = @messages_model.create(sender: user, recipient_id: data["user_id"], body: data["message"])
93
+ send_to(data["user_id"], type: "message", user_id: user.id, message: data["message"], time: msg.created_at)
94
+ end
95
+
96
+ def read_messages(user_id, user)
97
+ Message.where(recipient: user, sender_id: user_id, unread: true).update_all(unread: false)
98
+ end
99
+
100
+ class Client
101
+ attr_reader :id, :user, :connection
102
+
103
+ def initialize(user, connection)
104
+ @id = user.id
105
+ @connection = connection
106
+ @user = user
107
+ end
108
+
109
+ def send(message)
110
+ @connection.send(message.to_json)
111
+ end
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,28 @@
1
+ == README
2
+
3
+ This README would normally document whatever steps are necessary to get the
4
+ application up and running.
5
+
6
+ Things you may want to cover:
7
+
8
+ * Ruby version
9
+
10
+ * System dependencies
11
+
12
+ * Configuration
13
+
14
+ * Database creation
15
+
16
+ * Database initialization
17
+
18
+ * How to run the test suite
19
+
20
+ * Services (job queues, cache servers, search engines, etc.)
21
+
22
+ * Deployment instructions
23
+
24
+ * ...
25
+
26
+
27
+ Please feel free to use a different markup language if you do not plan to run
28
+ <tt>rake doc:app</tt>.
@@ -0,0 +1,6 @@
1
+ # Add your own tasks in files placed in lib/tasks ending in .rake,
2
+ # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3
+
4
+ require File.expand_path('../config/application', __FILE__)
5
+
6
+ Rails.application.load_tasks
@@ -0,0 +1,13 @@
1
+ // This is a manifest file that'll be compiled into application.js, which will include all the files
2
+ // listed below.
3
+ //
4
+ // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5
+ // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6
+ //
7
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8
+ // compiled file.
9
+ //
10
+ // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11
+ // about supported directives.
12
+ //
13
+ //= require_tree .
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any styles
10
+ * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
11
+ * file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,5 @@
1
+ class ApplicationController < ActionController::Base
2
+ # Prevent CSRF attacks by raising an exception.
3
+ # For APIs, you may want to use :null_session instead.
4
+ protect_from_forgery with: :exception
5
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
6
+ <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>