Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit 2fee23410bb1e71e8d82f0e805d79711747b0561 1 parent 8aef903
@M7 M7 authored
Showing with 2,394 additions and 66 deletions.
  1. +24 −0 .gitignore
  2. +55 −0 .rvmrc
  3. +58 −0 Gemfile
  4. +7 −0 Rakefile
  5. BIN  app/assets/images/rails.png
  6. +15 −0 app/assets/javascripts/application.js
  7. +3 −0  app/assets/javascripts/tasks.js.coffee
  8. +3 −0  app/assets/javascripts/whenbot.js.coffee
  9. +13 −0 app/assets/stylesheets/application.css
  10. +3 −0  app/assets/stylesheets/tasks.css.scss
  11. +3 −0  app/assets/stylesheets/whenbot.css.scss
  12. +3 −0  app/controllers/application_controller.rb
  13. +8 −0 app/controllers/tasks_controller.rb
  14. +31 −0 app/controllers/whenbot_controller.rb
  15. +2 −0  app/helpers/application_helper.rb
  16. +2 −0  app/helpers/tasks_helper.rb
  17. +2 −0  app/helpers/whenbot_helper.rb
  18. 0  app/mailers/.gitkeep
  19. 0  app/models/.gitkeep
  20. +7 −0 app/models/action.rb
  21. +4 −0 app/models/authentication.rb
  22. +21 −0 app/models/task.rb
  23. +96 −0 app/models/trigger.rb
  24. +14 −0 app/views/layouts/application.html.erb
  25. +5 −0 app/views/tasks/_channels.html.erb
  26. +2 −0  app/views/tasks/index.html.erb
  27. +5 −0 app/views/tasks/new.html.erb
  28. +4 −0 config.ru
  29. +60 −0 config/application.rb
  30. +6 −0 config/boot.rb
  31. +60 −0 config/database.yml.example
  32. +5 −0 config/environment.rb
  33. +37 −0 config/environments/development.rb
  34. +67 −0 config/environments/production.rb
  35. +37 −0 config/environments/test.rb
  36. +7 −0 config/initializers/backtrace_silencers.rb
  37. +15 −0 config/initializers/inflections.rb
  38. +5 −0 config/initializers/mime_types.rb
  39. +18 −0 config/initializers/require_lib_files.rb
  40. +7 −0 config/initializers/secret_token.rb
  41. +8 −0 config/initializers/session_store.rb
  42. +7 −0 config/initializers/whenbot.rb
  43. +14 −0 config/initializers/wrap_parameters.rb
  44. +5 −0 config/locales/en.yml
  45. +65 −0 config/routes.rb
  46. +24 −0 db/migrate/20120419221210_create_triggers.rb
  47. +18 −0 db/migrate/20120419230901_create_actions.rb
  48. +12 −0 db/migrate/20120419233318_create_authentications.rb
  49. +13 −0 db/migrate/20120419234122_create_tasks.rb
  50. +71 −0 db/schema.rb
  51. +7 −0 db/seeds.rb
  52. +2 −0  doc/README_FOR_APP
  53. +0 −8 factories/users.rb
  54. 0  lib/assets/.gitkeep
  55. 0  lib/tasks/.gitkeep
  56. +104 −0 lib/whenbot.rb
  57. +5 −0 lib/whenbot/channel.rb
  58. +25 −0 lib/whenbot/channels/developer/actions/do_some_event.rb
  59. +14 −0 lib/whenbot/channels/developer/service.rb
  60. +220 −0 lib/whenbot/channels/developer/triggers/sample_search.rb
  61. +11 −0 lib/whenbot/channels/twitter/service.rb
  62. +56 −0 lib/whenbot/channels/twitter/triggers/new_tweet_from.rb
  63. +19 −0 lib/whenbot/trigger.rb
  64. +3 −0  lib/whenbot/version.rb
  65. 0  log/.gitkeep
  66. +26 −0 public/404.html
  67. +26 −0 public/422.html
  68. +25 −0 public/500.html
  69. 0  public/favicon.ico
  70. +241 −0 public/index.html
  71. +5 −0 public/robots.txt
  72. +6 −0 script/rails
  73. +0 −58 spec/models/action_spec.rb
  74. +13 −0 test/factories/actions.rb
  75. +8 −0 test/factories/authentications.rb
  76. +13 −0 test/factories/tasks.rb
  77. +36 −0 test/factories/triggers.rb
  78. 0  test/functional/.gitkeep
  79. +14 −0 test/functional/tasks_controller_test.rb
  80. +37 −0 test/functional/whenbot_controller_test.rb
  81. 0  test/integration/.gitkeep
  82. +18 −0 test/integration/task_flows_test.rb
  83. +12 −0 test/performance/browsing_test.rb
  84. +39 −0 test/test_helper.rb
  85. 0  test/unit/.gitkeep
  86. +7 −0 test/unit/action_test.rb
  87. +7 −0 test/unit/authentication_test.rb
  88. +4 −0 test/unit/helpers/tasks_helper_test.rb
  89. +4 −0 test/unit/helpers/whenbot_helper_test.rb
  90. +46 −0 test/unit/task_test.rb
  91. +128 −0 test/unit/trigger_test.rb
  92. +127 −0 test/unit/triggers/sample_search_test.rb
  93. +107 −0 test/unit/triggers/trigger_conformance_test.rb
  94. +28 −0 test/unit/whenbot_test.rb
  95. 0  vendor/assets/javascripts/.gitkeep
  96. 0  vendor/assets/stylesheets/.gitkeep
  97. 0  vendor/plugins/.gitkeep
