cubscout 0.2.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: c14b1d696bee8bbb568d385670e7153c000372720d55612c5ea307cb7ea51531
4
+ data.tar.gz: a4411b99e61b6fee43267bb88c39c3649ce9872813fa09044c4a352216aa9753
5
+ SHA512:
6
+ metadata.gz: cf9ab8423a1c3505d43cf8e4a6666e76427941c3125dd41db0aeaa83724953260cee8569f4a89ad7d7bab67ec61d87708a52c276611ad936ec093339c5cbeba0
7
+ data.tar.gz: 6487fcbec28d761890d88366196be75282a5d024bb7f809eafa6bbd7cd60f3a8d97c71ce7e4c10eb8bc6b03f84310f154ced7441345dfd91cdbaaabe3eca6b40
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ ### Unreleased
2
+
3
+ ### 0.2.0 - 2020-05-14
4
+
5
+ **Breaking changes**
6
+
7
+ - Use named `ThreadItem` and `Error` instead of generic object & error [#25](https://github.com/GetSilverfin/cubscout/pull/25)
8
+ - On association method calls, do not make a request to Helpscout by default [#24](https://github.com/GetSilverfin/cubscout/pull/24)
9
+ - `Cubscout::Scopes.all` method returns a `Cubscout::List` object instead of an array of items [#23](https://github.com/GetSilverfin/cubscout/pull/23)
10
+
11
+ **Dependencies**
12
+
13
+ - Bump rack from 2.0.7 to 2.0.8 [#21](https://github.com/GetSilverfin/cubscout/pull/21)
14
+ - Update rake requirement from ~> 10.0 to ~> 13.0 [#22](https://github.com/GetSilverfin/cubscout/pull/22)
15
+
16
+ ### 0.1.1 - 2019-11-14
17
+
18
+ **Fixes**
19
+
20
+ - use new Auth endpoint after deprecation of old one by helpscout [#16](https://github.com/GetSilverfin/cubscout/issues/16)
21
+
22
+ ### 0.1.0 - 2019-03-21
23
+
24
+ BROKEN: DO NOT USE (Auth endpoint deprecated by Helpscout)
@@ -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 silverfin.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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Silverfin NV
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,202 @@
1
+ [![Build Status](https://travis-ci.org/GetSilverfin/cubscout.svg?branch=master)](https://travis-ci.org/GetSilverfin/cubscout)
2
+
3
+ # Cubscout
4
+
5
+ Unofficial Ruby client for the [Helpscout API V2](https://developer.helpscout.com/mailbox-api/).
6
+
7
+ Cubscout is heavily inspired by [girlscout](https://github.com/omise/girlscout), another unofficial Ruby Client for Helpscout API V1.
8
+
9
+ ## Installation
10
+
11
+ Add `gem 'cubscout'` to your application's Gemfile, and then run `bundle` to install.
12
+
13
+ Or install it yourself as `gem install cubscout`.
14
+
15
+ ## Configuration
16
+
17
+ To get started, you need to configure the client with your App ID and App secret. If you are using Rails, you should add the following to a new initializer file in `config/initializers/helpscout.rb`.
18
+
19
+ ```ruby
20
+ require 'cubscout'
21
+
22
+ Cubscout::Config.client_id = 'YOUR_APP_ID'
23
+ Cubscout::Config.client_secret = 'YOUR_APP_SECRET'
24
+ ```
25
+
26
+ Note: Your App ID and App Secret are secret credentials, and you should treat them like passwords. You can create an App in your Helpscout account, under Your Profile > My Apps.
27
+
28
+ ## Usage
29
+
30
+ Cubscout mimics Active Record's querying pattern.
31
+
32
+ ### Conversations
33
+
34
+ List of conversations:
35
+
36
+ ```ruby
37
+ # all possible conversations available
38
+ # WARNING: this will create a lot of HTTP requests. You probably want some filtering.
39
+ conversations = Cubscout::Conversation.all
40
+
41
+ # conversations with filters
42
+ conversations = Cubscout::Conversation.all(tag: 'red,blue', status: 'active')
43
+
44
+ # Cubscout::Conversation.all returns a Cubscout::List object. You can iterate
45
+ # over it's Cubscout::Conversation items like this:
46
+ conversations.each { |conversation| puts conversation.mailbox_id }
47
+
48
+ # or you can also get some metadata information. For example if you only care
49
+ # about the number of items, you can query the first page only and find out how
50
+ # many elements exist in total:
51
+ Cubscout::Conversation.all(page: 1, tag: 'red,blue', status: 'active').total_size
52
+ ```
53
+
54
+ Check Helpscout's API documentation for [all supported filters](https://developer.helpscout.com/mailbox-api/endpoints/conversations/list/#url-parameters) and [attributes returned](https://developer.helpscout.com/mailbox-api/endpoints/conversations/list/#response).
55
+
56
+ All filter keys must be passed in the same format as described in the documentation, and all values must be strings or integers. Attribute keys must be symbols:
57
+
58
+ ```ruby
59
+ conversations = Cubscout::Conversation.all(page: 1,
60
+ assigned_to: 1234,
61
+ sortField: "customerName",
62
+ modifiedSince: (DateTime.now - 4).to_time.utc.iso8601,
63
+ tag: "red,blue")
64
+ ```
65
+
66
+ Get one conversation by id:
67
+
68
+ ```ruby
69
+ # find conversation by id:
70
+ conversation = Cubscout::Conversation.find(12345)
71
+
72
+ # Cubscout::Conversation.find returns one Cubscout::Conversation object, from
73
+ # which attributes can be read. attributes can be read as snake case or camel case.
74
+ puts conversation.mailbox_id
75
+ puts conversation.mailboxId
76
+
77
+ # By default, the threads are not embedded in the conversations payload. They can
78
+ # optionally be returned with the `embed` option:
79
+ Cubscout::Conversation.find(12345, embed: "threads")
80
+ ```
81
+
82
+ Check Helpscout's API documentation for all [attributes returned](https://developer.helpscout.com/mailbox-api/endpoints/conversations/get/#response)
83
+
84
+ Update a conversation:
85
+
86
+ ```ruby
87
+ conversation = Cubscout::Conversation.find(12345)
88
+ conversation.update(op: "replace", path: "/subject", value: "New conversation subject")
89
+
90
+ # or
91
+ Cubscout::Conversation.update(12345, op: "replace", path: "/subject", value: "New conversation subject")
92
+ ```
93
+
94
+ Multiple combinations of `:op`, `:path` and `:value` are permitted, check Helpscout's API documentation for [all the possibilities](https://developer.helpscout.com/mailbox-api/endpoints/conversations/update/#valid-paths-and-operations).
95
+
96
+ ### Threads
97
+
98
+ In Helpscout's lingo, threads are all the items following a conversation: notes, replies, assignment to users, etc.
99
+
100
+ Get the threads for a conversation:
101
+
102
+ ```ruby
103
+ # by conversation id, will make a request to Helpscout:
104
+ threads = Cubscout::Conversation.threads(conversation_id)
105
+
106
+ # from a conversation object, either by embedding threads on conversation request:
107
+ also_threads = Cubscout::Conversation.find(id, embed: 'threads').threads
108
+ # or making the threads request with explicit `fetch` option, will make a request
109
+ # to Helpscout:
110
+ another_way_to_get_threads = Cubscout::Conversation.find(id).threads(fetch: true)
111
+ ```
112
+
113
+ Threads can also be embedded to the List Conversations response payload:
114
+
115
+ ```ruby
116
+ # By default, the threads are not embedded in the conversations payload. They can
117
+ # optionally be returned with the `embed` option:
118
+ conversations = Cubscout::Conversation.all(page: 1, tag: 'red,blue', embed: 'threads')
119
+ threads = conversations.first.threads
120
+ ```
121
+
122
+ Check Helpscout's API documentation for all [attributes returned](https://developer.helpscout.com/mailbox-api/endpoints/conversations/threads/list/#response)
123
+
124
+ Create a note on a conversation:
125
+
126
+ ```ruby
127
+ # by conversation id:
128
+ Cubscout::Conversation.create_note(conversation_id, attributes)
129
+
130
+ # from a conversation object:
131
+ Cubscout::Conversation.find(id).create_note(attributes)
132
+
133
+ # of the attributes hash, :text is the only attribute required
134
+ Cubscout::Conversation.create_note(12345, text: "A new note by me")
135
+
136
+ # this endpoint doesn't return any body
137
+ ```
138
+
139
+ Check Helpscout's API documentation for [all supported attributes](https://developer.helpscout.com/mailbox-api/endpoints/conversations/threads/note/#request-fields)
140
+
141
+ ## Users
142
+
143
+ List of users:
144
+
145
+ ```ruby
146
+ # all possible users available
147
+ # WARNING: this will create multiple HTTP requests. You may want some filtering.
148
+ users = Cubscout::User.all
149
+
150
+ # users with filters
151
+ users = Cubscout::User.all(mailbox: 12345)
152
+
153
+ # Cubscout::User.all returns a Cubscout::List object. You can iterate over
154
+ # it's Cubscout::User items like this:
155
+ users.each { |user| puts user.first_name }
156
+
157
+ # or you can also get some metadata information. For example if you only care
158
+ # about the number of items, you can query the first page only and find out how
159
+ # many elements exist in total:
160
+ Cubscout::User.all(page: 1, mailbox: 12345).total_size
161
+ ```
162
+
163
+ Check Helpscout's API documentation for [all supported filters](https://developer.helpscout.com/mailbox-api/endpoints/users/list/#url-parameters) and [attributes returned](https://developer.helpscout.com/mailbox-api/endpoints/users/list/#response).
164
+
165
+ Get one user by id:
166
+
167
+ ```ruby
168
+ # find user by id:
169
+ user = Cubscout::User.find(12345)
170
+
171
+ # Cubscout::User.find returns one Cubscout::User object, from
172
+ # which attributes can be read. attributes can be read as snake case or camel case.
173
+ puts user.firstName
174
+ puts user.first_name
175
+ ```
176
+
177
+ Check Helpscout's API documentation for all [attributes returned](https://developer.helpscout.com/mailbox-api/endpoints/users/get/#response)
178
+
179
+ Get a conversation's assigned user:
180
+
181
+ ```ruby
182
+ # With limited attributes returned in conversation payload. Small gotcha here:
183
+ # - "first" attributes is renamed to "firstName"
184
+ # - "last" attributes is renamed to "lastName"
185
+ # to keep consistency with the attribute names returned from the /users endpoint
186
+ user = Cubscout::Conversation.find(conversation_id).assignee
187
+
188
+ # All attributes, will make a request to Helpscout:
189
+ user = Cubscout::Conversation.find(conversation_id).assignee(fetch: true)
190
+ ```
191
+
192
+ ## Contributing
193
+
194
+ Bug reports and pull requests are welcome on GitHub at https://github.com/GetSilverfin/cubscout. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
195
+
196
+ ## License
197
+
198
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
199
+
200
+ ## Code of Conduct
201
+
202
+ Everyone interacting in the Cubscout project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/GetSilverfin/cubscout/blob/master/CODE_OF_CONDUCT.md).
data/lib/cubscout.rb ADDED
@@ -0,0 +1,28 @@
1
+ require "cubscout/version"
2
+ require "cubscout/config"
3
+
4
+ require "cubscout/resource"
5
+ require "cubscout/request"
6
+ require "cubscout/response"
7
+
8
+ require "cubscout/scopes"
9
+ require "cubscout/list"
10
+ require "cubscout/object"
11
+ require "cubscout/conversation"
12
+ require "cubscout/user"
13
+ require "cubscout/thread_item"
14
+
15
+ module Cubscout
16
+ class Error < StandardError; end
17
+
18
+ class AuthenticationError < Error; end
19
+ class InternalError < Error; end
20
+ class InvalidFormatError < Error; end
21
+ class JsonParseError < Error; end
22
+ class MalformedRequestError < Error; end
23
+ class PermissionDeniedError < Error; end
24
+ class ResourceNotFoundError < Error; end
25
+ class RateLimitExceeded < Error; end
26
+
27
+ class ParameterMissing < Error; end
28
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "oauth2"
4
+
5
+ module Cubscout
6
+ # The Config class allows for API client configuration. Basic setup:
7
+ # require 'cubscout'
8
+ # Cubscout::Config.client_id = 'YOUR_APP_ID'
9
+ # Cubscout::Config.client_secret = 'YOUR_APP_SECRET'
10
+ class Config
11
+ DEFAULT_API_PREFIX = 'https://api.helpscout.net/v2'
12
+
13
+ class << self
14
+ attr_writer :api_prefix, :client_id, :client_secret
15
+
16
+ # @return [String] Base url of Helpscout's API V2.
17
+ def api_prefix
18
+ @api_prefix ||= DEFAULT_API_PREFIX
19
+ end
20
+
21
+ # Resets +client_id+, +client_secret+, and +oauth_client+ to null values,
22
+ # +api_prefix+ to DEFAULT_API_PREFIX
23
+ def reset!
24
+ @client_id = @client_secret = nil
25
+ @access_token = @oauth_client = nil
26
+ @api_prefix = DEFAULT_API_PREFIX
27
+ end
28
+
29
+ # @return [String] OAuth token used in every request header:
30
+ # +Authorization: Bearer #{Cubscout::Config.oauth_token}+
31
+ def oauth_token
32
+ access_token.token
33
+ end
34
+
35
+ private
36
+
37
+ def access_token
38
+ if @access_token && @access_token.expires_at > Time.now.to_i + 30
39
+ return @access_token
40
+ end
41
+
42
+ @access_token = oauth_client.client_credentials.get_token
43
+ end
44
+
45
+ def oauth_client
46
+ @oauth_client ||= begin
47
+ unless @client_id && @client_secret
48
+ raise ParameterMissing, <<~TEXT
49
+ You need to provide a client_id and client secret that you can get from helpscout (In Your profile -> my Apps)
50
+
51
+ Cubscout::Config.client_id = 'your-app-id-here'
52
+ Cubscout::Config.client_secret = 'your-app-secret-here'
53
+
54
+ TEXT
55
+ end
56
+
57
+ OAuth2::Client.new(@client_id, @client_secret, site: URI.join(api_prefix, '/').to_s, token_url: "#{URI::parse(api_prefix).path}/oauth2/token")
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,114 @@
1
+ module Cubscout
2
+ # the Conversation class encapsulates a helpscout conversation.
3
+ class Conversation < Object
4
+ endpoint "conversations"
5
+
6
+ class << self
7
+ # Get the threads of a conversation. In Helpscout lingo, threads are all
8
+ # the items following a conversation: notes, replies, assignment to users, etc.
9
+ # @param id [Integer] the conversation ID
10
+ # @return [Array<Object>] thread items
11
+ def threads(id)
12
+ Cubscout.connection.get("#{path}/#{id}/threads").body.dig("_embedded", "threads").map { |item| ThreadItem.new(item) }
13
+ end
14
+
15
+ # Create a note to a conversation.
16
+ # @param id [Integer] the conversation ID
17
+ # @param text [String] the note's text
18
+ # @option attributes [Integer] :user (Resource Owner) ID of the user creating the note.
19
+ # @option attributes [Boolean] :imported (false) The imported field enables thread to be
20
+ # created for historical purposes (i.e. if moving from a different platform, you can import
21
+ # your history).
22
+ # When imported is set to true, no outgoing emails or notifications will be generated.
23
+ # @option attributes [String] :createdAt Optional creation date to be used
24
+ # when importing conversations and threads.
25
+ # It can only be used with imported field set to true
26
+ # @option attributes [Array<Hash>] :attachments Optional list of attachments to be attached to this thread
27
+ # * :fileName (String) Attachment’s file name
28
+ # * :mimeType (String) Attachment’s mime type
29
+ # * :data (String) Base64-encoded stream of data.
30
+ # @return [Boolean] success status
31
+ # @example
32
+ # Cubscout::Conversation.create_note(123, text: "This is a note")
33
+ # Cubscout::Conversation.create_note(123, text: "This is a note", attachments: [{fileName: "file.txt", mimeType: "plain/text", data: "ZmlsZQ=="}])
34
+ def create_note(id, text:, **attributes)
35
+ Cubscout.connection.post("#{path}/#{id}/notes", attributes.merge(text: text).to_json).body
36
+ end
37
+
38
+ # Update a conversation.
39
+ # @param id [Integer] the conversation ID
40
+ # @param op [String] Patch operation to be carried out, one of +move+, +remove+, +replace+
41
+ # @param path [String] Path of the value to be changed, one of:
42
+ # +/assignTo+, +/draft+, +/mailboxId+, +/primaryCustomer.id+, +/status+, +/subject+
43
+ # @option attributes [Varies] :value Value to be used in operation, refer to this documentation
44
+ # for valid types: https://developer.helpscout.com/mailbox-api/endpoints/conversations/update/#valid-paths-and-operations.
45
+ # In case of status update +(op: "replace", path: "/status")+, :value must be one of +active+, +closed+, +open+, +pending+, +spam+
46
+ def update(id, op:, path:, **attributes)
47
+ Cubscout.connection.patch("#{Conversation.path}/#{id}", attributes.merge(op: op, path: path).to_json).body
48
+ end
49
+ end
50
+
51
+ # Get the assignee of the conversation
52
+ # @param fetch [Boolean] Optional query to helpscout to fetch full user data.
53
+ # By default, use limited data provided in conversation payload
54
+ # @return [User, nil] User assigned to the conversation. Can be nil
55
+ def assignee(fetch: false)
56
+ return nil unless self.attributes.has_key?("assignee")
57
+ if fetch
58
+ User.find(self.attributes.dig("assignee", "id"))
59
+ else
60
+ user_attributes = self.attributes.fetch("assignee").merge(
61
+ "firstName" => self.attributes.dig("assignee", "first"),
62
+ "lastName" => self.attributes.dig("assignee", "last")
63
+ )
64
+ User.new(user_attributes)
65
+ end
66
+ end
67
+
68
+ # Get the threads of the conversation. In Helpscout lingo, threads are all
69
+ # the items following a conversation: notes, replies, assignment to users, etc.
70
+ # @param fetch [Boolean] Optional query to helpscout to fetch threads data.
71
+ # By default, use data provided in conversation payload. Note that the
72
+ # threads are only embedded to the conversation payload on demand, example:
73
+ # +Cubscout::Conversation.all(tag: 'blue,red', embed: 'threads')+
74
+ # +Cubscout::Conversation.find(1234567, embed: 'threads')+
75
+ # @return [Array<Object>] thread items
76
+ def threads(fetch: false)
77
+ if fetch
78
+ Conversation.threads(self.id)
79
+ else
80
+ self.attributes.dig("_embedded", "threads").map { |item| ThreadItem.new(item) }
81
+ end
82
+ end
83
+
84
+ # Create a note to a conversation.
85
+ # @option attributes [String] :text the note's text. Required.
86
+ # @option attributes [Integer] :user (Resource Owner) ID of the user creating the note.
87
+ # @option attributes [Boolean] :imported (false) The imported field enables thread to be
88
+ # created for historical purposes (i.e. if moving from a different platform, you can import
89
+ # your history).
90
+ # When imported is set to true, no outgoing emails or notifications will be generated.
91
+ # @option attributes [String] :createdAt Optional creation date to be used
92
+ # when importing conversations and threads.
93
+ # It can only be used with imported field set to true
94
+ # @option attributes [Array<Hash>] :attachments Optional list of attachments to be attached to this thread
95
+ # * :fileName (String) Attachment’s file name
96
+ # * :mimeType (String) Attachment’s mime type
97
+ # * :data (String) Base64-encoded stream of data.
98
+ # @return [Boolean] success status
99
+ def create_note(attributes)
100
+ Conversation.create_note(self.id, attributes)
101
+ end
102
+
103
+ # Update a conversation.
104
+ # @option attributes [String] :op Patch operation to be carried out, one of +move+, +remove+, +replace+. Required
105
+ # @option attributes [String] :path Path of the value to be changed, one of:
106
+ # +/assignTo+, +/draft+, +/mailboxId+, +/primaryCustomer.id+, +/status+, +/subject+. Required
107
+ # @option attributes [Varies] :value Value to be used in operation, refer to this documentation
108
+ # for valid types: https://developer.helpscout.com/mailbox-api/endpoints/conversations/update/#valid-paths-and-operations.
109
+ # In case of status update +(op: "replace", path: "/status")+, :value must be one of +active+, +closed+, +open+, +pending+, +spam+
110
+ def update(attributes)
111
+ Conversation.update(self.id, attributes)
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,54 @@
1
+ module Cubscout
2
+ # the List class is the base class for any collection of objects retrieved from the Helpscout API.
3
+ # it's an Enumerable that can iterate over each of it's items.
4
+ #
5
+ # Helpscout API V2 is paginated and will return at max 50 items for each collection
6
+ # endpoint. The List class allows to query the page status.
7
+ class List
8
+ include Enumerable
9
+
10
+ def initialize(raw_payload, collection_name, object_class)
11
+ @raw_payload = raw_payload
12
+ @collection_name = collection_name
13
+ @object_class = object_class
14
+ end
15
+
16
+ # current page number
17
+ def page
18
+ raw_payload.dig("page", "number")
19
+ end
20
+
21
+ # number of items in the current page. Should be the same as number of +items+, but sometimes it's not (assumption: it's a bug in helpscout)
22
+ def page_size
23
+ raw_payload.dig("page", "size")
24
+ end
25
+
26
+ # total number of pages available
27
+ def number_of_pages
28
+ raw_payload.dig("page", "totalPages")
29
+ end
30
+
31
+ # total number of items available
32
+ def total_size
33
+ raw_payload.dig("page", "totalElements")
34
+ end
35
+
36
+ # array of objects Object retrieved from the API's collection endpoint.
37
+ def items
38
+ Array(raw_payload.dig("_embedded", collection_name)).map { |item| object_class.new(item) }
39
+ end
40
+
41
+ # number of +items+
42
+ def size
43
+ items.size
44
+ end
45
+
46
+ def each(&block)
47
+ items.each(&block)
48
+ end
49
+
50
+ private
51
+
52
+ attr_reader :raw_payload, :collection_name, :object_class
53
+ end
54
+ end
@@ -0,0 +1,33 @@
1
+ module Cubscout
2
+ # the Object class is the base class for any object retrieved from the Helpscout API.
3
+ # it's attributes can be read either as they are returned (usually camel case)
4
+ # but also in snake case.
5
+ # @example
6
+ # obj = Cubscout::Object.new("firstName" => "Joren")
7
+ # puts obj.firstName # => "Joren"
8
+ # puts obj.first_name # => "Joren"
9
+ class Object
10
+ include Scopes
11
+
12
+ attr_reader :attributes
13
+
14
+ def initialize(attributes)
15
+ # Dirty deep_transform_keys to strings
16
+ @attributes = JSON.parse(attributes.to_json)
17
+ end
18
+
19
+ def method_missing(method_name, *args, &block)
20
+ key = camelize(method_name)
21
+ return super unless @attributes.key?(key)
22
+
23
+ @attributes[key]
24
+ end
25
+
26
+ private
27
+
28
+ def camelize(sym)
29
+ parts = sym.to_s.split('_')
30
+ parts[0] + parts[1..-1].map(&:capitalize).join
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cubscout
4
+ class Request < Faraday::Middleware
5
+ def call(env)
6
+ env.request_headers['Authorization'] = "Bearer #{Config.oauth_token}"
7
+ env.request_headers['Content-Type'] = 'application/json'
8
+ env.request_headers['Accept'] = 'application/json'
9
+
10
+ @app.call(env)
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+
5
+ module Cubscout
6
+ class << self
7
+ def connection
8
+ @connection ||= Faraday.new(url: Cubscout::Config.api_prefix) do |faraday|
9
+ faraday.use Cubscout::Request
10
+ faraday.use Cubscout::Response
11
+ faraday.adapter Faraday.default_adapter
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Cubscout
6
+ class Response < Faraday::Response::Middleware
7
+ def on_complete(env)
8
+ handle_response_status(env.status, env)
9
+ parse_json_reponse(env)
10
+ end
11
+
12
+ private
13
+
14
+ def handle_response_status(status, env)
15
+ case status
16
+ when 400
17
+ raise Cubscout::MalformedRequestError, env.body
18
+ when 401
19
+ raise Cubscout::AuthenticationError, env.body
20
+ when 403
21
+ raise Cubscout::PermissionDeniedError, env.body
22
+ when 404
23
+ raise Cubscout::ResourceNotFoundError, env.body
24
+ when 429
25
+ limit = env.response_headers["x-ratelimit-limit-minute"]
26
+ remaining = env.response_headers["x-ratelimit-remaining-minute"]
27
+ retry_after = env.response_headers["x-ratelimit-retry-after"]
28
+ raise Cubscout::RateLimitExceeded, {retry_after_minutes: retry_after, limit: limit, remaining: remaining}
29
+ when 500
30
+ raise Cubscout::InternalError, env.body
31
+ end
32
+ end
33
+
34
+ def parse_json_reponse(env)
35
+ return true if [201, 204].include?(env.status)
36
+
37
+ begin
38
+ parsed_body = JSON.parse(env.body)
39
+ env[:raw_body] = env.body
40
+ rescue JSON::ParserError
41
+ raise Cubscout::JsonParseError, env.body
42
+ end
43
+
44
+ env.body = parsed_body
45
+ end
46
+
47
+ end
48
+ end
@@ -0,0 +1,78 @@
1
+ module Cubscout
2
+ # The Scopes module allows for Active Record kind of queries like .all and .find
3
+ # this module is included in Object, meaning that every subclass of Object can
4
+ # call the Scopes ClassMethods.
5
+ # @example
6
+ # class Foo < Object; end
7
+ # Foo.find(id)
8
+ # Foo.all(page: 1)
9
+ module Scopes
10
+ module ClassMethods
11
+ # DSL: necessary to provide the endpoint of the resources to query.
12
+ # @param path [String] path to the endpoint, without leading slash
13
+ # @example
14
+ # class Conversation
15
+ # include Cubscout::Scopes
16
+ # endpoint "conversations"
17
+ # end
18
+ def endpoint(path)
19
+ @path = path
20
+ end
21
+
22
+ # Read the path entered through the DSL
23
+ def path
24
+ @path
25
+ end
26
+
27
+ # used with a collection endpoint, get all objects of a certain kind
28
+ # @param options [Hash] Optional query params described in Helspcout API documentation
29
+ # @return [Cubscout::List] Returns a List collection where items are instances of the class where the method is called.
30
+ # @example
31
+ # foos = Foo.all(tag: "bar")
32
+ # foos.total_size # 335 with this filter
33
+ # foos.each { |foo_element| puts "ID is #{foo_element.id}" }
34
+ def all(options = {})
35
+ raise Error, "`#{self}.all` method is not available" unless path
36
+
37
+ raw_first_or_requested_page = Cubscout.connection.get(path, page: options[:page] || 1, **options).body
38
+ first_or_requested_page = List.new(raw_first_or_requested_page, path, self)
39
+
40
+ if options[:page]
41
+ first_or_requested_page
42
+ else
43
+ last_page_number = first_or_requested_page.number_of_pages
44
+
45
+ raw_other_pages_items = (2..last_page_number).to_a.map do |page|
46
+ Array(Cubscout.connection.get(path, page: page, **options).body.dig("_embedded", path))
47
+ end
48
+
49
+ raw_all_pages = {
50
+ "_embedded" => { path => (Array(raw_first_or_requested_page.dig("_embedded", path)) + raw_other_pages_items).flatten },
51
+ "page" => {
52
+ "number" => first_or_requested_page.page,
53
+ "size" => first_or_requested_page.total_size,
54
+ "totalPages" => first_or_requested_page.number_of_pages,
55
+ "totalElements" => first_or_requested_page.total_size
56
+ }
57
+ }
58
+ List.new(raw_all_pages, path, self)
59
+ end
60
+ end
61
+
62
+ # used with an instance endpoint, get one instance of an Object
63
+ # @param id [Integer] ID of the object to get
64
+ # @param options [Hash] Optional query params described in Helspcout API documentation
65
+ # @return [Object] Returns an instance of the class where the method is called.
66
+ # Example: +Foo.find(123) # => returns an instance of Foo+
67
+ def find(id, options = {})
68
+ raise Error, "`#{self}.find` method is not available" unless path
69
+
70
+ self.new(Cubscout.connection.get("#{path}/#{id}", options).body)
71
+ end
72
+ end
73
+
74
+ def self.included(mod)
75
+ mod.extend ClassMethods
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,4 @@
1
+ module Cubscout
2
+ class ThreadItem < Object
3
+ end
4
+ end
@@ -0,0 +1,5 @@
1
+ module Cubscout
2
+ class User < Object
3
+ endpoint "users"
4
+ end
5
+ end
@@ -0,0 +1,3 @@
1
+ module Cubscout
2
+ VERSION = "0.2.0"
3
+ end
metadata ADDED
@@ -0,0 +1,162 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cubscout
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Joren De Groof
8
+ - Fabien Loup
9
+ autorequire:
10
+ bindir: exe
11
+ cert_chain: []
12
+ date: 2020-05-14 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: oauth2
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - "~>"
19
+ - !ruby/object:Gem::Version
20
+ version: '1.4'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - "~>"
26
+ - !ruby/object:Gem::Version
27
+ version: '1.4'
28
+ - !ruby/object:Gem::Dependency
29
+ name: faraday
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: '0'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: '0'
42
+ - !ruby/object:Gem::Dependency
43
+ name: bundler
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '2.0'
49
+ type: :development
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - "~>"
54
+ - !ruby/object:Gem::Version
55
+ version: '2.0'
56
+ - !ruby/object:Gem::Dependency
57
+ name: rake
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - "~>"
61
+ - !ruby/object:Gem::Version
62
+ version: '13.0'
63
+ type: :development
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - "~>"
68
+ - !ruby/object:Gem::Version
69
+ version: '13.0'
70
+ - !ruby/object:Gem::Dependency
71
+ name: rspec
72
+ requirement: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - "~>"
75
+ - !ruby/object:Gem::Version
76
+ version: '3.0'
77
+ type: :development
78
+ prerelease: false
79
+ version_requirements: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - "~>"
82
+ - !ruby/object:Gem::Version
83
+ version: '3.0'
84
+ - !ruby/object:Gem::Dependency
85
+ name: pry
86
+ requirement: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - "~>"
89
+ - !ruby/object:Gem::Version
90
+ version: '0.12'
91
+ type: :development
92
+ prerelease: false
93
+ version_requirements: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - "~>"
96
+ - !ruby/object:Gem::Version
97
+ version: '0.12'
98
+ - !ruby/object:Gem::Dependency
99
+ name: webmock
100
+ requirement: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - "~>"
103
+ - !ruby/object:Gem::Version
104
+ version: '3.5'
105
+ type: :development
106
+ prerelease: false
107
+ version_requirements: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - "~>"
110
+ - !ruby/object:Gem::Version
111
+ version: '3.5'
112
+ description: Help Scout api v2 wrapper
113
+ email:
114
+ - joren@silverfin.com
115
+ - fabien@silverfin.com
116
+ executables: []
117
+ extensions: []
118
+ extra_rdoc_files: []
119
+ files:
120
+ - CHANGELOG.md
121
+ - CODE_OF_CONDUCT.md
122
+ - LICENSE.txt
123
+ - README.md
124
+ - lib/cubscout.rb
125
+ - lib/cubscout/config.rb
126
+ - lib/cubscout/conversation.rb
127
+ - lib/cubscout/list.rb
128
+ - lib/cubscout/object.rb
129
+ - lib/cubscout/request.rb
130
+ - lib/cubscout/resource.rb
131
+ - lib/cubscout/response.rb
132
+ - lib/cubscout/scopes.rb
133
+ - lib/cubscout/thread_item.rb
134
+ - lib/cubscout/user.rb
135
+ - lib/cubscout/version.rb
136
+ homepage: https://developer.helpscout.com/mailbox-api/
137
+ licenses:
138
+ - MIT
139
+ metadata:
140
+ homepage_uri: https://developer.helpscout.com/mailbox-api/
141
+ source_code_uri: https://github.com/GetSilverfin/cubscout
142
+ changelog_uri: https://github.com/GetSilverfin/cubscout/blob/master/CHANGELOG.md
143
+ post_install_message:
144
+ rdoc_options: []
145
+ require_paths:
146
+ - lib
147
+ required_ruby_version: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - ">="
150
+ - !ruby/object:Gem::Version
151
+ version: '0'
152
+ required_rubygems_version: !ruby/object:Gem::Requirement
153
+ requirements:
154
+ - - ">="
155
+ - !ruby/object:Gem::Version
156
+ version: '0'
157
+ requirements: []
158
+ rubygems_version: 3.0.3
159
+ signing_key:
160
+ specification_version: 4
161
+ summary: Help Scout api v2 wrapper
162
+ test_files: []