ifree-sms 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "http://rubygems.org"
2
+
3
+ platforms :ruby do
4
+ gem 'curb', '~> 0.7.15'
5
+ gem 'nokogiri'
6
+ gem 'activemodel'
7
+ end
File without changes
@@ -34,22 +34,20 @@ Initialize IfreeSms and set its configurations.
34
34
  end
35
35
  end
36
36
 
37
- Send sms answer to user (asynchronous)
37
+ Send sms message to user (asynchronous)
38
38
 
39
- * phone format => 380971606179
40
- * text length => 160 Latin or 70 Unicode
41
- * sms_id - unique sms id
39
+ * phone - format => 380971606179
40
+ * text - length => 160 Latin or 70 Unicode (encoding utf-8)
41
+ * from - sender title, max length: 11
42
42
 
43
- IfreeSms.send_sms(phone, text, sms_id)
43
+ smsdirect = IfreeSms::SMSDirectAPI.new(login, password)
44
+
45
+ smsdirect.submit_message(phone, text, from)
44
46
 
45
47
  or
46
48
 
47
49
  IfreeSms::Message.first.send_answer("some text")
48
50
 
49
- If you want to send sms to custom user, don't put sms_id (Paid action)
50
-
51
- IfreeSms.send_sms(phone, text)
52
-
53
51
  == Dependences
54
52
 
