Commit e664772e authored by Andi Saurer's avatar Andi Saurer

start from scratch using rails plugin new . -d mysql -B -J --mountable

parent 2a17c68c
.bundle/
log/*.log
pkg/
spec/dummy/db/*.sqlite3
spec/dummy/log/*.log
spec/dummy/tmp/
spec/dummy/.sass-cache
spec/dummy/config/database.yml
tmp/*
test/dummy/db/*.sqlite3
test/dummy/db/*.sqlite3-journal
test/dummy/log/*.log
test/dummy/tmp/
test/dummy/.sass-cache
2.1.3@short_message
2.3.0@short_message
source "http://rubygems.org"
source 'https://rubygems.org'
# Declare your gem's dependencies in short_message.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
gemspec
# jquery-rails is used by the dummy application
gem "jquery-rails"
# 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 debugger
# gem 'debugger'
# To use a debugger
# gem 'byebug', group: [:development, :test]
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
guard 'rspec' do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
# Rails example
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
# Capybara features specs
watch(%r{^app/views/(.+)/.*\.(erb|haml)$}) { |m| "spec/features/#{m[1]}_spec.rb" }
# Turnip features and steps
watch(%r{^spec/acceptance/(.+)\.feature$})
watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end
Copyright 2013 YOURNAME
Copyright 2016 Andi Saurer
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
......
# ShortMessage #
[![Gem Version](https://badge.fury.io/rb/short_message.png)](http://badge.fury.io/rb/short_message)
## Installation ##
Add it to your Gemfile:
```ruby
gem 'short_message'
```
Run the following command to install it:
```console
bundle install
```
Run the generator:
```console
rails generate short_message:install
```
And rake the migrations:
```console
rake db:migrate
```
## Usage ##
Create a message and deliver it:
```ruby
@sms = ShortMessage::Message.new(:sender => "0041791234567", :recipient => "0041799876543", :text => "Hello World!")
@sms.deliver
```
## Customization ##
### Status Codes ##
If you need to customize the status response codes simply edit the internationalization files in config/locales
### Params ###
To override the params string add this to an initializer file (or put it into config/initializers/short_message.rb)
```ruby
ShortMessage::Message.module_eval do
private
def build_deliver_params_string
# your code here
end
def build_recharge_params_string amount
# your code here
end
end
```
= ShortMessage
This project rocks and uses MIT-LICENSE.
\ No newline at end of file
#!/usr/bin/env rake
begin
require 'bundler/setup'
rescue LoadError
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
end
begin
require 'rdoc/task'
rescue LoadError
require 'rdoc/rdoc'
require 'rake/rdoctask'
RDoc::Task = Rake::RDocTask
end
require 'rdoc/task'
RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
......@@ -20,8 +14,24 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end
APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
load 'rails/tasks/engine.rake'
load 'rails/tasks/statistics.rake'
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
......@@ -3,11 +3,13 @@
* 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.
* or any plugin's vendor/assets/stylesheets directory 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.
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
* defined in the other CSS/SCSS files in this directory. It is generally better to create a new
* file per style scope.
*
*= require_self
*= require_tree .
*= require_self
*/
module ShortMessage
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
end
module ShortMessage
class Mailer < ActionMailer::Base
default from: ShortMessage.config.default_mail_sender
def recharge_notification amount
mail to: ShortMessage.config.reload_notification_email, :subject => "SMS credit recharged", :body => "Your SMS Account has automatically been recharged with #{amount} sms."
end
def voucher_notification amount
mail :to => ShortMessage.config.voucher_notification_email, :subject => "SMS credit recharged, please create a voucher", :body => "Please add a voucher:\r\nCustomer: #{ShortMessage.config.user_id}\r\nAmount: #{amount} sms\r\n\r\nThank you!"
end
def recharge_failed_notification amount, message
mail :to => ShortMessage.config.reload_notification_email, :subject => "SMS credit recharge failed", :body =>"SMS account could not be recharged with #{amount} sms. Error: #{body}"
end
def error_notification message, response
mail :to => ShortMessage.config.reload_notification_email, :subject => "Error delivering SMS to #{message.recipient}", :body =>"SMS from #{message.sender} to #{message.recipient} could not be sent!\r\n\r\nResponse: #{response.to_yaml}"
end
end
end
require "net/http"
module ShortMessage
class Message < ActiveRecord::Base
attr_accessible :message_key, :recipient, :sender, :status_code, :text
def status_text
I18n.t("short_message.status.code_#{self.status_code}")
end
def deliver
self.sender = ShortMessage.config.default_sms_sender if self.sender.blank?
unless self.recipient.blank? and self.text.blank?
http = Net::HTTP.new(ShortMessage.config.gateway_server, ShortMessage.config.gateway_port)
if ShortMessage.config.gateway_port == Net::HTTP.https_default_port()
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
response, data = http.post(ShortMessage.config.send_file_path, build_deliver_params_string)
if response.code == "200"
# returns something like 0:200: OK (<mobilenumber>:<msgid>)
result_set = response.body.gsub("(","").gsub(")","").split(":")
self.status_code = result_set[0].to_i
self.message_key = result_set[3] unless result_set[3].blank?
if self.status_code == 3 and ShortMessage.config.default_reload_amount > 0
if self.recharge
self.deliver
else
self.status_code = 99
return false
end
end
self.save
true
else
Mailer.error_notification(self, response).deliver unless ShortMessage.config.admin_notification_email.blank?
false
end
end
end
def recharge amount = ShortMessage.config.default_reload_amount
unless ShortMessage.config.account_functions_path.blank?
http = Net::HTTP.new(ShortMessage.config.gateway_server)
response, body = http.post(ShortMessage.config.account_functions_path, build_recharge_params_string(amount))
if response.code == "200"
# returns something like 0:Successful
result_set = response.body.split(":")
if result_set[0].to_i == 0
logger.info "SMS account successfully charged with #{amount} sms."
Mailer.recharge_notification(amount).deliver unless ShortMessage.config.reload_notification_email.blank?
Mailer.voucher_notification(amount).deliver unless ShortMessage.config.voucher_notification_email.blank?
true
else
logger.warn "SMS account could not be recharged with #{amount} sms. Error: #{body}"
Mailer.recharge_failed_notification(amount, body).deliver unless ShortMessage.config.reload_notification_email.blank?
false
end
else
"#{response.code} #{response.message}"
end
end
end
private
def build_deliver_params_string
params = []
params << "UserID=#{ShortMessage.config.user_id}"
params << "CCUID=#{ShortMessage.config.ccu_id}"
params << "ID=#{ShortMessage.config.id_string}"
params << "sender=#{CGI.escape(self.sender)}"
params << "receipient=#{CGI.escape(self.recipient)}"
params << "message=#{CGI.escape(self.text)}"
params << "utf-8=1"
params.join("&")
end
def build_recharge_params_string amount
params = []
params << "UserIDFS=#{ShortMessage.config.user_id}"
params << "CCUID=#{ShortMessage.config.ccu_id}"
params << "pay=1"
params << "amount=#{amount}"
params << "idstring=#{ShortMessage.config.id_string}"
params.join("&")
end
end
end
<!DOCTYPE html>
<html>
<head>
<title>ShortMessage</title>
<%= stylesheet_link_tag "short_message/application", media: "all" %>
<%= javascript_include_tag "short_message/application" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
#!/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.
# This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application.
ENGINE_ROOT = File.expand_path('../..', __FILE__)
ENGINE_PATH = File.expand_path('../../lib/short_message/engine', __FILE__)
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
require 'rails/all'
require 'rails/engine/commands'
class CreateShortMessageMessages < ActiveRecord::Migration
def change
create_table :short_message_messages do |t|
t.string :message_key
t.string :sender
t.string :recipient
t.integer :status_code
t.text :text
t.timestamps
end
end
end
module ShortMessage
module Generators
class InstallGenerator < Rails::Generators::Base
desc "Copy ShortMessage configuration files"
source_root File.expand_path('../templates', __FILE__)
def copy_config
template "config/initializers/short_message.rb"
template "config/locales/short_message.de.yml"
template "config/locales/short_message.en.yml"
end
end
end
end
ShortMessage.configure do |config|
config.gateway_server = "www1.q-x.ch"
config.gateway_port = 443
config.send_file_path = "/app/sms/gw1/cust/send.php"
config.account_functions_path = "/app/sms/gw1/cust/accfunc.php"
# enter your details received from provider here
config.user_id = ""
config.ccu_id = ""
config.id_string = ""
config.default_reload_amount = 1000
config.default_mail_sender = "webmaster@your-domain.com"
config.reload_notification_email = "webmaster@your-domain.com"
config.admin_notification_email = "webmaster@your-domain.com" # set to blank to deactivate error mailing
config.voucher_notification_email = "give-me-money@your-domain.com" # set nil to disable voucher mailing
# set a default sms sender (used if no sender is present)
# config.default_sms_sender = ""
end
de:
short_message:
status:
code_1: "Empfänger abwesend"
code_3: "anerkannt"
code_5: "anruf blockiert"
code_6: "MSC Fehler"
code_7: "zugestellt"
code_18: "abgewiesen"
code_20: "nicht verfügbar während Roaming"
code_21: "unerwarteter Wert"
code_22: "unbekannter Abonnent"
code_99: "Aufladen fehlgeschlagen"
code_999: "unkategorisierter Status"
en:
short_message:
status:
code_1: "absent subscriber"
code_3: "accepted"
code_5: "call barred"
code_6: "controlling MSC failure"
code_7: "delivered"
code_18: "rejected by gateway"
code_20: "unavailable while roaming to"
code_21: "unexpected data value"
code_22: "unknown subscriber"
code_99: "recharge failed"
code_999: "uncategorized status"
require "short_message/engine"
require "short_message/config"
module ShortMessage
end
require 'active_support/configurable'
module ShortMessage
def self.configure(&block)
yield @config ||= ShortMessage::Configuration.new
end
def self.config
@config
end
class Configuration #:nodoc:
include ActiveSupport::Configurable
config_accessor :gateway_server
config_accessor :gateway_port
config_accessor :send_file_path
config_accessor :account_functions_path
config_accessor :user_id
config_accessor :ccu_id
config_accessor :id_string
config_accessor :default_sms_sender
config_accessor :default_reload_amount
config_accessor :reload_notification_email
config_accessor :admin_notification_email
config_accessor :voucher_notification_email
config_accessor :default_mail_sender
def param_name
config.param_name.respond_to?(:call) ? config.param_name.call : config.param_name
end
# define param_name writer (copied from AS::Configurable)
writer, line = 'def param_name=(value); config.param_name = value; end', __LINE__
singleton_class.class_eval writer, __FILE__, line
class_eval writer, __FILE__, line
end
end
module ShortMessage
class Engine < ::Rails::Engine
isolate_namespace ShortMessage
initializer "short_message.migrate_database" do |app|
Rails.application.config.paths['db/migrate'] << paths["db/migrate"].expanded.join
end
config.generators do |g|
g.test_framework :rspec, :fixture => false
g.fixture_replacement :factory_girl, :dir => 'spec/factories'
g.assets false
g.helper false
end
end
end
module ShortMessage
VERSION = "0.1.0"
VERSION = "0.0.1"
end
......@@ -8,22 +8,16 @@ Gem::Specification.new do |s|
s.name = "short_message"
s.version = ShortMessage::VERSION
s.authors = ["Andi Saurer"]
s.email = ["andi@saurer.me"]
s.homepage = "https://github.com/qinglong15/short_message"
s.summary = "Send short messages to a specific SMS Gateway"
s.description = "Send short messages to a specific SMS Gateway"
s.email = ["andreas.saurer@econ.uzh.ch"]
s.homepage = "TODO"
s.summary = "TODO: Summary of ShortMessage."
s.description = "TODO: Description of ShortMessage."
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"]
s.test_files = Dir["spec/**/*"]
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rails", "> 3.2.12"
# s.add_dependency "jquery-rails"
s.add_dependency "rails", "~> 4.2.6"
s.add_development_dependency "mysql2"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "capybara"
s.add_development_dependency "factory_girl_rails"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "rb-fsevent"
s.add_development_dependency "growl"
end
# encoding: utf-8
module ConfigHelper
def load_default_config
ShortMessage.configure do |config|
config.user_id = "1234"
config.ccu_id = "1234"
config.id_string = "123456789abcdefghijklmnopq"
config.default_reload_amount = 1000
config.reload_notification_email = "webmaster@your-domain.com"
config.voucher_notification_email = "give-me-money@your-domain.com"
config.default_mail_sender = "webmaster@your-domain.com"
end
end
end
== Welcome to Rails
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
This pattern splits the view (also called the presentation) into "dumb"
templates that are primarily responsible for inserting pre-built data in between
HTML tags. The model contains the "smart" domain objects (such as Account,
Product, Person, Post) that holds all the business logic and knows how to
persist themselves to a database. The controller handles the incoming requests
(such as Save New Account, Update Product, Show Post) by manipulating the model
and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, create a new Rails application:
<tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
2. Change directory to <tt>myapp</tt> and start the web server:
<tt>cd myapp; rails server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and you'll see:
"Welcome aboard: You're riding Ruby on Rails!"
4. Follow the guidelines to start developing your application. You can find
the following resources handy:
* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands
running on the server.log and development.log. Rails will automatically display
debugging and runtime information to these files. Debugging info will also be
shown in the browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code
using the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
several books available online as well:
* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two books will bring you up to speed on the Ruby language and also on
programming in general.
== Debugger
Debugger support is available through the debugger command when you start your
Mongrel or WEBrick server with --debugger. This means that you can break out of
execution at any point in the code, investigate and change the model, and then,
resume execution! You need to install ruby-debug to run the server in debugging
mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
@posts = Post.all
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#<Post:0x14a6be8
@attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
#<Post:0x14a6620
@attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better, you can examine how your runtime objects actually work:
>> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you can enter "cont".
== Console
The console is a Ruby shell, which allows you to interact with your
application's domain model. Here you'll have all parts of the application
configured, just like it is when the application is running. You can inspect
domain models, change values, and save to the database. Starting the script
without arguments will launch it in the development environment.
To start the console, run <tt>rails console</tt> from the application
directory.
Options:
* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
made to the database.
* Passing an environment name as an argument will load the corresponding
environment. Example: <tt>rails console production</tt>.
To reload your controllers and models after launching the console run
<tt>reload!</tt>
More information about irb can be found at:
link:http://www.rubycentral.org/pickaxe/irb.html
== dbconsole
You can go to the command line of your database directly through <tt>rails
dbconsole</tt>. You would be connected to the database with the credentials
defined in database.yml. Starting the script without arguments will connect you