limeade 0.1.0

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: dde82df533a775a40556b8dbb81994c0105024765909b76755d8c8328a9c6fc3
4
+ data.tar.gz: df433be9bbaca0e38f8c253dd919987f34d616c58072e08b8edb6b0a13ea11ca
5
+ SHA512:
6
+ metadata.gz: 793c66ca4da4fc38230b7b115d5dd353a31b5cd3e6a3fac98dd974cb945304847f946c322a0748c2cad1a95131c7547ea289ca6d9a76e10c51b15491c9116369
7
+ data.tar.gz: c5c692cf20af911dacdd44a3701a68a0c2d09d7836cb6a0c8e8ebfea473646c67eca7705c4f5bf7db5bf160a9f085327a42d01c2344b640521567bb5cdd7e37d
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ .idea
10
+ Gemfile.lock
11
+
12
+ # rspec failure tracking
13
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.3.3
7
+ before_install: gem install bundler -v 2.0.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at david.pellegrini@spokesoftware.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in limeade.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 David Pellegrini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # Limeade
2
+
3
+ Ruby interface to the LimeSurvey RemoteControl 2 API
4
+
5
+ LimeSurvey provides an API for accessing and managing surveys. The current version is RemoteControl 2.
6
+ It is exposed as a XML-RPC/JSON-RPC based web service. This gem accesses using JSON-RPC.
7
+
8
+ The goal of this gem is to access the API in a manner that is natural to rubyists. The API is defined in
9
+ terms of methods and arguments. That's easy to mimic in Ruby by means of `#method_missing`. Thus, call any
10
+ of the API's methods on the Limeade client itself!
11
+
12
+ This gem handles the API session transparently so you don't have to even think about it.
13
+
14
+ > __Note__ that before using the LimeSurvey RemoteControl API you need to activate it for your account.
15
+ See [the manual](https://manual.limesurvey.org/RemoteControl_2_API#How_to_configure_LSRC2) for
16
+ instructions on how to do this. Be sure to choose the **JSON-RPC** option.
17
+
18
+ > __Note__ also that you must activate a survey in order for it to be visible via the API.
19
+
20
+ ## Installation
21
+
22
+ Add this line to your application's Gemfile:
23
+
24
+ ```ruby
25
+ gem 'limeade'
26
+ ```
27
+
28
+ And then execute:
29
+
30
+ $ bundle
31
+
32
+ Or install it yourself as:
33
+
34
+ $ gem install limeade
35
+
36
+ ## Usage
37
+
38
+ Start by requiring limeade into your code.
39
+
40
+ ``` ruby
41
+ require 'limeade'
42
+ ```
43
+
44
+ Instantiate a client and start invoking API methods on it. The API methods are documented
45
+ [here](https://api.limesurvey.org/classes/remotecontrol_handle.html).
46
+
47
+ ```ruby
48
+ client = Limeade::Client.new(api_uri, username, password)
49
+ surveys = client.list_surveys
50
+ summary = client.get_summary(surveys.first['sid'])
51
+ ```
52
+
53
+ You'll probably want to get `api_uri`, `username`, and `password` from environment variables.
54
+
55
+ The responses from the API are parsed from JSON into Ruby objects. Bear in mind that `Hash` keys are
56
+ going to be `String`.
57
+
58
+ When you are done accessing the API, it is polite to disconnect.
59
+ ```ruby
60
+ client.disconnect
61
+ ```
62
+
63
+ ### Retry Mechanism
64
+
65
+ Not every network call goes as planned. Limeade uses the underlying Faraday gem for handling the
66
+ transport. Faraday has a retry mechanism,
67
+ [Faraday::Request::Retry](https://www.rubydoc.info/gems/faraday/0.9.2/Faraday/Request/Retry). Its
68
+ behavior is configurable via
69
+ [options](https://www.rubydoc.info/gems/faraday/0.9.2/Faraday/Request/Retry:initialize) offering a
70
+ high degree of control. These same options may be passed when instantiating `Limeade::Client`.
71
+
72
+ ```ruby
73
+ client = Limeade::Client.new(api_uri, username, password, max: 5, interval: 1.5)
74
+ ```
75
+
76
+ View the `Limeade::Client` documentation for details.
77
+
78
+ ### Logging
79
+
80
+ The gem defines a logger for its own use. Access it via `Limeade.logger`. Change logging
81
+ level like so `Limeade.logger.level = Logger::WARN`
82
+
83
+ You can substitute your own logger to consolidate logging throughout your app:
84
+ ```ruby
85
+ Limeade.logger = my_apps_logger
86
+ ```
87
+
88
+ ## Development
89
+
90
+ After checking out the repo, run `bin/setup` to install dependencies.
91
+
92
+ The specs rely on API location and credentials being defined as environment variables. Edit `bin/env.sh`
93
+ for your situation, then execute it.
94
+
95
+ $ source bin/env.sh
96
+
97
+ Then run the tests.
98
+
99
+ $ bundle exec rake spec
100
+
101
+ You can also run `bin/console` for an interactive prompt that will allow you to experiment.
102
+
103
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version,
104
+ update the version number in `version.rb`, and then run `bundle exec rake release`, which will create
105
+ a git tag for the version, push git commits and tags, and push the `.gem` file to
106
+ [rubygems.org](https://rubygems.org).
107
+
108
+ ## Contributing
109
+
110
+ Bug reports and pull requests are welcome on GitHub at https://github.com/spokesoftware/limeade.
111
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are
112
+ expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
113
+
114
+ ## License
115
+
116
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
117
+ Copyright 2019 David Pellegrini and Spoke Software, Inc.
118
+
119
+ ## Code of Conduct
120
+
121
+ Everyone interacting in the Limeade project’s codebases, issue trackers, chat rooms and mailing lists is
122
+ expected to follow the [code of conduct](https://github.com/spokesoftware/limeade/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'limeade'
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require 'pry'
11
+ # Pry.start
12
+
13
+ require 'irb'
14
+ IRB.start(__FILE__)
data/bin/env.sh ADDED
@@ -0,0 +1,21 @@
1
+ #!/bin/bash
2
+
3
+ # The spec suite connects to the LimeSurvey RemoteControl API. If you intend to run the
4
+ # specs, update this script with values specific to your situation. Then source this script
5
+ # to set up your environment prior to running the specs.
6
+ # Note that the specs test accessing a survey by id. Kindly provide that id below. If
7
+ # necessary, create a dummy survey for this purpose. It only has to exist and be activated.
8
+
9
+ # If you are not going to run the specs, you can skip this.
10
+
11
+ echo "Setting LimeSurvey API auth"
12
+
13
+ LIMESURVEY_ENDPOINT="https://<your_domain>.limequery.com/admin/remotecontrol"
14
+ LIMESURVEY_ACCOUNT="margarita"
15
+ LIMESURVEY_PASSWORD="sooper_seekrit"
16
+ LIMESURVEY_SURVEY_ID=<the id of one of your surveys>
17
+
18
+ export LIMESURVEY_ENDPOINT
19
+ export LIMESURVEY_ACCOUNT
20
+ export LIMESURVEY_PASSWORD
21
+ export LIMESURVEY_SURVEY_ID
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,157 @@
1
+ require 'limeade/methods'
2
+
3
+ module Limeade
4
+
5
+ # Client for accessing the LimeSurvey RemoteControl API from Ruby.
6
+ class Client
7
+
8
+ #
9
+ # Instantiate a client and setup a connection to the LimeSurvey RemoteControl API.
10
+ # Passes configuration for the Faraday::Request::Retry mechanism.
11
+ # @see Faraday::Request::Retry
12
+ #
13
+ # @param endpoint [String] The URI for your account's API.
14
+ # @param username [String] The username for your account.
15
+ # @param password [String] The password for your account.
16
+ # @param retry_options [Hash] The options for Faraday::Request::Retry.
17
+ # @option retry_options [Integer] :max (2) Maximum number of retries.
18
+ # @option retry_options [Float] :interval (0) Pause in seconds between retries.
19
+ # @option retry_options [Float] :interval_randomness (0) The maximum random interval amount
20
+ # expressed as a float between 0 and 1 to use in addition to the interval.
21
+ # @option retry_options [Float] :max_interval (Float::MAX) An upper limit for the interval.
22
+ # @option retry_options [Float] :backoff_factor (1) The amount to multiply each successive
23
+ # retry's interval amount by in order to provide backoff.
24
+ # @option retry_options [Array<Error, String>] :exceptions ([Errno::ETIMEDOUT, 'Timeout::Error',
25
+ # Error::TimeoutError, Faraday::Error::RetriableResponse]) The list of exceptions
26
+ # to handle. Exceptions can be given as Class, Module, or String.
27
+ # @option retry_options [Array<Symbol>] :methods (Faraday::Request::Retry::IDEMPOTENT_METHODS)
28
+ # A list of HTTP methods to retry without calling retry_if. Pass an empty Array to call
29
+ # retry_if for all exceptions.
30
+ # @option retry_options [Proc] :retry_if (return false) Block that will receive the env object
31
+ # and the exception raised and decides whether to retry regardless of the retry count.
32
+ # This would be useful if the exception produced is non-recoverable or if the the HTTP method
33
+ # called is not idempotent.
34
+ # @option retry_options [Proc] :retry_block Block that is executed after every retry. Request
35
+ # environment, middleware options, current number of retries and the exception are passed to
36
+ # the block as parameters.
37
+ #
38
+ # @raise [InvalidCredentialsError] The username and password combination is not valid.
39
+ # @raise [ServerError] The API endpoint server is having issues. An error code and message are
40
+ # included.
41
+ # @raise [InvalidResponseError] The API endpoint is returning malformed JSON RPC responses.
42
+ # A descriptive message details the problem.
43
+ # @raise [URI::InvalidURIError] The API endpoint URI is not valid.
44
+ def initialize(endpoint, username, password, retry_options = {})
45
+ @json_rpc = Limeade::JSON_RPC.new(endpoint, retry_options)
46
+ @username = username
47
+ @password = password
48
+ @session_key = get_session_key
49
+ end
50
+
51
+ # Is the client ready to send requests to the endpoint?
52
+ # @return [Boolean] true if the client is ready; false otherwise.
53
+ def connected?
54
+ @session_key && @json_rpc
55
+ end
56
+
57
+ # Release resources for this client locally and at the endpoint.
58
+ # @return [Boolean] true if the resources were released; false if client has already disconnected.
59
+ def disconnect
60
+ if connected?
61
+ release_session_key
62
+ @json_rpc = nil
63
+ @session_key = nil
64
+ true
65
+ else
66
+ false
67
+ end
68
+ end
69
+
70
+ # Handle LimeSurvey RemoteControl API calls invoked on the client by invoking them on the endpoint.
71
+ # @param method [Symbol] the method invoked
72
+ # @param arguments [Array] the arguments to the method
73
+ #
74
+ # @raise [ServerError] The API endpoint server is having issues. An error code and message are included.
75
+ # @raise [InvalidResponseError] The API endpoint is returning malformed JSON RPC responses. A descriptive message
76
+ #
77
+ # @return [Object] the result of invoking the method on the endpoint
78
+ def method_missing(method, *arguments)
79
+ if API_METHODS.include? method
80
+ process_request(method, *arguments)
81
+ else
82
+ super
83
+ end
84
+ end
85
+
86
+ def respond_to_missing?(method_name, include_private = false)
87
+ API_METHODS.include?(method_name) || super
88
+ end
89
+
90
+ private
91
+
92
+ # Send an LimeSurvey RemoteControl API call to the endpoint and handle the response.
93
+ # @param method [Symbol] the method invoked
94
+ # @param arguments [Array] the arguments to the method
95
+ #
96
+ # @raise [ServerError] The API endpoint server is having issues. An error code and message are included.
97
+ # @raise [InvalidResponseError] The API endpoint is returning malformed JSON RPC responses. A descriptive message
98
+ #
99
+ # @return [Object] the result of invoking the method on the endpoint
100
+ def process_request(method_name, *arguments)
101
+ raise DisconnectedError unless connected?
102
+ result = @json_rpc.invoke(method_name, @session_key, *arguments)
103
+ if result.is_a? Hash and result['status']
104
+ case result['status']
105
+ when 'OK'
106
+ true
107
+ when 'No surveys found'
108
+ []
109
+ when 'No Tokens found'
110
+ []
111
+ when /(left to send)|(No candidate tokens)$/
112
+ result
113
+ when /Invalid surveyid$/i
114
+ nil
115
+ when /Invalid session key$/i
116
+ raise NoSessionError
117
+ else
118
+ raise APIError.new(method_name, result['status'])
119
+ end
120
+ else
121
+ result
122
+ end
123
+ rescue NoSessionError
124
+ # Get a fresh session and retry the call.
125
+ @session_key = get_session_key
126
+ retry
127
+ end
128
+
129
+ # Get a session key from the endpoint
130
+ #
131
+ # @raise [InvalidCredentialsError] The username and password combination is not valid.
132
+ # @raise [ServerError] The API endpoint server is having issues. An error code and message are included.
133
+ # @raise [InvalidResponseError] The API endpoint is returning malformed JSON RPC responses. A descriptive message
134
+ # details the problem.
135
+ #
136
+ # @return [String] the session key
137
+ def get_session_key
138
+ response = @json_rpc.invoke(:get_session_key, @username, @password)
139
+ raise(InvalidCredentialsError, (response['status'] || response.inspect)) if response.is_a?(Hash)
140
+ response
141
+ end
142
+
143
+ # Release a session key on the endpoint
144
+ #
145
+ # @raise [ServerError] The API endpoint server is having issues. An error code and message are included.
146
+ # @raise [InvalidResponseError] The API endpoint is returning malformed JSON RPC responses. A descriptive message
147
+ #
148
+ # @return [String] "OK"
149
+ def release_session_key
150
+ @json_rpc.invoke(:release_session_key, @session_key)
151
+ end
152
+ end
153
+
154
+ # Private exception raised only in the context of #process_request.
155
+ class NoSessionError < Error; end
156
+
157
+ end
@@ -0,0 +1,31 @@
1
+ module Limeade
2
+
3
+ class Error < StandardError; end
4
+
5
+ class InvalidResponseError < Error; end
6
+
7
+ class InvalidCredentialsError < Error; end
8
+
9
+ class DisconnectedError < Error
10
+ def initialize
11
+ super('Attempting to use a disconnected client to the LimeSurvey API')
12
+ end
13
+ end
14
+
15
+ class ServerError < Error
16
+ attr_reader :code, :response_error
17
+
18
+ def initialize(code, message)
19
+ @code = code
20
+ @response_error = message
21
+ super("Server error #{code}: #{message}")
22
+ end
23
+ end
24
+
25
+ class APIError < Error
26
+ def initialize(method, status)
27
+ super("LimeSurvey API '#{method}' returned a failure status: #{status}")
28
+ end
29
+ end
30
+
31
+ end
@@ -0,0 +1,126 @@
1
+ require 'faraday'
2
+ require 'multi_json'
3
+
4
+ module Limeade
5
+
6
+ # An implementation of JSON RPC version 1. This is inspired by jsonrpc-client, which implements
7
+ # version 2 of the spec. This implementation adds retry capability via Faraday::Request::Retry.
8
+
9
+ class JSON_RPC
10
+
11
+ JSON_RPC_VERSION = '1.0'.freeze
12
+
13
+ #
14
+ # Instantiate a client and setup a connection to the endpoint.
15
+ # Passes configuration for the Faraday::Request::Retry mechanism.
16
+ # @see Faraday::Request::Retry
17
+ #
18
+ # @param retry_options [Hash] The options for Faraday::Request::Retry.
19
+ # @option retry_options [Integer] :max (2) Maximum number of retries.
20
+ # @option retry_options [Float] :interval (0) Pause in seconds between retries.
21
+ # @option retry_options [Float] :interval_randomness (0) The maximum random interval amount
22
+ # expressed as a float between 0 and 1 to use in addition to the interval.
23
+ # @option retry_options [Float] :max_interval (Float::MAX) An upper limit for the interval.
24
+ # @option retry_options [Float] :backoff_factor (1) The amount to multiply each successive
25
+ # retry's interval amount by in order to provide backoff.
26
+ # @option retry_options [Array<Error, String>] :exceptions ([Errno::ETIMEDOUT, 'Timeout::Error',
27
+ # Error::TimeoutError, Faraday::Error::RetriableResponse]) The list of exceptions
28
+ # to handle. Exceptions can be given as Class, Module, or String.
29
+ # @option retry_options [Array<Symbol>] :methods (Faraday::Request::Retry::IDEMPOTENT_METHODS)
30
+ # A list of HTTP methods to retry without calling retry_if. Pass an empty Array to call
31
+ # retry_if for all exceptions.
32
+ # @option retry_options [Proc] :retry_if (return false) Block that will receive the env object
33
+ # and the exception raised and decides whether to retry regardless of the retry count.
34
+ # This would be useful if the exception produced is non-recoverable or if the the HTTP method
35
+ # called is not idempotent.
36
+ # @option retry_options [Proc] :retry_block Block that is executed after every retry. Request
37
+ # environment, middleware options, current number of retries and the exception are passed to
38
+ # the block as parameters.
39
+ #
40
+ # @raise [ServerError] The API endpoint server is having issues. An error code and message are
41
+ # included.
42
+ # @raise [InvalidResponseError] The API endpoint is returning malformed JSON RPC responses.
43
+ # A descriptive message details the problem.
44
+ # @raise [URI::InvalidURIError] The API endpoint URI is not valid.
45
+ def initialize(endpoint, retry_options = {})
46
+ @uri = ::URI.parse(endpoint).to_s # Ensure that endpoint is a valid URI
47
+ @retry_options = retry_options || {} # Ensure not nil
48
+ end
49
+
50
+ # Send the request with the specified method and arguments
51
+ # @param method [Symbol] the method to invoke
52
+ # @param args [Array] the arguments to the method
53
+ # @return the results of the call
54
+ def invoke(method, *args)
55
+ Limeade.logger.debug "invoke(#{method}, #{args.inspect})"
56
+ request_id = make_id
57
+ post_data = ::MultiJson.encode({
58
+ 'jsonrpc' => JSON_RPC_VERSION,
59
+ 'method' => method,
60
+ 'params' => args,
61
+ 'id' => request_id
62
+ })
63
+ response = connection.post(@uri, post_data, STANDARD_HEADERS)
64
+
65
+ Limeade.logger.debug "API response: #{response.inspect}"
66
+
67
+ process_response(response, request_id)
68
+ end
69
+
70
+ private
71
+
72
+ STANDARD_HEADERS = {content_type: 'application/json'}.freeze
73
+
74
+ def connection
75
+ @connection ||= ::Faraday.new do |connection|
76
+ connection.request :retry, @retry_options
77
+ connection.response :logger, Limeade.logger
78
+ connection.adapter ::Faraday.default_adapter
79
+ end
80
+ end
81
+
82
+ def process_response(response, request_id)
83
+ verify_response(response)
84
+ payload = payload_from(response)
85
+ verify_payload(payload, request_id)
86
+ raise ServerError.new(payload['error']['code'], payload['error']['message']) if payload['error']
87
+ payload['result']
88
+ end
89
+
90
+ def verify_response(response)
91
+ Limeade.logger.debug "verify_response: #{response.inspect}"
92
+ raise(InvalidResponseError, 'Response is nil') if response.nil?
93
+ raise(InvalidResponseError, 'Response body is nil') if response.body.nil?
94
+ raise(InvalidResponseError, 'Response body is empty') if response.body.empty?
95
+ end
96
+
97
+ def verify_payload(payload, request_id)
98
+ Limeade.logger.debug "verify_payload: #{payload.inspect}"
99
+ raise(InvalidResponseError, 'Response body is not a Hash') unless payload.is_a?(::Hash)
100
+ raise(InvalidResponseError, 'Response body is missing the id') unless payload.has_key?('id')
101
+ raise(InvalidResponseError, "Response id (#{payload['id']}) does not match request id (#{request_id})") unless (payload['id'] == request_id)
102
+ raise(InvalidResponseError, 'Response body must have a result and an error') unless (payload.has_key?('error') && payload.has_key?('result'))
103
+
104
+ if payload['error']
105
+ error = payload['error']
106
+ raise(InvalidResponseError, 'Response error is not a Hash') unless error.is_a?(::Hash)
107
+ raise(InvalidResponseError, 'Response error is missing the code') unless error.has_key?('code')
108
+ raise(InvalidResponseError, 'Response error code is not a number') unless error['code'].is_a?(::Integer)
109
+ raise(InvalidResponseError, 'Response error is missing the message') unless error.has_key?('message')
110
+ raise(InvalidResponseError, 'Response error message is not a string') unless error['message'].is_a?(::String)
111
+ end
112
+ end
113
+
114
+ def payload_from(response)
115
+ ::MultiJson.decode(response.body)
116
+ rescue => parsing_error
117
+ Limeade.logger.info "Failed to parse JSON from:\n#{response.body}"
118
+ raise InvalidResponseError, parsing_error.message
119
+ end
120
+
121
+ def make_id
122
+ rand(10**12)
123
+ end
124
+
125
+ end
126
+ end
@@ -0,0 +1,53 @@
1
+ module Limeade
2
+ API_METHODS = (<<_API_METHODS
3
+ activate_survey
4
+ activate_tokens
5
+ add_group
6
+ add_language
7
+ add_participants
8
+ add_response
9
+ add_survey
10
+ copy_survey
11
+ cpd_importParticipants
12
+ delete_group
13
+ delete_language
14
+ delete_participants
15
+ delete_question
16
+ delete_survey
17
+ export_responses
18
+ export_responses_by_token
19
+ export_statistics
20
+ export_timeline
21
+ get_group_properties
22
+ get_language_properties
23
+ get_participant_properties
24
+ get_question_properties
25
+ get_response_ids
26
+ get_session_key
27
+ get_site_settings
28
+ get_summary
29
+ get_survey_properties
30
+ get_uploaded_files
31
+ import_group
32
+ import_question
33
+ import_survey
34
+ invite_participants
35
+ list_groups
36
+ list_participants
37
+ list_questions
38
+ list_surveys
39
+ list_users
40
+ mail_registered_participants
41
+ release_session_key
42
+ remind_participants
43
+ set_group_properties
44
+ set_language_properties
45
+ set_participant_properties
46
+ set_question_properties
47
+ set_quota_properties
48
+ set_survey_properties
49
+ update_response
50
+ upload_file
51
+ _API_METHODS
52
+ ).split("\n").map(&:to_sym).freeze
53
+ end
@@ -0,0 +1,3 @@
1
+ module Limeade
2
+ VERSION = '0.1.0'
3
+ end
data/lib/limeade.rb ADDED
@@ -0,0 +1,17 @@
1
+ require 'limeade/version'
2
+ require 'limeade/errors'
3
+ require 'limeade/client'
4
+ require 'limeade/json_rpc'
5
+ require 'logger'
6
+
7
+ module Limeade
8
+
9
+ def self.logger
10
+ @logger ||= ::Logger.new($stdout)
11
+ end
12
+
13
+ def self.logger=(logger)
14
+ @logger = logger
15
+ end
16
+
17
+ end
data/limeade.gemspec ADDED
@@ -0,0 +1,44 @@
1
+
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'limeade/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'limeade'
8
+ spec.version = Limeade::VERSION
9
+ spec.authors = ['David Pellegrini']
10
+ spec.email = ['david.pellegrini@spokesoftware.com']
11
+
12
+ spec.summary = %q{A Ruby interface to the LimeSurvey API.}
13
+ spec.description = %q{LimeSurvey exposes a JSON-RPC API for querying and managing surveys. This gem abstracts away the RPC calls and provides a friendly interface for Ruby clients.}
14
+ spec.homepage = 'https://github.com/spokesoftware/limeade'
15
+ spec.license = 'MIT'
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
21
+
22
+ spec.metadata['homepage_uri'] = spec.homepage
23
+ spec.metadata['source_code_uri'] = 'https://github.com/spokesoftware/limeade'
24
+ spec.metadata['changelog_uri'] = 'https://github.com/spokesoftware/limeade/releases'
25
+ else
26
+ raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.'
27
+ end
28
+
29
+ # Specify which files should be added to the gem when it is released.
30
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
31
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
32
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
33
+ end
34
+ spec.bindir = 'exe'
35
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
36
+ spec.require_paths = ['lib']
37
+
38
+ spec.add_runtime_dependency 'faraday'
39
+ spec.add_runtime_dependency 'multi_json'
40
+
41
+ spec.add_development_dependency 'bundler', '< 2.0'
42
+ spec.add_development_dependency 'rake', '~> 10.0'
43
+ spec.add_development_dependency 'rspec', '~> 3.2'
44
+ end
metadata ADDED
@@ -0,0 +1,137 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: limeade
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - David Pellegrini
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-06-07 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: multi_json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "<"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "<"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.2'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.2'
83
+ description: LimeSurvey exposes a JSON-RPC API for querying and managing surveys.
84
+ This gem abstracts away the RPC calls and provides a friendly interface for Ruby
85
+ clients.
86
+ email:
87
+ - david.pellegrini@spokesoftware.com
88
+ executables: []
89
+ extensions: []
90
+ extra_rdoc_files: []
91
+ files:
92
+ - ".gitignore"
93
+ - ".rspec"
94
+ - ".travis.yml"
95
+ - CODE_OF_CONDUCT.md
96
+ - Gemfile
97
+ - LICENSE.txt
98
+ - README.md
99
+ - Rakefile
100
+ - bin/console
101
+ - bin/env.sh
102
+ - bin/setup
103
+ - lib/limeade.rb
104
+ - lib/limeade/client.rb
105
+ - lib/limeade/errors.rb
106
+ - lib/limeade/json_rpc.rb
107
+ - lib/limeade/methods.rb
108
+ - lib/limeade/version.rb
109
+ - limeade.gemspec
110
+ homepage: https://github.com/spokesoftware/limeade
111
+ licenses:
112
+ - MIT
113
+ metadata:
114
+ allowed_push_host: https://rubygems.org
115
+ homepage_uri: https://github.com/spokesoftware/limeade
116
+ source_code_uri: https://github.com/spokesoftware/limeade
117
+ changelog_uri: https://github.com/spokesoftware/limeade/releases
118
+ post_install_message:
119
+ rdoc_options: []
120
+ require_paths:
121
+ - lib
122
+ required_ruby_version: !ruby/object:Gem::Requirement
123
+ requirements:
124
+ - - ">="
125
+ - !ruby/object:Gem::Version
126
+ version: '0'
127
+ required_rubygems_version: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ requirements: []
133
+ rubygems_version: 3.0.3
134
+ signing_key:
135
+ specification_version: 4
136
+ summary: A Ruby interface to the LimeSurvey API.
137
+ test_files: []