55
53
  * {curb}[https://github.com/taf2/curb]
data/Rakefile CHANGED
@@ -2,7 +2,6 @@
2
2
  require 'rake'
3
3
  require 'rake/testtask'
4
4
  require 'rake/rdoctask'
5
- require File.join(File.dirname(__FILE__), 'lib', 'ifree_sms', 'version')
6
5
 
7
6
  desc 'Default: run unit tests.'
8
7
  task :default => :test
@@ -23,22 +22,3 @@ Rake::RDocTask.new(:rdoc) do |rdoc|
23
22
  rdoc.rdoc_files.include('README')
24
23
  rdoc.rdoc_files.include('lib/**/*.rb')
25
24
  end
26
-
27
- begin
28
- require 'jeweler'
29
- Jeweler::Tasks.new do |s|
30
- s.name = "ifree-sms"
31
- s.version = IfreeSms::VERSION.dup
32
- s.summary = "The IfreeSms gem for i-free sms provider"
33
- s.description = "The IfreeSms gem for i-free sms provider"
34
- s.email = "superp1987@gmail.com"
35
- s.homepage = "https://github.com/superp/ifree-sms"
36
- s.authors = ["Igor Galeta", "Pavlo Galeta"]
37
- s.files = FileList["[A-Z]*", "{app,lib}/**/*"] - ["Gemfile"]
38
- #s.extra_rdoc_files = FileList["[A-Z]*"]
39
- end
40
-
41
- Jeweler::GemcutterTasks.new
42
- rescue LoadError
43
- puts "Jeweler not available. Install it with: gem install jeweler"
44
- end
@@ -5,6 +5,8 @@ if Object.const_defined?("IfreeSms")
5
5
  config.secret_key = ""
6
6
  config.project_name = ""
7
7
  config.service_number = ""
8
+ config.login = ""
9
+ config.password = ""
8
10
  config.debug = true
9
11
  end
10
12
 
@@ -8,45 +8,77 @@ module IfreeSms
8
8
  autoload :Manager, 'ifree_sms/manager'
9
9
  autoload :Config, 'ifree_sms/config'
10
10
  autoload :Callbacks, 'ifree_sms/callbacks'
11
+ autoload :Response, 'ifree_sms/response'
12
+ autoload :SMSDirectAPIMethods, 'ifree_sms/smsdirect_api'
11
13
 
12
14
  mattr_accessor :config
13
15
  @@config = Config.new
14
16
 
17
+ class API
18
+ # initialize with an access token
19
+ def initialize(login = nil, pass = nil)
20
+ @login = login || IfreeSms.config.login
21
+ @pass = pass || IfreeSms.config.password
22
+ end
23
+ attr_reader :access_token
24
+
25
+ def api(path, args = {}, verb = "get", options = {}, &error_checking_block)
26
+ # Fetches the given path in the Graph API.
27
+ args["login"] = @login
28
+ args["pass"] = @pass
29
+
30
+ # add a leading /
31
+ path = "/#{path}" unless path =~ /^(\/|http|https|ftp)/
32
+
33
+ # make the request via the provided service
34
+ result = IfreeSms.make_request(path, args, verb, options)
35
+
36
+ # Check for any 500 errors before parsing the body
37
+ # since we're not guaranteed that the body is valid JSON
38
+ # in the case of a server error
39
+ raise APIError.new({"type"=>"HTTP #{result.status.to_s}", "message"=>"Response body: #{result.body}"}) if result.status >= 500
40
+
41
+ body = result.body
42
+ yield body if error_checking_block
43
+
44
+ # if we want a component other than the body (e.g. redirect header for images), return that
45
+ options[:http_component] ? result.send(options[:http_component]) : body
46
+ end
47
+ end
48
+
49
+ class APIError < StandardError
50
+ attr_accessor :sms_error_type
51
+ def initialize(details = {})
52
+ self.sms_error_type = details["type"]
53
+ super("#{sms_error_type}: #{details["message"]}")
54
+ end
55
+ end
56
+
57
+ # APIs
58
+
59
+ class SMSDirectAPI < API
60
+ include SMSDirectAPIMethods
61
+ end
62
+
63
+ # Class methods
64
+
15
65
  def self.setup(&block)
16
66
  yield config
17
67
  end
18
68
 
19
69
  def self.log(message)
20
70
  if IfreeSms.config.debug
21
- Rails.logger.info("[IfreeSms] #{message}")
71
+ Rails.logger.info("[Ifree #{Time.now.strftime('%d.%m.%Y %H:%M')}] #{message}")
22
72
  end
23
73
  end
24
74
 
25
75
  def self.table_name_prefix
26
76
  'ifree_sms_'
27
77
  end
28
-
29
- # Send sms message
30
- # Sample request:
31
- # http://srv1.com.ua/mcdonalds/second.php?smsId=noID&phone=380971606179&serviceNumber=3533&smsText=test-message&md5key=f920c72547012ece62861938b7731415&now=20110527160613
32
- #
33
- def self.send_sms(phone, text, sms_id='noID')
34
- now = Time.now.utc.strftime("%Y%m%d%H%M%S")
35
-
36
- params = {}
37
- params[:smsId] = sms_id
38
- params[:phone] = phone
39
- params[:serviceNumber] = config.service_number
40
- params[:smsText] = Base64.encode64(text)
41
- params[:now] = now
42
- params[:md5key] = calc_digest(config.service_number, params[:smsText], now)
43
-
44
- get(params)
45
- end
46
78
 
47
- def self.get(params)
79
+ def self.make_request(path, params, verb, options = {})
48
80
  query = Rack::Utils.build_query(params)
49
- url = [config.url, query].join('?')
81
+ url = [path, query].join('?')
50
82
 
51
83
  log("request: #{url}")
52
84
 
@@ -55,7 +87,7 @@ module IfreeSms
55
87
 
56
88
  log("response: #{http.body_str}")
57
89
 
58
- http.body_str
90
+ Response.new(http.response_code, http.body_str, http.headers)
59
91
  end
60
92
 
61
93
  def self.calc_digest(number, text, now)
@@ -25,7 +25,7 @@ module IfreeSms
25
25
  end
26
26
  end
27
27
 
28
- hash_accessor :routes, :secret_key, :service_number, :project_name, :debug
28
+ hash_accessor :routes, :secret_key, :service_number, :project_name, :login, :password, :debug
29
29
 
30
30
  def initialize(other={})
31
31
  merge!(other)
@@ -33,6 +33,8 @@ module IfreeSms
33
33
  self[:secret_key] ||= "some_very_secret_key_given_ifree"
34
34
  self[:service_number] ||= "some_service_number"
35
35
  self[:project_name] ||= "project_name"
36
+ self[:login] ||= "demo"
37
+ self[:password] ||= "demo"
36
38
  self[:debug] ||= false
37
39
  end
38
40
 
@@ -0,0 +1,10 @@
1
+ module IfreeSms
2
+ class Response
3
+ attr_reader :status, :body, :headers
4
+ def initialize(status, body, headers)
5
+ @status = status
6
+ @body = body
7
+ @headers = headers
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,95 @@
1
+ module IfreeSms
2
+ module SMSDirectAPIMethods
3
+ SMSDIRECT_SERVER = "https://www.smsdirect.ru"
4
+
5
+ # Send SMS message
6
+ # Sample request:
7
+ # GET /submit_message?login=demo&pass=demo&from=test&to=380503332211&text=smsdirect_submit_sm
8
+ #
9
+ def submit_message(phone, text, from = 'test')
10
+ call("submit_message", {:from => from, :to => phone, :text => text})
11
+ end
12
+
13
+ # Получение статуса сообщения
14
+ # Параметры запроса:
15
+ # mid - ID сообщения полученный с помощью вызова submit_message
16
+ #
17
+ def status_message(message_id)
18
+ call("status_message", {:mid => message_id})
19
+ end
20
+
21
+ # Создание/обновление базы абонентов
22
+ # Параметры запроса:
23
+ # id - ID базы (может быть пустым при создании новой базы);
24
+ # lname - название базы (может быть пустым);
25
+ # qfile - список записей разделенных переводом строк, со следующими полями (поля разделяются знаком ;):
26
+ # msisdn;name;secondname;lastname;city;date;sex
27
+ # поле msisdn - номер телефона абонента;
28
+ # поля name;secondname;lastname;city;sex - текстовые, по указанным именам их можно использовать в п.8 в поле mess, для подстановки значений (при указании поля pattern = 1);
29
+ # поле date - дата в формате ДД-ММ-ГГГГ;
30
+ #
31
+ def submit_db(uid, qfile, name = '')
32
+ call("submit_db", {:id => uid, :qfile => qfile, :lname => name})
33
+ end
34
+
35
+ # Удаление записей из базы абонентов
36
+ # Параметры запроса:
37
+ # id - ID базы;
38
+ # msisdn - список номеров телефонов подлежащих удалению, разделенные запятой (,).
39
+ #
40
+ def edit_db(uid, phones)
41
+ call('edit_db', {:id => uid, :msisdn => phones.join(',')})
42
+ end
43
+
44
+ # Получение статуса базы
45
+ # Параметры запроса:
46
+ # id - ID базы;
47
+ #
48
+ def status_db(uid)
49
+ call('status_db', {:id => uid})
50
+ end
51
+
52
+ # Получение списка созданных баз
53
+ #
54
+ def get_db
55
+ call("get_db")
56
+ end
57
+
58
+ # Удаление базы
59
+ # Параметры запроса:
60
+ # id - ID базы подлежащей удалению;
61
+ #
62
+ def delete_db(uid)
63
+ call("delete_db", {:id => uid})
64
+ end
65
+
66
+ # Отправка смс-рассылки по созданной базе пользователей
67
+ # Параметры запроса:
68
+ # typelist – тип данных (значения: 1 - база, 2 - список телефонов)
69
+ # list - ID базы\выборки;
70
+ # msisdn - список телефонов через запятую “,”
71
+ # mess - текст сообщения, в случае если параметр pattern=1, название полей для последующей подстановки,
72
+ # необходимо использовать в виде %ИМЯ ПОЛЯ%. Например, подстановка поля name будет выглядеть следующим образом:
73
+ # «Уважаемый %name% поздравляем Вас с днём рождения.»;
74
+ # isurl - признак wap-push (значения: 0 - отправлять как обычное сообщение, 1 - отправлять сообщения как push);
75
+ # wappushheader - заголовок wap-push (в случае если тип isurl = 1);
76
+ # max_mess - максимальное количество сообщений в день, оставить пустым, если не ограничено;
77
+ # max_mess_per_hour - максимальное количество сообщений в час, оставить пустым, если не ограничено;
78
+ def submit_dispatch(params = {})
79
+ call('submit_dispatch', params)
80
+ end
81
+
82
+ protected
83
+
84
+ def call(method_name, args = {}, options = {}, verb = "get")
85
+ options = options.merge!(:smsdirect_api => true)
86
+
87
+ api("#{SMSDIRECT_SERVER}/#{method_name}", args, verb, options) do |response|
88
+ # check for REST API-specific errors
89
+ if response.is_a?(Hash) && response["error_code"]
90
+ raise APIError.new("type" => response["error_code"], "message" => response["error_msg"])
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
@@ -1,4 +1,4 @@
1
1
  # encoding: utf-8
2
2
  module IfreeSms
3
- VERSION = "0.1.0".freeze
3
+ VERSION = "0.1.1".freeze
4
4
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ifree-sms
3
3
  version: !ruby/object:Gem::Version
4
- hash: 27
4
+ hash: 25
5
5
  prerelease:
6
6
  segments:
7
7
  - 0
8
8
  - 1
9
- - 0
10
- version: 0.1.0
9
+ - 1
10
+ version: 0.1.1
11
11
  platform: ruby
12
12
  authors:
13
13
  - Igor Galeta
@@ -16,11 +16,12 @@ autorequire:
16
16
  bindir: bin
17
17
  cert_chain: []
18
18
 
19
- date: 2011-06-08 00:00:00 +03:00
19
+ date: 2011-09-16 00:00:00 +03:00
20
20
  default_executable:
21
21
  dependencies:
22
22
  - !ruby/object:Gem::Dependency
23
- type: :runtime
23
+ name: curb
24
+ prerelease: false
24
25
  requirement: &id001 !ruby/object:Gem::Requirement
25
26
  none: false
26
27
  requirements:
@@ -32,27 +33,25 @@ dependencies:
32
33
  - 7
33
34
  - 15
34
35
  version: 0.7.15
35
- name: curb
36
+ type: :runtime
36
37
  version_requirements: *id001
37
- prerelease: false
38
38
  - !ruby/object:Gem::Dependency
39
- type: :runtime
39
+ name: nokogiri
40
+ prerelease: false
40
41
  requirement: &id002 !ruby/object:Gem::Requirement
41
42
  none: false
42
43
  requirements:
43
- - - ~>
44
+ - - ">="
44
45
  - !ruby/object:Gem::Version
45
- hash: 15
46
+ hash: 3
46
47
  segments:
47
- - 1
48
- - 4
49
- - 4
50
- version: 1.4.4
51
- name: nokogiri
48
+ - 0
49
+ version: "0"
50
+ type: :runtime
52
51
  version_requirements: *id002
53
- prerelease: false
54
52
  - !ruby/object:Gem::Dependency
55
- type: :runtime
53
+ name: activemodel
54
+ prerelease: false
56
55
  requirement: &id003 !ruby/object:Gem::Requirement
57
56
  none: false
58
57
  requirements:
@@ -62,9 +61,8 @@ dependencies:
62
61
  segments:
63
62
  - 0
64
63
  version: "0"
65
- name: activemodel
64
+ type: :runtime
66
65
  version_requirements: *id003
67
- prerelease: false
68
66
  description: The IfreeSms gem for i-free sms provider
69
67
  email: superp1987@gmail.com
70
68
  executables: []
@@ -72,25 +70,27 @@ executables: []
72
70
  extensions: []
73
71
 
74
72
  extra_rdoc_files:
75
- - LICENSE
76
73
  - README.rdoc
77
74
  files:
78
- - LICENSE
79
- - README.rdoc
80
- - Rakefile
81
75
  - app/models/ifree_sms/message.rb
76
+ - lib/ifree_sms.rb
82
77
  - lib/generators/ifree_sms/USAGE
83
- - lib/generators/ifree_sms/install_generator.rb
84
- - lib/generators/ifree_sms/templates/config/ifree_sms.rb
85
78
  - lib/generators/ifree_sms/templates/migrate/create_messages.rb
79
+ - lib/generators/ifree_sms/templates/config/ifree_sms.rb
80
+ - lib/generators/ifree_sms/install_generator.rb
86
81
  - lib/ifree-sms.rb
87
- - lib/ifree_sms.rb
88
- - lib/ifree_sms/callbacks.rb
89
- - lib/ifree_sms/config.rb
82
+ - lib/ifree_sms/smsdirect_api.rb
90
83
  - lib/ifree_sms/engine.rb
91
- - lib/ifree_sms/manager.rb
92
84
  - lib/ifree_sms/smsing.rb
85
+ - lib/ifree_sms/config.rb
86
+ - lib/ifree_sms/response.rb
87
+ - lib/ifree_sms/callbacks.rb
93
88
  - lib/ifree_sms/version.rb
89
+ - lib/ifree_sms/manager.rb
90
+ - MIT-LICENSE
91
+ - Rakefile
92
+ - Gemfile
93
+ - README.rdoc
94
94
  has_rdoc: true
95
95
  homepage: https://github.com/superp/ifree-sms
96
96
  licenses: []
@@ -120,7 +120,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
120
120
  version: "0"
121
121
  requirements: []
122
122
 
123
- rubyforge_project:
123
+ rubyforge_project: ifree-sms
124
124
  rubygems_version: 1.6.2
125
125
  signing_key:
126
126
  specification_version: 3