View
24 .gitignore
@@ -0,0 +1,24 @@
+# See http://help.github.com/ignore-files/ for more about ignoring files.
+#
+# If you find yourself ignoring temporary files generated by your text editor
+# or operating system, you probably want to add a global ignore instead:
+# git config --global core.excludesfile ~/.gitignore_global
+
+# Ignore bundler config
+/.bundle
+
+# Ignore the default SQLite database.
+/db/*.sqlite3
+
+# Ignore all logfiles and tempfiles.
+/log/*.log
+/tmp
+
+# This code will be Open Source, so don't include files with sensitive data
+/config/database.yml
+
+# Ignore .watchr file
+/.watchr
+
+# Random files to ignore
+/lib/whenbot/old_trigger.rb
View
55 .rvmrc
@@ -0,0 +1,55 @@
+#!/usr/bin/env bash
+
+# This is an RVM Project .rvmrc file, used to automatically load the ruby
+# development environment upon cd'ing into the directory
+
+# First we specify our desired <ruby>[@<gemset>], the @gemset name is optional.
+environment_id="ruby-1.9.3-p125@whenbot"
+
+#
+# Uncomment following line if you want options to be set only for given project.
+#
+# PROJECT_JRUBY_OPTS=( --1.9 )
+
+#
+# First we attempt to load the desired environment directly from the environment
+# file. This is very fast and efficient compared to running through the entire
+# CLI and selector. If you want feedback on which environment was used then
+# insert the word 'use' after --create as this triggers verbose mode.
+#
+if [[ -d "${rvm_path:-$HOME/.rvm}/environments" \
+ && -s "${rvm_path:-$HOME/.rvm}/environments/$environment_id" ]]
+then
+ \. "${rvm_path:-$HOME/.rvm}/environments/$environment_id"
+
+ if [[ -s "${rvm_path:-$HOME/.rvm}/hooks/after_use" ]]
+ then
+ . "${rvm_path:-$HOME/.rvm}/hooks/after_use"
+ fi
+else
+ # If the environment file has not yet been created, use the RVM CLI to select.
+ if ! rvm --create "$environment_id"
+ then
+ echo "Failed to create RVM environment '${environment_id}'."
+ exit 1
+ fi
+fi
+
+#
+# If you use an RVM gemset file to install a list of gems (*.gems), you can have
+# it be automatically loaded. Uncomment the following and adjust the filename if
+# necessary.
+#
+# filename=".gems"
+# if [[ -s "$filename" ]]
+# then
+# rvm gemset import "$filename" | grep -v already | grep -v listed | grep -v complete | sed '/^$/d'
+# fi
+
+# If you use bundler, this might be useful to you:
+# if command -v bundle && [[ -s Gemfile ]]
+# then
+# bundle install
+# fi
+
+
View
58 Gemfile
@@ -0,0 +1,58 @@
+source 'https://rubygems.org'
+
+gem 'rails', '3.2.3'
+
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+
+gem 'pg'
+
+
+# Gems used only for assets and not required
+# in production environments by default.
+group :assets do
+ gem 'sass-rails', '~> 3.2.3'
+ gem 'coffee-rails', '~> 3.2.1'
+
+ # See https://github.com/sstephenson/execjs#readme for more supported runtimes
+ gem 'therubyracer', :platform => :ruby
+
+ gem 'uglifier', '>= 1.0.3'
+end
+
+gem 'jquery-rails'
+
+gem 'heroku'
+
+group :test, :development do
+ gem 'awesome_print'
+ gem 'factory_girl_rails'
+end
+
+group :development do
+ #gem 'ruby-debug19', :require => 'ruby-debug' # To use debugger
+ gem 'rails-footnotes', '>= 3.7'
+end
+
+group :test do
+ gem 'test-unit' # not bundled with ruby 1.9
+ gem 'capybara', :git => 'git://github.com/jnicklas/capybara.git' # For #has_text?
+ gem 'database_cleaner' # For Capybara. See test_helper.rb for details
+ gem 'mocha', :require => false
+ gem 'shoulda'
+end
+
+# To use ActiveModel has_secure_password
+# gem 'bcrypt-ruby', '~> 3.0.0'
+
+# To use Jbuilder templates for JSON
+# gem 'jbuilder'
+
+# Use unicorn as the app server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano'
+
+# To use debugger
+# gem 'ruby-debug19', :require => 'ruby-debug'
View
7 Rakefile
@@ -0,0 +1,7 @@
+#!/usr/bin/env rake
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+
+Whenbot::Application.load_tasks
View
BIN  app/assets/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
15 app/assets/javascripts/application.js
@@ -0,0 +1,15 @@
+// This is a manifest file that'll be compiled into application.js, which will include all the files
+// listed below.
+//
+// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
+// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+//
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// the compiled file.
+//
+// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
+// GO AFTER THE REQUIRES BELOW.
+//
+//= require jquery
+//= require jquery_ujs
+//= require_tree .
View
3  app/assets/javascripts/tasks.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
View
3  app/assets/javascripts/whenbot.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
View
13 app/assets/stylesheets/application.css
@@ -0,0 +1,13 @@
+/*
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
+ * listed below.
+ *
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
+ * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ *
+ * You're free to add application-wide styles to this file and they'll appear at the top of the
+ * compiled file, but it's generally better to create a new file per style scope.
+ *
+ *= require_self
+ *= require_tree .
+*/
View
3  app/assets/stylesheets/tasks.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the tasks controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
View
3  app/assets/stylesheets/whenbot.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the Whenbot controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
View
3  app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
View
8 app/controllers/tasks_controller.rb
@@ -0,0 +1,8 @@
+class TasksController < ApplicationController
+ def index
+ end
+
+ def new
+ # ==== One-liner 12 ====
+ end
+end
View
31 app/controllers/whenbot_controller.rb
@@ -0,0 +1,31 @@
+class WhenbotController < ApplicationController
+
+ # /whenbot/:channel/:trigger/callback
+ def callback
+
+ # ==== One-liner 13 ====
+ # ==== One-liner 14 ====
+
+ if response[:head_only]
+ # ==== One-liner 15 ====
+ else
+ render response[:type] => response[:body],
+ :status => response[:status],
+ :layout => false
+ end
+ end
+
+ private
+
+ def validate_response(response)
+ # ==== One-liner 16 ====
+ response[:head_only] ||= response[:body] ? false : true
+ response[:status] ||= :ok
+ response[:type] ||= :json
+ response[:headers] ||= ''
+ response[:body] ||= 'Success'
+ # ==== One-liner 17 ====
+ end
+
+
+end
View
2  app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
View
2  app/helpers/tasks_helper.rb
@@ -0,0 +1,2 @@
+module TasksHelper
+end
View
2  app/helpers/whenbot_helper.rb
@@ -0,0 +1,2 @@
+module WhenbotHelper
+end
View
0  app/mailers/.gitkeep
No changes.
View
0  app/models/.gitkeep
No changes.
View
7 app/models/action.rb
@@ -0,0 +1,7 @@
+class Action < ActiveRecord::Base
+ belongs_to :task
+
+ serialize :parameters, Hash
+ serialize :extra_data, Hash
+ attr_accessible :channel, :action, :parameters, :active
+end
View
4 app/models/authentication.rb
@@ -0,0 +1,4 @@
+class Authentication < ActiveRecord::Base
+ serialize :parameters, Hash
+ attr_accessible :channel, :parameters
+end
View
21 app/models/task.rb
@@ -0,0 +1,21 @@
+class Task < ActiveRecord::Base
+ # ==== One-liner 18 ====
+ # ==== One-liner 19 ====
+
+ accepts_nested_attributes_for :triggers, :actions
+
+ # ==== One-liner 20 ====
+
+ #
+ # Handles calling the appropriate Trigger's #callback method,
+ # saves the match data to the table, and runs the Action(s) if
+ # its conditions are met.
+ #
+ def self.handle_callback(channel, trigger, params, headers, body)
+ triggers, trigger_ids = Trigger.triggers_for(channel, trigger)
+ returned_triggers, response = Whenbot.relay_callback(channel, trigger, triggers, params, headers, body)
+ # ==== One-liner 21 ====
+ # ==== One-liner 22 ====
+ end
+
+end
View
96 app/models/trigger.rb
@@ -0,0 +1,96 @@
+class Trigger < ActiveRecord::Base
+ # ==== One-liner 23 ====
+
+ # ==== One-liner 24 ====
+ # ==== One-liner 25 ====
+ # ==== One-liner 26 ====
+ # ==== One-liner 27 ====
+ # ==== One-liner 28 ====
+ # ==== One-liner 29 ====
+
+
+ #
+ # Returns all active triggers for the requested Channel and Trigger
+ #
+ def self.triggers_for(channel, trigger)
+ records = where("channel = ? AND trigger = ?", channel.to_s.camelize, trigger.to_s.camelize).
+ select([:id, :channel, :trigger, :parameters, :match_data, :extra_data, :last_matched]).
+ active
+ convert_for_matching(records)
+ end
+
+ #
+ # Saves triggers that either have their :save or
+ # :matched flag set
+ def self.save_updated_triggers(triggers, trigger_ids)
+ save_updated_hash(triggers, trigger_ids)
+ end
+
+ private
+
+ #
+ # Creates an array of hashes to be passed to the Trigger
+ # via its #callback method. The Trigger will fill in
+ # the array[n][:match_data] if there's a match, and
+ # can use array[n][:extra_data] to store data that
+ # it may need later.
+ #
+ # Another array of ids is returned to keep track of
+ # which records should be updated.
+ #
+ # We do this to avoid passing around actual records.
+ # A Trigger only needs to concern itself with certain
+ # things, and shouldn't be playing with table data.
+ #
+ # Hash Values:
+ #
+ # :save => Signals that the hash was updated and
+ # should be saved
+ # :matched => New match was found, and stored in
+ # :match_data. Data will be saved
+ # even if :save isn't set to true
+ # :parameters => Parameters saved from the user
+ # :match_data => Match data that's saved to be
+ # used by the Action (i.e. the
+ # data to be used by Liquid)
+ # :extra_data => Use this to store any data
+ # you want to receive next time
+ # :last_matched => Time that this Trigger last
+ # had a match.
+ def self.convert_for_matching(records)
+ array = Array.new
+ ids_array = Array.new
+
+ triggers = Array(records)
+ triggers.each do |trigger|
+ hash = Hash.new
+ hash[:save] = false
+ hash[:match_found] = false
+ hash[:parameters] = trigger.parameters || {}
+ hash[:match_data] = trigger.match_data || {}
+ hash[:extra_data] = trigger.extra_data || {}
+ hash[:last_matched] = trigger.last_matched
+ array << hash
+ ids_array << trigger.id
+ end
+ return array, ids_array
+ end
+
+ def self.save_updated_hash(triggers, trigger_ids)
+ triggers.each_with_index do |trigger, index|
+ if trigger[:save] || trigger[:match]
+ record = Trigger.find(trigger_ids[index])
+
+ if trigger[:save]
+ trigger.each_pair do |key, value|
+ record.send("#{key}=", value) if record.respond_to? "#{key}=".to_sym
+ end
+ elsif trigger[:match_found]
+ record.match_data = trigger[:match_data]
+ end
+
+ record.save! if record.changed?
+ end
+ end
+ end
+end
View
14 app/views/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Whenbot</title>
+ <%= stylesheet_link_tag "application", :media => "all" %>
+ <%= javascript_include_tag "application" %>
+ <%= csrf_meta_tags %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
View
5 app/views/tasks/_channels.html.erb
@@ -0,0 +1,5 @@
+<% channels.each do |channel| %>
+ <div class="channel">
+ <h3><%= channel %></h3>
+ </div>
+<% end %>
View
2  app/views/tasks/index.html.erb
@@ -0,0 +1,2 @@
+<h1>Tasks#index</h1>
+<p>Find me in app/views/tasks/index.html.erb</p>
View
5 app/views/tasks/new.html.erb
@@ -0,0 +1,5 @@
+<h1>Create New Task</h1>
+<div class="trigger_channels">
+ <h2>Trigger Channels</h2>
+ <%= render 'channels', channels: @channels %>
+</div>
View
4 config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Whenbot::Application
View
60 config/application.rb
@@ -0,0 +1,60 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+if defined?(Bundler)
+ # If you precompile assets before deploying to production, use this line
+ Bundler.require(*Rails.groups(:assets => %w(development test)))
+ # If you want your assets lazily compiled in production, use this line
+ # Bundler.require(:default, :assets, Rails.env)
+end
+
+module Whenbot
+ class Application < Rails::Application
+ # Settings in config/environments/* take precedence over those specified here.
+ # Application configuration should go into files in config/initializers
+ # -- all .rb files in that directory are automatically loaded.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ config.autoload_paths += Dir["#{config.root}/lib"]
+ # Was: config.autoload_paths += Dir["#{config.root}/lib", "#{config.root}/lib/**/"]
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named.
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running.
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ # config.time_zone = 'Central Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+
+ # Use SQL instead of Active Record's schema dumper when creating the database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Enforce whitelist mode for mass assignment.
+ # This will create an empty whitelist of attributes available for mass-assignment for all models
+ # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
+ # parameters by using an attr_accessible or attr_protected declaration.
+ config.active_record.whitelist_attributes = true
+
+ # Enable the asset pipeline
+ config.assets.enabled = true
+
+ # Version of your assets, change this if you want to expire all your assets
+ config.assets.version = '1.0'
+ end
+end
View
6 config/boot.rb
@@ -0,0 +1,6 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
View
60 config/database.yml.example
@@ -0,0 +1,60 @@
+# Note: For local development and testing, you'll need a database.yml file.
+# Rename this file to database.yml, and update the information as appropriate
+# For Heroku, you won't need the database.yml.
+
+
+# PostgreSQL. Versions 8.2 and up are supported.
+#
+# Install the pg driver:
+# gem install pg
+# On Mac OS X with macports:
+# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
+# On Windows:
+# gem install pg
+# Choose the win32 build.
+# Install PostgreSQL and put its /bin directory on your path.
+#
+# Configure Using Gemfile
+# gem 'pg'
+#
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: whenbot_development
+ pool: 5
+ username: whenbot
+ password:
+
+ # Connect on a TCP socket. Omitted by default since the client uses a
+ # domain socket that doesn't need configuration. Windows does not have
+ # domain sockets, so uncomment these lines.
+ #host: localhost
+ #port: 5432
+
+ # Schema search path. The server defaults to $user,public
+ #schema_search_path: myapp,sharedapp,public
+
+ # Minimum log levels, in increasing order:
+ # debug5, debug4, debug3, debug2, debug1,
+ # log, notice, warning, error, fatal, and panic
+ # The server defaults to notice.
+ #min_messages: warning
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: postgresql
+ encoding: unicode
+ database: whenbot_test
+ pool: 5
+ username: whenbot
+ password:
+
+production:
+ adapter: postgresql
+ encoding: unicode
+ database: whenbot_production
+ pool: 5
+ username: whenbot
+ password:
View
5 config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Whenbot::Application.initialize!
View
37 config/environments/development.rb
@@ -0,0 +1,37 @@
+Whenbot::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the web server when you make code changes.
+ config.cache_classes = false
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
+
+ # Raise exception on mass assignment protection for Active Record models
+ config.active_record.mass_assignment_sanitizer = :strict
+
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL)
+ config.active_record.auto_explain_threshold_in_seconds = 0.5
+
+ # Do not compress assets
+ config.assets.compress = false
+
+ # Expands the lines which load the assets
+ config.assets.debug = true
+end
View
67 config/environments/production.rb
@@ -0,0 +1,67 @@
+Whenbot::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Disable Rails's static asset server (Apache or nginx will already do this)
+ config.serve_static_assets = false
+
+ # Compress JavaScripts and CSS
+ config.assets.compress = true
+
+ # Don't fallback to assets pipeline if a precompiled asset is missed
+ config.assets.compile = false
+
+ # Generate digests for assets URLs
+ config.assets.digest = true
+
+ # Defaults to Rails.root.join("public/assets")
+ # config.assets.manifest = YOUR_PATH
+
+ # Specifies the header that your server uses for sending files
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
+
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
+ # config.force_ssl = true
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Prepend all log lines with the following tags
+ # config.log_tags = [ :subdomain, :uuid ]
+
+ # Use a different logger for distributed setups
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+ # config.assets.precompile += %w( search.js )
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL)
+ # config.active_record.auto_explain_threshold_in_seconds = 0.5
+end
View
37 config/environments/test.rb
@@ -0,0 +1,37 @@
+Whenbot::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Configure static asset server for tests with Cache-Control for performance
+ config.serve_static_assets = true
+ config.static_cache_control = "public, max-age=3600"
+
+ # Log error messages when you accidentally call methods on nil
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Raise exception on mass assignment protection for Active Record models
+ config.active_record.mass_assignment_sanitizer = :strict
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
View
7 config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
View
15 config/initializers/inflections.rb
@@ -0,0 +1,15 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
+#
+# These inflection rules are supported but not enabled by default:
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.acronym 'RESTful'
+# end
View
5 config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
View
18 config/initializers/require_lib_files.rb
@@ -0,0 +1,18 @@
+# Rails doesn't autoload files that contain classes or modules that
+# have already been defined (i.e. when you try and re-open a class
+# or module). We'll be doing a bunch of that here, so we'll
+# manually require the files in the lib folder, along with
+# its subfolders.
+#
+# This is also required to load the Triggers and Actions for
+# automatic detection of Triggers/Actions after a Channel is
+# added.
+
+# Solution from here:
+# - http://stackoverflow.com/a/3181988/321896
+# and
+# - http://stackoverflow.com/a/6797707/321896
+
+Dir[Rails.root + 'lib/**/*.rb'].each do |file|
+ require file
+end
View
7 config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Whenbot::Application.config.secret_token = '58346e466b61a5d0de4bce286af184ec95f0b429755c754ff6a6cc9536955bbe9c0278c30493630e70ad0c96b0ef94608ebf48760b9fd62a2ae89ecf9b576372'
View
8 config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Whenbot::Application.config.session_store :cookie_store, key: '_whenbot_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rails generate session_migration")
+# Whenbot::Application.config.session_store :active_record_store
View
7 config/initializers/whenbot.rb
@@ -0,0 +1,7 @@
+require 'whenbot'
+
+# Add your installed Channels here.
+Whenbot.config do |config|
+ config.channels << Whenbot::Channels::Developer
+ config.channels << Whenbot::Channels::Twitter
+end
View
14 config/initializers/wrap_parameters.rb
@@ -0,0 +1,14 @@
+# Be sure to restart your server when you modify this file.
+#
+# This file contains settings for ActionController::ParamsWrapper which
+# is enabled by default.
+
+# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
+ActiveSupport.on_load(:action_controller) do
+ wrap_parameters format: [:json]
+end
+
+# Disable root element in JSON by default.
+ActiveSupport.on_load(:active_record) do
+ self.include_root_in_json = false
+end
View
5 config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
View
65 config/routes.rb
@@ -0,0 +1,65 @@
+Whenbot::Application.routes.draw do
+
+ # Routes calls to appropriate Trigger
+ match '/whenbot/:channel/:trigger/callback' => 'whenbot#callback'
+
+ get "tasks/index"
+ get "tasks/new"
+
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
+
+ # Sample of regular route:
+ # match 'products/:id' => 'catalog#view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
+ # resources :products
+
+ # Sample resource route with options:
+ # resources :products do
+ # member do
+ # get 'short'
+ # post 'toggle'
+ # end
+ #
+ # collection do
+ # get 'sold'
+ # end
+ # end
+
+ # Sample resource route with sub-resources:
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
+ # Sample resource route with more complex sub-resources
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get 'recent', :on => :collection
+ # end
+ # end
+
+ # Sample resource route within a namespace:
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
+ # end
+
+ # You can have the root of your site routed with "root"
+ # just remember to delete public/index.html.
+ # root :to => 'welcome#index'
+
+ # See how all your routes lay out with "rake routes"
+
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
+ # Note: This route will make all actions in every controller accessible via GET requests.
+ # match ':controller(/:action(/:id))(.:format)'
+end
View
24 db/migrate/20120419221210_create_triggers.rb
@@ -0,0 +1,24 @@
+class CreateTriggers < ActiveRecord::Migration
+ def change
+ create_table :triggers do |t|
+ t.integer :task_id, null: false
+ t.string :channel, null: false
+ t.string :trigger, null: false
+ t.boolean :polling_trigger, null: false, default: false
+ t.text :parameters
+ t.text :match_data
+ t.datetime :last_matched
+ t.text :extra_data
+ t.string :webhook_uid
+ t.boolean :active, null: false, default: true
+
+ t.timestamps
+ end
+
+ add_index :triggers, :task_id
+ add_index :triggers, :polling_trigger
+ add_index :triggers, :active
+ add_index :triggers, [:active, :polling_trigger]
+ add_index :triggers, [:channel, :trigger]
+ end
+end
View
18 db/migrate/20120419230901_create_actions.rb
@@ -0,0 +1,18 @@
+class CreateActions < ActiveRecord::Migration
+ def change
+ create_table :actions do |t|
+ t.integer :task_id, null: false
+ t.string :channel, null: false
+ t.string :action, null: false
+ t.text :parameters
+ t.text :extra_data
+ t.boolean :active, null: false, default: true
+
+ t.timestamps
+ end
+
+ add_index :actions, :task_id
+ add_index :actions, :active
+ add_index :actions, [:channel, :action]
+ end
+end
View
12 db/migrate/20120419233318_create_authentications.rb
@@ -0,0 +1,12 @@
+class CreateAuthentications < ActiveRecord::Migration
+ def change
+ create_table :authentications do |t|
+ t.string :channel, null: false
+ t.text :parameters
+
+ t.timestamps
+ end
+
+ add_index :authentications, :channel, unique: true
+ end
+end
View
13 db/migrate/20120419234122_create_tasks.rb
@@ -0,0 +1,13 @@
+class CreateTasks < ActiveRecord::Migration
+ def change
+ create_table :tasks do |t|
+ t.string :name
+ t.datetime :last_executed
+ t.boolean :active, null: false, default: true
+
+ t.timestamps
+ end
+
+ add_index :tasks, :active
+ end
+end
View
71 db/schema.rb
@@ -0,0 +1,71 @@
+# encoding: UTF-8
+# This file is auto-generated from the current state of the database. Instead
+# of editing this file, please use the migrations feature of Active Record to
+# incrementally modify your database, and then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your
+# database schema. If you need to create the application database on another
+# system, you should be using db:schema:load, not running all the migrations
+# from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20120419234122) do
+
+ create_table "actions", :force => true do |t|
+ t.integer "task_id", :null => false
+ t.string "channel", :null => false
+ t.string "action", :null => false
+ t.text "parameters"
+ t.text "extra_data"
+ t.boolean "active", :default => true, :null => false
+ t.datetime "created_at", :null => false
+ t.datetime "updated_at", :null => false
+ end
+
+ add_index "actions", ["active"], :name => "index_actions_on_active"
+ add_index "actions", ["channel", "action"], :name => "index_actions_on_channel_and_action"
+ add_index "actions", ["task_id"], :name => "index_actions_on_task_id"
+
+ create_table "authentications", :force => true do |t|
+ t.string "channel", :null => false
+ t.text "parameters"
+ t.datetime "created_at", :null => false
+ t.datetime "updated_at", :null => false
+ end
+
+ add_index "authentications", ["channel"], :name => "index_authentications_on_channel", :unique => true
+
+ create_table "tasks", :force => true do |t|
+ t.string "name"
+ t.datetime "last_executed"
+ t.boolean "active", :default => true, :null => false
+ t.datetime "created_at", :null => false
+ t.datetime "updated_at", :null => false
+ end
+
+ add_index "tasks", ["active"], :name => "index_tasks_on_active"
+
+ create_table "triggers", :force => true do |t|
+ t.integer "task_id", :null => false
+ t.string "channel", :null => false
+ t.string "trigger", :null => false
+ t.boolean "polling_trigger", :default => false, :null => false
+ t.text "parameters"
+ t.text "match_data"
+ t.datetime "last_matched"
+ t.text "extra_data"
+ t.string "webhook_uid"
+ t.boolean "active", :default => true, :null => false
+ t.datetime "created_at", :null => false
+ t.datetime "updated_at", :null => false
+ end
+
+ add_index "triggers", ["active", "polling_trigger"], :name => "index_triggers_on_active_and_polling_trigger"
+ add_index "triggers", ["active"], :name => "index_triggers_on_active"
+ add_index "triggers", ["channel", "trigger"], :name => "index_triggers_on_channel_and_trigger"
+ add_index "triggers", ["polling_trigger"], :name => "index_triggers_on_polling_trigger"
+ add_index "triggers", ["task_id"], :name => "index_triggers_on_task_id"
+
+end
View
7 db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
+# Mayor.create(name: 'Emanuel', city: cities.first)
View
2  doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
View
8 factories/users.rb
@@ -1,8 +0,0 @@
-FactoryGirl.define do
- factory :user do
- username 'Whenbotter'
- email 'whenbotter@gmail.com'
- password 'dictionaryattack123'
- password_confirmation 'dictionaryattack123'
- end
-end
View
0  lib/assets/.gitkeep
No changes.
View
0  lib/tasks/.gitkeep
No changes.
View
104 lib/whenbot.rb
@@ -0,0 +1,104 @@
+require "whenbot/version"
+require "whenbot/channel"
+require "whenbot/trigger"
+
+module Whenbot
+
+ # Note that we can't use autoload because we automatically detect
+ # Triggers/Actions when a Channel is added via #config. If the
+ # Triggers aren't loaded, # we can't use #constants to detect the
+ # Triggers.
+ #
+ # autoload :Channel, 'whenbot/channel'
+ # autoload :Trigger, 'whenbot/trigger'
+
+ # ==== One-liner 1 ====
+ @@channels = []
+
+ #
+ # Relays the callbacks that come into the Whenbot#callback
+ # action to the proper Trigger class.
+ #
+ def self.relay_callback(channel, trigger, triggers, url_params, headers, body)
+ # ==== One-liner 2 ====
+ if klass
+ # ==== One-liner 3 ====
+ else
+ :error
+ end
+ end
+
+ #
+ # Handles "config do" block. To be used from intializer.
+ #
+ def self.config
+ # ==== One-liner 4 ====
+ end
+
+ #
+ # Overloaded accessor to ensure that we always return an array
+ #
+ def self.channels
+ # ==== One-liner 5 ====
+ end
+
+ #
+ # Returns an array of Channels that have at least one Trigger
+ # Array values are strings. E.g. 'Developer'
+ #
+ def self.trigger_channels
+ trigger_channels_as_consts.collect { |channel| # ==== One-liner 6 ==== }
+ end
+
+ #
+ # Returns an array of Trigger Channels as constants. That is,
+ # any Channels that have at least one Trigger.
+ #
+ # E.g. Whenbot::Channels::Developer
+ #
+ def self.trigger_channels_as_consts
+ channels.select do |channel|
+ # ==== One-liner 7 ====
+ end
+ end
+
+ #
+ # Returns an array of Channels that have at least one Trigger
+ #
+ def self.action_channels
+ # Task: Fill this in
+ end
+
+ private
+
+
+ #
+ # Helper method to find the constant for the given Channel and Trigger
+ #
+ def self.build_class_constant(channel, trigger)
+ # ==== One-liner 8 ====
+ klass = Whenbot::Channels::const_get(channel.camelize)::Triggers::const_get(trigger.camelize)
+ rescue NameError => e
+ # Happens if we can't find the Channel or Trigger.
+ # Log, email exception (Exceptional? Hoptoad? New Relic?)
+ Rails.logger.error "[ERROR] NameError. Message = #{e.message}"
+ # ==== One-liner 9 ====
+ end
+
+
+ #
+ # Checks if there's at least one Trigger defined under the
+ # Channel's "Triggers" module.
+ #
+ def self.has_triggers?(channel)
+ channel::Triggers::constants.present? if channel.const_defined?(:Triggers)
+ end
+
+ #
+ # Helper method to return an array of Trigger's defined for the
+ # given Channel
+ #
+ def self.detect_triggers_for(channel)
+ channel::Triggers::constants
+ end
+end
View
5 lib/whenbot/channel.rb
@@ -0,0 +1,5 @@
+module Whenbot
+ module Channel
+
+ end
+end
View
25 lib/whenbot/channels/developer/actions/do_some_event.rb
@@ -0,0 +1,25 @@
+module Whenbot
+ module Channels
+ module Developer
+ module Actions
+
+ class DoSomeEvent
+
+ # Task: Enable this functionality. See tests in trigger_test.rb
+ #
+ # set_option :display_title, 'SampleSearch trigger'
+ # set_option :description, 'Does nothing. Always reports a match.'
+
+ #
+ # Perform the Action
+ #
+ def self.perform(parameters)
+ # ...
+ end
+
+ end
+
+ end
+ end
+ end
+end
View
14 lib/whenbot/channels/developer/service.rb
@@ -0,0 +1,14 @@
+module Whenbot
+ module Channels
+ module Developer
+ class Service
+
+ #
+ # Place common code here to handle calls to
+ # your webservice.
+ #
+
+ end
+ end
+ end
+end
View
220 lib/whenbot/channels/developer/triggers/sample_search.rb
@@ -0,0 +1,220 @@
+module Whenbot
+ module Channels
+ module Developer
+ module Triggers
+ class SampleSearch
+
+ include Whenbot::Trigger
+
+ # Note that the Channel's display title is taken by
+ # the module name. In this case: Whenbot::Channels::Twitter
+ # would yield "Developer" as the Channel name.
+
+ # Task: Enable this functionality. See tests in trigger_test.rb
+ #
+ # set_option :display_title, 'SampleSearch trigger'
+ # set_option :description, 'Does nothing. Always reports a match.'
+
+
+ #
+ # Is this a polling trigger?
+ #
+ # Note: When creating a webhook or polling a service, it is
+ # important to set the callback URL to
+ # /webhooks/<channel_name>/<trigger_name>/callback
+ # For example, this Trigger would use:
+ # /webhooks/developer/sample_search/callback.
+ #
+ # Without this, your #callback method will never be called.
+ #
+ # - Returns false if this Trigger sets up a webhook to be notified
+ # of potential matches.
+ #
+ # - Returns true if #poll should be called periodically to allow
+ # this Trigger to check for matches.
+ #
+ def self.is_polling_trigger?
+ true
+ end
+
+ #
+ # Run poll. Calls out to Webservice (use your Channel's Service
+ # class to hold common code for this).
+ #
+ # If your service doesn't poll, you don't need this method.
+ #
+ # triggers [Array] => An array of hashes.
+ # - Each hash contains the same keys/values as those given
+ # in the #callback method.
+ #
+ def self.poll(triggers)
+ #
+ # Poll the service.
+ # If you get the response back immediately
+ # [Do pretty much the same thing as #callback]
+ # - Check results
+ # - Update the triggers array of hashes with any match_data found
+ # - Set the appropriate flags to signal if Whenbot should save
+ # the updated data to the database
+ #
+ # If you receive the response back via a callback, be sure
+ # to set your path to /whenbot/<channel_name>/<trigger_name>/callback
+ #
+ # For example, this Trigger would use:
+ # /whenbot/developer/sample_search/callback
+ #
+ end
+
+ # Optional. Only needed if this is Trigger can be watched via a webhook.
+ #
+ # Creates a webhook on the server for this Trigger, with
+ # the given params.
+ #
+ # trigger => Trigger hash for this Trigger. Same as
+ # the hash passed into #callback.
+ #
+ # Returns: wehbook_uid (string) => an identifier given by the webservice,
+ # that is used to uniquely identify this hook.
+ #
+ def self.create_webhook_for(trigger)
+ #
+ # Note: When creating a webhook or polling a service, it is
+ # important to set the callback URL to
+ # /whenbot/<channel_name>/<trigger_name>/callback
+ # For example, this Trigger would use:
+ # /whenbot/developer/sample_search/callback
+ #
+ end
+
+ #
+ # Cancels a webhook that has been setup on the server.
+ # Called when a User deletes or deactivates a Trigger.
+ #
+ # webhook_uid => The unique id returned from create_webhook_for
+ # trigger => Trigger hash for this Trigger. Same as
+ # the hash passed into #callback.
+ #
+ # Returns: true or false.
+ #
+ def self.cancel_webhook_for(webhook_uid, trigger)
+ # Optional. Only needed if this Trigger uses webhooks.
+ end
+
+ #
+ # A form will be automatically generated when the User is
+ # creating a Task, to get the required parameters.
+ #
+ # Returns: Hash of parameters to be obtained from the
+ # user when setting up this Trigger, and then saved
+ # to the database.
+ #
+ # @return [Hash]
+ # Hash of the following form:
+ #
+ # {
+ # parameter_name: {
+ # label: <display label text>,
+ # input_type: <type>, # can be :text_field, :select, :checkbox, etc.
+ # help_text: <help_text> # optional
+ # optional: <true or false> # Is this parameter mandatory?
+ # template: <true or false> # Should be parsed for Liquid data
+ # }
+ # }
+ #
+ #
+ def self.parameters
+ {
+ search_term: {
+ label: 'Search term',
+ input_type: :text,
+ help_text: 'Text to be reported back as the matched data',
+ optional: false,
+ accepts_liquid: true
+ }
+ }
+ end
+
+ #
+ # Called by Whenbot whenever a new response is received
+ # from a web service for this Trigger.
+ #
+ # triggers [Array] => An array of hashes. Each hash contains:
+ #
+ # hash[:parameters] # => saved parameters
+ #
+ # hash[:match_data] # => an empty hash, for you to fill with
+ # your match data if a match is found.
+ #
+ # hash[:extra_data] # => Use this to store/retrieve custom data
+ # that you need from callback to callback.
+ # Starts out empty, saves what you put in
+ # and returns the previously saved data
+ # with each call to #callback.
+ #
+ # hash[:last_matched] # => The last date and time the Trigger was
+ # matched. Will be updated by Whenbot if
+ # you update the :matched_data hash.
+ #
+ # parameters [Hash] => params hash
+ # headers [Hash] => Result of request.headers
+ # body [String] => Result of request.body.read
+ #
+ # returns:
+ # - The original trigger_params array, but with
+ # updated :match_data where appropriate
+ # - An array containing [:status, :headers, :body] for
+ # the response to the server.
+ #
+ def self.callback(triggers, url_params, headers, body)
+ [find_matches(triggers, body), build_response(:ok)]
+ end
+
+ private
+
+ # This sort of method would be specific to your needs.
+ # For this example Trigger, the data we need can be
+ # found in the body.
+ def self.find_matches(triggers, body)
+ return triggers unless body
+ payload = json_to_hash(body)
+
+ triggers.each do |trigger|
+ if payload['content'].include? trigger[:parameters][:search_term]
+ # Update the current trigger, since we have a match
+ # This is how we signal a match.
+ #
+ # Note: When updating :last_matched, use the #current_time
+ # method, to ensure that all times are in the correct timezone.
+
+ trigger[:match_found] = true
+ trigger[:match_data] = { content: payload['content'] }
+ trigger[:last_updated] = current_time # To maintain integrity
+ trigger[:save] = true
+ end
+ end
+
+ triggers
+ end
+
+ def self.json_to_hash(data)
+ ActiveSupport::JSON.decode(data)
+ end
+
+ # Support method to build the response hash
+ #
+ # For this example, we either return the challenge (sometimes
+ # requested by a web service), or just return a status code.
+ def self.build_response(status, headers=nil, body=nil)
+ {
+ head_only: true,
+ status: status,
+ type: nil, # Can be :json, :xml, :js
+ headers: headers,
+ body: body
+ }
+ end
+ end
+ end
+ end
+ end
+end
View
11 lib/whenbot/channels/twitter/service.rb
@@ -0,0 +1,11 @@
+module Whenbot
+ module Channels
+ module Twitter
+ class Service
+
+ # TODO
+
+ end
+ end
+ end
+end
View
56 lib/whenbot/channels/twitter/triggers/new_tweet_from.rb
@@ -0,0 +1,56 @@
+module Whenbot
+ module Channels
+ module Twitter
+ module Triggers
+ class NewTweetFrom
+
+ include Whenbot::Trigger
+
+ # Task: Enable this functionality. See tests in trigger_test.rb
+ #
+ # set_option :display_title, "New tweet posted by a user"
+ # set_option :description, "Triggers whenever a new message is tweeted by "\
+ # "a specific user."
+
+ # Called by Whenbot whenever a new response is received
+ # from a web service for this Trigger.
+ # body (string) => Result of request.body.read
+ # headers (hash) => Result of request.headers
+ def self.callback(triggers, url_params, headers, body)
+ return [nil, build_response(:ok, nil, url_params[:challenge])] if url_params[:challenge]
+ [find_matches(triggers, body), build_response(:ok, nil, nil)]
+ end
+
+ private
+
+ # This sort of method would be specific to your needs.
+ # For this example Trigger, the data we need can be
+ # found in the body.
+ def self.find_matches(triggers, body)
+ return triggers unless body
+ payload = json_to_hash(body)
+
+ triggers
+ end
+
+ def self.json_to_hash(data)
+ ActiveSupport::JSON.decode(data)
+ end
+
+ # Support method to build the response hash
+ def self.build_response(status, headers=nil, body=nil)
+ {
+ head_only: true,
+ status: status,
+ type: nil, # Can be :json, :xml, :js
+ headers: headers,
+ body: body
+ }
+ end
+
+
+ end
+ end
+ end
+ end
+end
View
19 lib/whenbot/trigger.rb
@@ -0,0 +1,19 @@
+require "active_support/core_ext/class/attribute"
+
+module Whenbot
+ module Trigger
+
+ def self.included(base)
+ # ==== One-liner 10 ====
+ end
+
+ module ClassMethods
+
+ # Use this when setting :last_matched value
+ def current_time
+ # ==== One-liner 11
+ end
+
+ end
+ end
+end
View
3  lib/whenbot/version.rb
@@ -0,0 +1,3 @@
+module Whenbot
+ VERSION = "0.0.1"
+end
View
0  log/.gitkeep
No changes.
View
26 public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
View
26 public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
View
25 public/500.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ </div>
+</body>
+</html>
View
0  public/favicon.ico
No changes.
View
241 public/index.html
@@ -0,0 +1,241 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Ruby on Rails: Welcome aboard</title>
+ <style type="text/css" media="screen">
+ body {
+ margin: 0;
+ margin-bottom: 25px;
+ padding: 0;
+ background-color: #f0f0f0;
+ font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
+ font-size: 13px;
+ color: #333;
+ }
+
+ h1 {
+ font-size: 28px;
+ color: #000;
+ }
+
+ a {color: #03c}
+ a:hover {
+ background-color: #03c;
+ color: white;
+ text-decoration: none;
+ }
+
+
+ #page {
+ background-color: #f0f0f0;
+ width: 750px;
+ margin: 0;
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ #content {
+ float: left;
+ background-color: white;
+ border: 3px solid #aaa;
+ border-top: none;
+ padding: 25px;
+ width: 500px;
+ }
+
+ #sidebar {
+ float: right;
+ width: 175px;
+ }
+
+ #footer {
+ clear: both;
+ }
+
+ #header, #about, #getting-started {
+ padding-left: 75px;
+ padding-right: 30px;
+ }
+
+
+ #header {
+ background-image: url("assets/rails.png");
+ background-repeat: no-repeat;
+ background-position: top left;
+ height: 64px;
+ }
+ #header h1, #header h2 {margin: 0}
+ #header h2 {
+ color: #888;
+ font-weight: normal;
+ font-size: 16px;
+ }
+
+
+ #about h3 {
+ margin: 0;
+ margin-bottom: 10px;
+ font-size: 14px;
+ }
+
+ #about-content {
+ background-color: #ffd;
+ border: 1px solid #fc0;
+ margin-left: -55px;
+ margin-right: -10px;
+ }
+ #about-content table {
+ margin-top: 10px;
+ margin-bottom: 10px;
+ font-size: 11px;
+ border-collapse: collapse;
+ }
+ #about-content td {
+ padding: 10px;
+ padding-top: 3px;
+ padding-bottom: 3px;
+ }
+ #about-content td.name {color: #555}
+ #about-content td.value {color: #000}
+
+ #about-content ul {
+ padding: 0;
+ list-style-type: none;
+ }
+
+ #about-content.failure {
+ background-color: #fcc;
+ border: 1px solid #f00;
+ }
+ #about-content.failure p {
+ margin: 0;
+ padding: 10px;
+ }
+
+
+ #getting-started {
+ border-top: 1px solid #ccc;
+ margin-top: 25px;
+ padding-top: 15px;
+ }
+ #getting-started h1 {
+ margin: 0;
+ font-size: 20px;
+ }
+ #getting-started h2 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: normal;
+ color: #333;
+ margin-bottom: 25px;
+ }
+ #getting-started ol {
+ margin-left: 0;
+ padding-left: 0;
+ }
+ #getting-started li {
+ font-size: 18px;
+ color: #888;
+ margin-bottom: 25px;
+ }
+ #getting-started li h2 {
+ margin: 0;
+ font-weight: normal;
+ font-size: 18px;
+ color: #333;
+ }
+ #getting-started li p {
+ color: #555;
+ font-size: 13px;
+ }
+
+
+ #sidebar ul {
+ margin-left: 0;
+ padding-left: 0;
+ }
+ #sidebar ul h3 {
+ margin-top: 25px;
+ font-size: 16px;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #ccc;
+ }
+ #sidebar li {
+ list-style-type: none;
+ }
+ #sidebar ul.links li {
+ margin-bottom: 5px;
+ }
+
+ .filename {
+ font-style: italic;
+ }
+ </style>
+ <script type="text/javascript">
+ function about() {
+ info = document.getElementById('about-content');
+ if (window.XMLHttpRequest)
+ { xhr = new XMLHttpRequest(); }
+ else
+ { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
+ xhr.open("GET","rails/info/properties",false);
+ xhr.send("");
+ info.innerHTML = xhr.responseText;
+ info.style.display = 'block'
+ }
+ </script>
+ </head>
+ <body>
+ <div id="page">
+ <div id="sidebar">
+ <ul id="sidebar-items">
+ <li>
+ <h3>Browse the documentation</h3>
+ <ul class="links">
+ <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
+ <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
+ <li><a href="http://www.ruby-doc.org/core/">Ruby core</a></li>
+ <li><a href="http://www.ruby-doc.org/stdlib/">Ruby standard library</a></li>
+ </ul>
+ </li>
+ </ul>
+ </div>
+
+ <div id="content">
+ <div id="header">
+ <h1>Welcome aboard</h1>
+ <h2>You&rsquo;re riding Ruby on Rails!</h2>
+ </div>
+
+ <div id="about">
+ <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3>
+ <div id="about-content" style="display: none"></div>
+ </div>
+
+ <div id="getting-started">
+ <h1>Getting started</h1>
+ <h2>Here&rsquo;s how to get rolling:</h2>
+
+ <ol>
+ <li>
+ <h2>Use <code>rails generate</code> to create your models and controllers</h2>
+ <p>To see all available options, run it without parameters.</p>
+ </li>
+
+ <li>
+ <h2>Set up a default route and remove <span class="filename">public/index.html</span></h2>
+ <p>Routes are set up in <span class="filename">config/routes.rb</span>.</p>
+ </li>
+
+ <li>
+ <h2>Create your database</h2>
+ <p>Run <code>rake db:create</code> to create your database. If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p>
+ </li>
+ </ol>
+ </div>
+ </div>
+
+ <div id="footer">&nbsp;</div>
+ </div>
+ </body>
+</html>
View
5 public/robots.txt
@@ -0,0 +1,5 @@
+# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
+#
+# To ban all spiders from the entire site uncomment the next two lines:
+# User-Agent: *
+# Disallow: /
View
6 script/rails
@@ -0,0 +1,6 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require File.expand_path('../../config/boot', __FILE__)
+require 'rails/commands'
View
58 spec/models/action_spec.rb
@@ -1,58 +0,0 @@
-require 'spec_helper'
-
-describe Action do
-
- before(:each)do
- @user=Factory(:user)
-
- end
-
- it "should create a new instance given valid attributes" do
- @user.actions.create!(@attr)
- end
-
- describe "user associations" do
-
- before(:each)do
- @action=@user.actions.create(@attr)
- end
-
- it "should have a user attribute" do
- @action.should respond_to(:user)
- end
-
- it "should have the right associated user" do
- @action.user_id.should == @user.id
- @action.user.should == @user
- end
-
- end
-
- describe "trigger associations" do
-
- it "should have a trigger attribute" do
- @action.should respond_to(:trigger)
- end
-
- it "should have the right associated trigger" do
- @trigger.action_id.should == @action.id
- @trigger.action.should == @action
- end
-
-
- end
-
- describe "publisher associations" do
-
- it "should have a publisher attribute" do
- @action.should respond_to(:publisher)
- end
-
- it "should have the right associated publisher" do
- @publisher.action_id.should == @action.id
- @publisher.action.should == @action
- end
-
- end
-
-end
View
13 test/factories/actions.rb
@@ -0,0 +1,13 @@
+# Read about factories at https://github.com/thoughtbot/factory_girl
+
+FactoryGirl.define do
+ factory :action do
+ task_id 1
+ channel "MyString"
+ action "MyString"
+ parameters "MyText"
+ last_executed "2012-04-19 19:09:01"
+ extra_data "MyText"
+ active true
+ end
+end
View
8 test/factories/authentications.rb
@@ -0,0 +1,8 @@
+# Read about factories at https://github.com/thoughtbot/factory_girl
+
+FactoryGirl.define do
+ factory :authentication do
+ channel "MyString"
+ parameters "MyText"
+ end
+end
View
13 test/factories/tasks.rb
@@ -0,0 +1,13 @@
+# Read about factories at https://github.com/thoughtbot/factory_girl
+
+FactoryGirl.define do
+ factory :task do
+ name "My Task"
+ active true
+ last_executed "2012-04-19 19:41:22"
+
+ factory :developer_task do
+ name "Developer Task"
+ end
+ end
+end
View
36 test/factories/triggers.rb
@@ -0,0 +1,36 @@
+# Read about factories at https://github.com/thoughtbot/factory_girl
+
+FactoryGirl.define do
+ factory :trigger do
+ task_id { |t| t.association(:task) }
+ channel "Developer"
+ trigger "SampleSearch"
+ polling_trigger false
+ parameters({ search_term: 'MyText' })
+ match_data nil
+ extra_data nil
+ last_matched "2012-04-19 19:41:22"
+ webhook_uid "MyString"
+ active true
+
+ factory :matching_trigger do
+ parameters({ search_term: 'banana' })
+ extra_data({ some_value: 'saved result' })
+ end
+
+ factory :non_matching_trigger do
+ parameters({ search_term: "a string that shouldn't be matched" })
+ end
+
+ factory :twitter_new_tweet_from_trigger do
+ channel "Twitter"
+ trigger "NewTweetFrom"
+ parameters({ username: 'rails' })
+ task_id { |task| task.association(:developer_task) }
+ end
+
+ factory :single_trigger_under_new_task do
+ task
+ end
+ end
+end
View
0  test/functional/.gitkeep
No changes.
View
14 test/functional/tasks_controller_test.rb
@@ -0,0 +1,14 @@
+require 'test_helper'
+
+class TasksControllerTest < ActionController::TestCase
+ test "should get index" do
+ get :index
+ assert_response :success
+ end
+
+ test "should get new" do
+ get :new
+ assert_response :success
+ end
+
+end
View
37 test/functional/whenbot_controller_test.rb
@@ -0,0 +1,37 @@
+require 'test_helper'
+
+class WhenbotControllerTest < ActionController::TestCase
+
+ context "webhook callback access" do
+
+ setup do
+ @sample_search_trigger = Whenbot::Channels::Developer::Triggers::SampleSearch
+ @matching = FactoryGirl.create(:matching_trigger)
+ @non_matching = FactoryGirl.create(:non_matching_trigger)
+ @search_term = @matching[:parameters][:search_term]
+
+ @body_as_hash = { content: "Some text that mentions #{@search_term}" }
+ @body = @body_as_hash.to_json
+ @url_params = { url_data: "some data" }
+ @headers = { 'Content-Type' => 'application/json' }
+ end
+
+ should "route paths with Channel and Trigger to Whenbot#callback" do
+ expected_params = { controller: 'whenbot',
+ action: 'callback',
+ channel: 'developer',
+ trigger: 'sample_search' }
+ assert_routing '/whenbot/developer/sample_search/callback', expected_params
+ end
+
+ should "relay received webhook data to appropriate Trigger's #callback method" do
+ triggers, ids = Trigger.triggers_for('Developer', 'SampleSearch')
+ @sample_search_trigger.expects(:callback).returns([triggers, {status: :ok}])
+
+ # Task for reader (that's you): Use Fakeweb or VCR.
+ params = { channel: 'developer', trigger: 'sample_search'}
+ response = raw_post('callback', params, @body)
+ end
+
+ end
+end
View
0  test/integration/.gitkeep
No changes.
View
18 test/integration/task_flows_test.rb
@@ -0,0 +1,18 @@
+require 'test_helper'
+
+class TaskFlowsTest < ActionDispatch::IntegrationTest
+
+ test "New Task page should show installed Trigger Channels" do