Repository: ndea/notifyor Branch: master Commit: b95878a055ba Files: 20 Total size: 19.9 KB Directory structure: gitextract_lkhu2u5d/ ├── .gitignore ├── .rspec ├── Gemfile ├── MIT-LICENSE ├── README.md ├── Rakefile ├── bin/ │ └── notify_me ├── lib/ │ ├── notifyor/ │ │ ├── cli.rb │ │ ├── configuration.rb │ │ ├── growl/ │ │ │ └── adapters/ │ │ │ ├── libnotify_notifier.rb │ │ │ └── terminal_notifier.rb │ │ ├── growl.rb │ │ ├── plugin.rb │ │ ├── remote/ │ │ │ └── connection.rb │ │ ├── util/ │ │ │ ├── formatter.rb │ │ │ └── os_analyzer.rb │ │ └── version.rb │ └── notifyor.rb ├── notifyor.gemspec └── spec/ └── spec_helper.rb ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .bundle/ log/*.log pkg/ spec/test_app .idea .ruby-gemset .ruby-version ================================================ FILE: .rspec ================================================ --color --require spec_helper ================================================ FILE: Gemfile ================================================ source 'https://rubygems.org' # Declare your gem's dependencies in notifyor.gemspec. # Bundler will treat runtime dependencies like base dependencies, and # development dependencies will be added by default to the :development group. gemspec # Declare any dependencies that are still in development here instead of in # your gemspec. These might include edge Rails or gems from your path or # Git. Remember to move these dependencies to your gemspec before releasing # your gem to rubygems.org. # To use a debugger # gem 'byebug', group: [:development, :test] ================================================ FILE: MIT-LICENSE ================================================ Copyright 2016 Erwin Schens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Notifyor ## [![](http://i.imgur.com/FrRacwt.png)]() Get realtime notifications (growl messages) on your desktop if something happens in your rails app. Notifyor publishes changes to a redis channel. Subscription is performed from your local machine via a ssh tunnel. Simply put: Very growl. Such notifications. Much Notifyor. ## Installation Add this line to your Gemfile: ```ruby gem 'notifyor', '~> 0.8.1' ``` Or install it via rubygems if you just need the CLI. ```bash gem install notifyor ``` And then execute: $ bundle install ## Getting started Run the bundle command to install it. After you install Notifyor create a new file **config/initializers/notifyor.rb** (a rails generator will be available soon for this task). Add the following content to your initializer. ```ruby Notifyor.configure do |config| #config.redis_connection = Redis.new end ``` ### Linux If you want to receive growl notifications on a linux system you have to install the *libnotify-bin*. ```bash sudo apt-get install libnotify-bin ``` ### Mac OS X Notifyor runs out of the box on Mac OS X. Lucky you. ### Windows Currently not supported (see roadmap) ## Usage ### Plugin Notifyor can be plugged into your models by adding the *notifyor* method to your class. ```ruby class SomeClass < ActiveRecord::Base notifyor end ``` By just including the method without options, notifyor will send notifications for the following events: *create*, *update* and *destroy*. The default message is the i18n key **notifyor.model.[create | update | destroy]** you have to provide in your application. If you want to customize this message you can provide the following option to the notifyor method: ```ruby class SomeClass < ActiveRecord::Base notifyor messages: { create: -> (model) { "My Message for model #{model.id}." }, update: -> (model) { "My Message for model #{model.id}." }, destroy: -> (model) { "My Message for model #{model.id}." } } end ``` If you dont want to receive a notification for a certain action just add the **only** option to notifyor. ```ruby class SomeClass < ActiveRecord::Base notifyor only: [:create] end ``` The default channel on which notifyor publishes messages is 'notifyor'. This can be changed via the **channel** option. You can provide multiple channels and notifyor will publish messages on them. (See the channel option on the CLI to subscribe to those channels). ```ruby class SomeClass < ActiveRecord::Base notifyor channels: ['channel1', 'channel2'] end ``` ### CLI The CLI can be used independently just install the gem and run following command. ```bash notify_me --ssh-host some_host --ssh-port some_port --ssh-user some_user ``` #### Arguments for the CLI - **ssh-host** Provide the ssh host to which notifyor should connect to. (Default is localhost) - **ssh-port** Provide the ssh port on which notifyor should connect to. (Default is 22) - **ssh-user** Provide the ssh user for your remote server. (Please use ssh keys so that you just have to provide the *ssh-host*. -> Security reasons) - **tunnel-port** The tunnel port on which ssh will establish the connection. (Default is 2000) - **redis-port** The port of your redis server (Default is 6379) - **channel** Listen on another channel. Every message received on this channel will be displayed in a growl notification. (Default is notifyor) **If you dont provide a ssh host notifyor will subscribe from your local redis and display them.** Every notify_me instance is an individual subscriber so multiple users can receive growl messages. ## Roadmap - Notifications for multiple OS (currently only Mac OS X and Linux systems with libnotify-lib installed.) - Provide own logo in the growl notification - Specs - Documentation ## Development After checking out the repo, run `bundle install` to install dependencies. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing 1. Fork it ( https://github.com/[my-github-username]/notifyor/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ================================================ FILE: Rakefile ================================================ begin require 'bundler/setup' rescue LoadError puts 'You must `gem install bundler` and `bundle install` to run rake tasks' end require 'rdoc/task' RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'Notifyor' rdoc.options << '--line-numbers' rdoc.rdoc_files.include('README.rdoc') rdoc.rdoc_files.include('lib/**/*.rb') end Bundler::GemHelper.install_tasks require 'rake/testtask' Rake::TestTask.new(:test) do |t| t.libs << 'lib' t.libs << 'test' t.pattern = 'test/**/*_test.rb' t.verbose = false end task default: :test ================================================ FILE: bin/notify_me ================================================ #! /usr/bin/env ruby require 'notifyor/cli' require 'notifyor/remote/connection' begin cli = ::Notifyor::CLI.new cli.parse cli.check_notifications rescue => e STDERR.puts e.message STDERR.puts e.backtrace.join("\n") exit 1 end ================================================ FILE: lib/notifyor/cli.rb ================================================ require 'notifyor/version' require 'optparse' module Notifyor class CLI def parse # Default configuration. ENV['ssh_host'] = 'localhost' ENV['ssh_port'] = '22' ENV['ssh_tunnel_port'] = '2000' ENV['ssh_redis_port'] = '6379' ::OptionParser.new do |opts| opts.banner = 'Usage: notify_me [options]' opts.on('-v', '--version', 'Show the current version of this gem') do puts "Notifyor Version: #{::Notifyor::VERSION}"; exit end opts.on('--ssh-host host', 'Provide the host address to your deployment/remote server') do |host| ENV['ssh_host'] = host end opts.on('--ssh-port port', 'Provide the ssh port for the deployment/remote server') do |port| ENV['ssh_port'] = port end opts.on('--ssh-user user', 'Provide the ssh user for the deployment/remote server') do |user| ENV['ssh_user'] = user end opts.on('--tunnel-port tunnel_port', 'Provide the ssh user for the deployment/remote server') do |tunnel_port| ENV['ssh_tunnel_port'] = tunnel_port end opts.on('--redis-port redis_port', 'Provide the ssh user for the deployment/remote server') do |redis_port| ENV['ssh_redis_port'] = redis_port end opts.on('--channel [channel]', 'Provide channel on which notifyor should listen.') do |channel| ENV['channel'] = channel end end.parse! end def check_notifications connection = Notifyor::Remote::Connection.new begin connection.build_tunnel connection.build_redis_tunnel_connection connection.subscribe_to_redis rescue => e STDOUT.write "Could not establish SSH tunnel. Reason: #{e.message}" end end end end ================================================ FILE: lib/notifyor/configuration.rb ================================================ require 'redis' require 'connection_pool' module Notifyor class Configuration attr_accessor :redis_connection def initialize @redis_connection = ::Redis.new end end end ================================================ FILE: lib/notifyor/growl/adapters/libnotify_notifier.rb ================================================ module Notifyor module Growl module Adapters module LibnotifyNotifier extend self def create_growl(title, message) %x(notify-send '#{title}' '#{message}') end end end end end ================================================ FILE: lib/notifyor/growl/adapters/terminal_notifier.rb ================================================ require 'terminal-notifier' module Notifyor module Growl module Adapters module TerminalNotifier extend self def create_growl(title, message) ::TerminalNotifier.notify(message, :title => title) end end end end end ================================================ FILE: lib/notifyor/growl.rb ================================================ require 'notifyor/util/os_analyzer' module Notifyor module Growl extend self def adapter return @adapter if @adapter self.adapter = case ::Notifyor::Util::OSAnalyzer.os when :macosx :terminal_notifier when :linux :libnotify_notifier when :unix :libnotify_notifier else raise 'Operating system not recognized.' end @adapter end def adapter=(adapter_name) case adapter_name when Symbol, String require "notifyor/growl/adapters/#{adapter_name}" @adapter = Notifyor::Growl::Adapters.const_get("#{adapter_name.to_s.split('_').collect(&:capitalize).join}") else raise "Missing adapter #{adapter_name}" end end def create_growl(title, message) adapter.create_growl(title, message) end end end ================================================ FILE: lib/notifyor/plugin.rb ================================================ require 'active_support' require 'redis' module Notifyor module Plugin extend ::ActiveSupport::Concern included do end module ClassMethods def notifyor(options = {}) configure_plugin(options) end def configure_plugin(options = {}) configuration = default_configuration.deep_merge(options) publish_channels = configuration[:channels] || ['notifyor'] append_callbacks(configuration, publish_channels) end def append_callbacks(configuration, publish_channels) publish_channels.each do |channel| configuration[:only].each do |action| case action when :create self.after_commit -> { ::Notifyor.configuration.redis_connection.publish channel, configuration[:messages][:create].call(self) }, on: :create, if: -> { configuration[:only].include? :create } when :update self.after_commit -> { ::Notifyor.configuration.redis_connection.publish channel, configuration[:messages][:update].call(self) }, on: :update, if: -> { configuration[:only].include? :update } when :destroy self.before_destroy -> { ::Notifyor.configuration.redis_connection.publish channel, configuration[:messages][:destroy].call(self) }, if: -> { configuration[:only].include? :destroy } else #nop end end end end def default_configuration { only: [:create, :destroy, :update], messages: { create: -> (model) { I18n.t('notifyor.model.create') }, update: -> (model) { I18n.t('notifyor.model.update') }, destroy: -> (model) { I18n.t('notifyor.model.destroy') } } } end end end end ================================================ FILE: lib/notifyor/remote/connection.rb ================================================ require 'json' require 'redis' require 'notifyor/growl' require 'notifyor/util/formatter' require 'net/ssh/gateway' module Notifyor module Remote class Connection def initialize @ssh_host = ENV['ssh_host'] || 'localhost' @ssh_port = ENV['ssh_port'] || '22' @ssh_user = ENV['ssh_user'] @tunnel_port = ENV['ssh_tunnel_port'] || '2000' @redis_port = ENV['ssh_redis_port'] || '6379' @redis_channel = ENV['channel'] || 'notifyor' @ssh_gateway = nil @redis_tunnel_connection = nil end def build_tunnel unless ['127.0.0.1', 'localhost'].include? @ssh_host @ssh_gateway = Net::SSH::Gateway.new(@ssh_host, @ssh_user, port: @ssh_port) @ssh_gateway.open('127.0.0.1', @redis_port, @tunnel_port) end end def build_redis_tunnel_connection redis_port = (['127.0.0.1', 'localhost'].include? @ssh_host) ? @redis_port : @tunnel_port @redis_tunnel_connection = Redis.new(port: redis_port) end def subscribe_to_redis @redis_tunnel_connection.subscribe(@redis_channel) do |on| on.message do |channel, msg| STDERR.write "INFO - Message received on channel: #{channel} \n" growl_message(msg) end end end def growl_message(message) ::Notifyor::Growl.create_growl("Notifyor", message) unless Notifyor::Util::Formatter.squish!(message).empty? end end end end ================================================ FILE: lib/notifyor/util/formatter.rb ================================================ module Notifyor module Util module Formatter extend self def squish!(string) string.gsub!(/\A[[:space:]]+/, '') string.gsub!(/[[:space:]]+\z/, '') string.gsub!(/[[:space:]]+/, ' ') string end end end end ================================================ FILE: lib/notifyor/util/os_analyzer.rb ================================================ require 'rbconfig' module Notifyor module Util module OSAnalyzer extend self def os host_os = RbConfig::CONFIG['host_os'] case host_os when /mswin|msys|mingw|cygwin|bccwin|wince|emc/ :windows when /darwin|mac os/ :macosx when /linux/ :linux when /solaris|bsd/ :unix else raise "unknown os: #{host_os.inspect}" end end end end end ================================================ FILE: lib/notifyor/version.rb ================================================ module Notifyor VERSION = "0.8.1" end ================================================ FILE: lib/notifyor.rb ================================================ $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'notifyor/plugin' require 'notifyor/configuration' module Notifyor class << self attr_accessor :configuration end def self.configure self.configuration ||= Configuration.new yield(configuration) if block_given? end ActiveRecord::Base.send(:include, ::Notifyor::Plugin) if defined?(ActiveRecord) end ================================================ FILE: notifyor.gemspec ================================================ $:.push File.expand_path("../lib", __FILE__) require "notifyor/version" Gem::Specification.new do |s| s.name = "notifyor" s.version = Notifyor::VERSION s.authors = ["Erwin Schens"] s.email = ["erwin.schens@qurasoft.de"] s.homepage = "https://github.com/ndea/notifyer" s.summary = "Get realtime notifications on your desktop if something happens in your Rails app." s.description = "Notifyer creates growl notifications on your desktop if something happens in your Rails app." s.license = "MIT" s.executables = ["notify_me"] s.require_paths = ["lib"] s.files = Dir["{app,config,db,lib,bin}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["spec/**/*"] s.add_dependency 'redis' s.add_dependency 'connection_pool' s.add_dependency 'terminal-notifier' s.add_dependency 'net-ssh' s.add_dependency 'net-ssh-gateway' s.add_development_dependency "sqlite3" s.add_development_dependency "rspec", "~> 3.4.0" end ================================================ FILE: spec/spec_helper.rb ================================================ # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end