zammad_api 1.3.1 → 2.0.0.alpha1
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 +4 -4
- data/.yardopts +11 -0
- data/CHANGELOG.md +235 -0
- data/LICENSE.AGPL.txt +661 -0
- data/LICENSE.MIT.txt +7 -0
- data/LICENSE.md +6 -0
- data/README.md +794 -0
- data/UPGRADING.md +158 -0
- data/lib/zammad_api/attribute_access.rb +121 -0
- data/lib/zammad_api/client.rb +243 -43
- data/lib/zammad_api/collection.rb +233 -0
- data/lib/zammad_api/config.rb +239 -0
- data/lib/zammad_api/deep_copy.rb +43 -0
- data/lib/zammad_api/errors.rb +124 -0
- data/lib/zammad_api/resource_proxy.rb +195 -0
- data/lib/zammad_api/resources/base.rb +196 -99
- data/lib/zammad_api/resources/group.rb +12 -2
- data/lib/zammad_api/resources/organization.rb +12 -2
- data/lib/zammad_api/resources/ticket.rb +43 -19
- data/lib/zammad_api/resources/ticket_article.rb +14 -7
- data/lib/zammad_api/resources/ticket_article_attachment.rb +29 -14
- data/lib/zammad_api/resources/ticket_priority.rb +10 -2
- data/lib/zammad_api/resources/ticket_state.rb +9 -2
- data/lib/zammad_api/resources/user.rb +16 -2
- data/lib/zammad_api/resources.rb +13 -13
- data/lib/zammad_api/response.rb +52 -0
- data/lib/zammad_api/transport.rb +212 -40
- data/lib/zammad_api/version.rb +4 -1
- data/lib/zammad_api.rb +16 -2
- data/sig/zammad_api/attribute_access.rbs +31 -0
- data/sig/zammad_api/client.rbs +42 -0
- data/sig/zammad_api/collection.rbs +46 -0
- data/sig/zammad_api/config.rbs +69 -0
- data/sig/zammad_api/deep_copy.rbs +7 -0
- data/sig/zammad_api/errors.rbs +61 -0
- data/sig/zammad_api/resource_proxy.rbs +41 -0
- data/sig/zammad_api/resources/base.rbs +66 -0
- data/sig/zammad_api/resources/resources.rbs +201 -0
- data/sig/zammad_api/response.rbs +16 -0
- data/sig/zammad_api/transport.rbs +47 -0
- data/sig/zammad_api.rbs +3 -0
- metadata +70 -15
- data/lib/zammad_api/dispatcher.rb +0 -12
- data/lib/zammad_api/json_helper.rb +0 -11
- data/lib/zammad_api/list_all.rb +0 -11
- data/lib/zammad_api/list_base.rb +0 -83
- data/lib/zammad_api/list_search.rb +0 -11
- data/lib/zammad_api/log.rb +0 -18
data/UPGRADING.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Upgrading from 1.x
|
|
2
|
+
|
|
3
|
+
Version 2.0 fixes long-standing behaviour that could not change without breaking
|
|
4
|
+
compatibility. Most calling code needs one rename: the resource names are plural, so
|
|
5
|
+
`client.ticket` is `client.tickets`. Almost everything else that needs an edit raises at
|
|
6
|
+
the call site. Start with the few changes that do not.
|
|
7
|
+
|
|
8
|
+
If this is not the time to move, [1.x stays available](#staying-on-1x).
|
|
9
|
+
|
|
10
|
+
## Silent changes
|
|
11
|
+
|
|
12
|
+
- **`record.attributes = {...}`** was a writer in 1.x. It is now an ordinary attribute
|
|
13
|
+
assignment, so it stages a change named `attributes` and `save` sends it to Zammad:
|
|
14
|
+
|
|
15
|
+
```ruby
|
|
16
|
+
group.attributes = {name: 'Support'}
|
|
17
|
+
group.changes # => {attributes: [nil, {name: "Support"}]}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Use `assign_attributes(name: 'Support')`, or `update` to assign and save.
|
|
21
|
+
|
|
22
|
+
- **`record.save`** returns `false` when Zammad rejects the attributes, where 1.x raised.
|
|
23
|
+
Code that relied on the exception carries on after a rejected save:
|
|
24
|
+
|
|
25
|
+
```ruby
|
|
26
|
+
ticket.state = 'closed'
|
|
27
|
+
ticket.save # false on a 422 in 2.0; nothing raises, and the ticket is still open
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Check what `save` returns and read `record.error`, or call `save!`, which raises
|
|
31
|
+
`ZammadAPI::ValidationError` as `save` used to. `update` and `update!` are the same pair.
|
|
32
|
+
|
|
33
|
+
- **`collection.each`** reads every page, where 1.x stopped after the first (100 records
|
|
34
|
+
for `all`, 10 for `search`). A loop that used to touch the first 100 tickets now touches
|
|
35
|
+
all of them. To keep the old limit, use `first(n)` or `page(1, per_page: n)`.
|
|
36
|
+
|
|
37
|
+
- **A Hash inside an Array attribute** has Symbol keys, where 1.x left it the String keys
|
|
38
|
+
Zammad sent: only a Hash directly under another Hash was symbolized. Read by String key,
|
|
39
|
+
it answers `nil` and nothing raises:
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
article.attributes[:attachments].first['filename'] # the name in 1.x, nil in 2.0
|
|
43
|
+
article.attributes[:attachments].first[:filename] # the name in 2.0
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Keys are Symbols at every depth now, so one spelling reads a value wherever it sits.
|
|
47
|
+
|
|
48
|
+
- **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer
|
|
49
|
+
matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`,
|
|
50
|
+
`ZammadAPI::TimeoutError`, or `ZammadAPI::TransportError` for both.
|
|
51
|
+
|
|
52
|
+
## The client
|
|
53
|
+
|
|
54
|
+
| 1.x | 2.0 | Why |
|
|
55
|
+
| -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- |
|
|
56
|
+
| `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted |
|
|
57
|
+
| an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word |
|
|
58
|
+
| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object. Anything that responds to `debug` works |
|
|
59
|
+
| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is every record of its kind. The singular names raise `NoMethodError` |
|
|
60
|
+
| `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads |
|
|
61
|
+
| `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised |
|
|
62
|
+
| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list. [Raw requests][raw-requests] reach whatever is not a resource |
|
|
63
|
+
|
|
64
|
+
## Collections
|
|
65
|
+
|
|
66
|
+
| 1.x | 2.0 | Why |
|
|
67
|
+
| ---------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------- |
|
|
68
|
+
| `collection.page(1, 3) { \|r\| ... }` | `collection.page(1, per_page: 3).each { ... }` | `page` now returns a collection instead of mutating and yielding |
|
|
69
|
+
| `collection.page_next` / `page_prev` | `collection.page(n)` or `in_batches` | Removed; they mutated shared state |
|
|
70
|
+
| `collection[3]` | `collection.page(4, per_page: 1).first` | An index that costs a request, and that ignored `page`, was a trap |
|
|
71
|
+
| `collection.find(1)` | `client.x.find(1)`, or `collection.detect { ... }` | `find` on a collection is `Enumerable#find`; an id raises `ArgumentError` |
|
|
72
|
+
| `client.x.all(per_page: 50)` | `client.x.all.page(1, per_page: 50)`, `find_each(batch_size: 50)` | `all` accepted the argument and discarded it; page size belongs to the call that reads |
|
|
73
|
+
| `client.x.all(active: true)` | `client.x.search(...)`, or `client.x.all.detect { ... }` | Zammad's index endpoints do not filter, so 1.x ignored the argument |
|
|
74
|
+
| `client.x.search(query: 'zammad')` | `client.x.search('zammad')` | The search term is the argument, not a keyword |
|
|
75
|
+
| `client.x.search(query: 'z', page: 2, per_page: 50)` | `client.x.search('z').page(2, per_page: 50)` | Search did honour those two; paging is the collection's job now |
|
|
76
|
+
|
|
77
|
+
## Records
|
|
78
|
+
|
|
79
|
+
| 1.x | 2.0 | Why |
|
|
80
|
+
| ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- |
|
|
81
|
+
| `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it |
|
|
82
|
+
| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported. It raises `ZammadAPI::Error` now |
|
|
83
|
+
| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError` |
|
|
84
|
+
| `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` |
|
|
85
|
+
| `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo used to read as `nil` |
|
|
86
|
+
| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | Renamed; `ticket.article(...)` raises `NoMethodError` |
|
|
87
|
+
|
|
88
|
+
## Errors
|
|
89
|
+
|
|
90
|
+
| 1.x | 2.0 | Why |
|
|
91
|
+
| ------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------- |
|
|
92
|
+
| `ZammadAPI::Error < RuntimeError` | `ZammadAPI::Error < StandardError` | `RuntimeError` is for `raise "string"` |
|
|
93
|
+
| `ZammadAPI::ResourceNotFoundError` | `ZammadAPI::UnknownResourceError`, from `client.resource(:name)`; `NoMethodError` from `client.name` | Renamed so it is not confused with a 404, now `NotFoundError`. A reader the client does not have is a missing method like any other |
|
|
94
|
+
| `ClientError` for every 4xx | `AuthenticationError`, `NotFoundError`, `ValidationError`, … | All still `ClientError`, so existing rescues keep working |
|
|
95
|
+
| `error.response` was a Faraday object | `ZammadAPI::Response` with `status`/`body`/`headers` | Faraday is no longer part of the public surface |
|
|
96
|
+
| `error.body` was a raw JSON string | decoded Hash, or the raw body for non-JSON | Saves every caller from parsing it again |
|
|
97
|
+
| `"Can't find object (ZammadAPI::Resources::Ticket): …"` | `"GET api/v1/tickets/1 failed: …"` | A message names the request that failed, so match on the error class or `status`, not on its text |
|
|
98
|
+
| `error.operation`, `error.resource_class` | removed; read the request from `error.message` | They existed to word the message |
|
|
99
|
+
|
|
100
|
+
## Removed constants, and the Ruby version
|
|
101
|
+
|
|
102
|
+
| 1.x | 2.0 | Why |
|
|
103
|
+
| ------------------------------------------------ | -------------------------- | ------------------------------------------------------------ |
|
|
104
|
+
| `ZammadAPI::ListBase` / `ListAll` / `ListSearch` | `ZammadAPI::Collection` | One class instead of three |
|
|
105
|
+
| `ZammadAPI::Dispatcher` | `ZammadAPI::ResourceProxy` | Renamed; `client.<resource>` hands you one |
|
|
106
|
+
| `ZammadAPI::Log`, `ZammadAPI::JsonHelper` | removed | Pass any `Logger` as `logger:`; decoding moved into the transport |
|
|
107
|
+
| Ruby >= 3.0 | Ruby >= 3.4 | 3.0 through 3.3 are end-of-life or nearly so |
|
|
108
|
+
|
|
109
|
+
## New defaults
|
|
110
|
+
|
|
111
|
+
A collection fetches as many records per request as the endpoint serves: 1000 on most
|
|
112
|
+
index endpoints (1.x: 100), 100 on tickets (unchanged) and 200 on a search (1.x: 10).
|
|
113
|
+
`page(n)` without `per_page:` is a page of that size, so pin it with
|
|
114
|
+
`page(n, per_page: 100)` if a persisted page number has to keep meaning what it did.
|
|
115
|
+
|
|
116
|
+
A request times out after 60 seconds (10 to connect), where 1.x waited as long as the
|
|
117
|
+
server took. A call that used to hang raises `ZammadAPI::TimeoutError`, or
|
|
118
|
+
`ZammadAPI::ConnectionError` when the connection is not opened in time. A `GET` is retried
|
|
119
|
+
twice with exponential backoff on connection failures, timeouts and the transient
|
|
120
|
+
statuses; a `POST`, `PUT` or `DELETE` is never retried. Both are options: see
|
|
121
|
+
[Timeouts and retries][timeouts-and-retries]. The `User-Agent` is
|
|
122
|
+
`zammad_api-ruby/<version>` rather than `Zammad API Ruby`.
|
|
123
|
+
|
|
124
|
+
## What did not change
|
|
125
|
+
|
|
126
|
+
`find`, `all`, `create` and `new` on a resource, `record.destroy`, attribute readers and
|
|
127
|
+
writers, `ticket.articles` and `attachment.download`.
|
|
128
|
+
|
|
129
|
+
`record.save`, `record.changes` and `record.attributes` still exist and still mean what
|
|
130
|
+
they meant; the tables above only change how they behave at the edges.
|
|
131
|
+
|
|
132
|
+
## Staying on 1.x
|
|
133
|
+
|
|
134
|
+
1.x stays available for a project that is not ready for 2.0, or that runs on a Ruby older
|
|
135
|
+
than 3.4: 1.x needs Ruby 3.0 or later.
|
|
136
|
+
|
|
137
|
+
Its code lives on the
|
|
138
|
+
[`1-stable`](https://github.com/zammad/zammad-api-client-ruby/tree/1-stable) branch, and
|
|
139
|
+
the [README there](https://github.com/zammad/zammad-api-client-ruby/blob/1-stable/README.md)
|
|
140
|
+
documents the 1.x API. To install it, keep the version below 2:
|
|
141
|
+
|
|
142
|
+
```ruby
|
|
143
|
+
gem 'zammad_api', '~> 1.4'
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Or:
|
|
147
|
+
|
|
148
|
+
```sh
|
|
149
|
+
gem install zammad_api -v '~> 1.4'
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
1.x is in maintenance mode, and will stay there for the foreseeable future: it still gets
|
|
153
|
+
fixes, while new features go into 2.0 only. Report a 1.x problem in the same
|
|
154
|
+
[issue tracker](https://github.com/zammad/zammad-api-client-ruby/issues), naming the
|
|
155
|
+
version, and open a pull request for it against `1-stable`.
|
|
156
|
+
|
|
157
|
+
[raw-requests]: https://github.com/zammad/zammad-api-client-ruby/blob/master/README.md#raw-requests
|
|
158
|
+
[timeouts-and-retries]: https://github.com/zammad/zammad-api-client-ruby/blob/master/README.md#timeouts-and-retries
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
|
|
5
|
+
module ZammadAPI
|
|
6
|
+
# Read access to a Zammad record's attributes.
|
|
7
|
+
#
|
|
8
|
+
# Zammad objects can carry administrator-defined custom attributes, so the
|
|
9
|
+
# set of readable attributes is not known ahead of time and is resolved
|
|
10
|
+
# through +method_missing+. A reader for an attribute the record does not
|
|
11
|
+
# carry raises +NoMethodError+; {#[]}, {#fetch} with a default, and {#key?}
|
|
12
|
+
# are the readers for an attribute that may be absent.
|
|
13
|
+
module AttributeAccess
|
|
14
|
+
# What a writer for an attribute is named: a plain identifier and an `=`,
|
|
15
|
+
# so that operators such as +<=+ are not taken for one.
|
|
16
|
+
ATTRIBUTE_WRITER = /\A[a-zA-Z_]\w*=\z/
|
|
17
|
+
private_constant :ATTRIBUTE_WRITER
|
|
18
|
+
|
|
19
|
+
# All known attributes, deeply frozen. {#to_h} returns a copy that is safe
|
|
20
|
+
# to modify; an attribute writer is the way to stage a change.
|
|
21
|
+
#
|
|
22
|
+
# @return [Hash{Symbol => Object}]
|
|
23
|
+
attr_reader :attributes
|
|
24
|
+
|
|
25
|
+
# @param key [Symbol, String]
|
|
26
|
+
# @return [Object, nil]
|
|
27
|
+
def [](key) = attributes[key.to_sym]
|
|
28
|
+
|
|
29
|
+
# Stages a change to an attribute, like the attribute writer does.
|
|
30
|
+
#
|
|
31
|
+
# @param key [Symbol, String]
|
|
32
|
+
# @param value [Object]
|
|
33
|
+
# @return [Object] the staged value
|
|
34
|
+
def []=(key, value)
|
|
35
|
+
write_attribute(key.to_sym, value)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Reads an attribute the way +Hash#fetch+ does.
|
|
39
|
+
#
|
|
40
|
+
# @param key [Symbol, String]
|
|
41
|
+
# @return [Object]
|
|
42
|
+
# @raise [KeyError] when the record does not carry the attribute and
|
|
43
|
+
# neither a default nor a block is given
|
|
44
|
+
def fetch(key, *default, &block) = attributes.fetch(key.to_sym, *default, &block) # steep:ignore UnresolvedOverloading
|
|
45
|
+
|
|
46
|
+
# @return [Boolean]
|
|
47
|
+
def key?(key) = attributes.key?(key.to_sym)
|
|
48
|
+
|
|
49
|
+
# @return [Hash{Symbol => Object}] a deep copy of all attributes, safe to
|
|
50
|
+
# modify
|
|
51
|
+
def to_h = DeepCopy.writable_copy(attributes)
|
|
52
|
+
|
|
53
|
+
# @return [Integer, nil]
|
|
54
|
+
def id = attributes[:id]
|
|
55
|
+
|
|
56
|
+
# Enables Ruby pattern matching against a record's attributes.
|
|
57
|
+
#
|
|
58
|
+
# @example
|
|
59
|
+
# case client.tickets.find(1)
|
|
60
|
+
# in {state: 'closed'}
|
|
61
|
+
# nil
|
|
62
|
+
# in {state: String => state, priority: '3 high'}
|
|
63
|
+
# escalate(state)
|
|
64
|
+
# end
|
|
65
|
+
#
|
|
66
|
+
# @param keys [Array<Symbol>, nil] the keys the pattern asks for
|
|
67
|
+
# @return [Hash{Symbol => Object}]
|
|
68
|
+
def deconstruct_keys(keys) = keys.nil? ? attributes : attributes.slice(*keys)
|
|
69
|
+
|
|
70
|
+
# Whether +other+ is the same Zammad record: the same class, carrying the
|
|
71
|
+
# same id. A record with no id is equal only to itself.
|
|
72
|
+
#
|
|
73
|
+
# @param other [Object]
|
|
74
|
+
# @return [Boolean]
|
|
75
|
+
def ==(other)
|
|
76
|
+
return true if equal?(other)
|
|
77
|
+
|
|
78
|
+
other.instance_of?(self.class) && !id.nil? && other.id == id
|
|
79
|
+
end
|
|
80
|
+
alias eql? ==
|
|
81
|
+
|
|
82
|
+
# Consistent with {#==}, so that records can be deduplicated with +uniq+,
|
|
83
|
+
# collected in a +Set+ and used as Hash keys.
|
|
84
|
+
#
|
|
85
|
+
# @return [Integer]
|
|
86
|
+
def hash
|
|
87
|
+
id.nil? ? super : [self.class, id].hash
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# @return [Hash{Symbol => Object}] the attributes, for a JSON encoder
|
|
91
|
+
def as_json(*) = to_h
|
|
92
|
+
|
|
93
|
+
# @return [String] the attributes as a JSON object
|
|
94
|
+
def to_json(*args) = to_h.to_json(*args) # steep:ignore UnexpectedPositionalArgument
|
|
95
|
+
|
|
96
|
+
def method_missing(name, *args)
|
|
97
|
+
identifier = name.to_s
|
|
98
|
+
return write_attribute(identifier.delete_suffix('=').to_sym, args.first) if ATTRIBUTE_WRITER.match?(identifier) && args.size == 1
|
|
99
|
+
return attributes[name] if args.empty? && attributes.key?(name)
|
|
100
|
+
|
|
101
|
+
super
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def respond_to_missing?(name, include_private = false)
|
|
105
|
+
identifier = name.to_s
|
|
106
|
+
return writable_attributes? if ATTRIBUTE_WRITER.match?(identifier)
|
|
107
|
+
|
|
108
|
+
attributes.key?(name) || super
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
private
|
|
112
|
+
|
|
113
|
+
def writable_attributes? = false
|
|
114
|
+
|
|
115
|
+
def write_attribute(key, _value)
|
|
116
|
+
raise NoMethodError, "#{self.class.name} attributes are read-only (tried to set #{key})"
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def frozen_attributes(value) = DeepCopy.frozen_copy(value)
|
|
120
|
+
end
|
|
121
|
+
end
|
data/lib/zammad_api/client.rb
CHANGED
|
@@ -1,65 +1,265 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
require 'zammad_api/log'
|
|
4
|
-
require 'zammad_api/transport'
|
|
5
|
-
require 'zammad_api/dispatcher'
|
|
6
|
-
require 'zammad_api/resources'
|
|
1
|
+
# frozen_string_literal: true
|
|
7
2
|
|
|
8
3
|
module ZammadAPI
|
|
4
|
+
# The entry point of this gem.
|
|
5
|
+
#
|
|
6
|
+
# @example Token authentication
|
|
7
|
+
# client = ZammadAPI::Client.new(
|
|
8
|
+
# url: 'https://zammad.example.com/',
|
|
9
|
+
# http_token: 'your-access-token'
|
|
10
|
+
# )
|
|
11
|
+
# client.tickets.find(1).title
|
|
12
|
+
#
|
|
13
|
+
# @example Basic authentication with a custom timeout and logger
|
|
14
|
+
# client = ZammadAPI::Client.new(
|
|
15
|
+
# url: 'https://zammad.example.com/',
|
|
16
|
+
# user: 'user@example.com',
|
|
17
|
+
# password: 'secret',
|
|
18
|
+
# timeout: 10,
|
|
19
|
+
# logger: Logger.new($stdout)
|
|
20
|
+
# )
|
|
9
21
|
class Client
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
22
|
+
# Maps the reader methods of this client to their resource classes.
|
|
23
|
+
RESOURCES = {
|
|
24
|
+
groups: Resources::Group,
|
|
25
|
+
organizations: Resources::Organization,
|
|
26
|
+
tickets: Resources::Ticket,
|
|
27
|
+
ticket_articles: Resources::TicketArticle,
|
|
28
|
+
ticket_priorities: Resources::TicketPriority,
|
|
29
|
+
ticket_states: Resources::TicketState,
|
|
30
|
+
users: Resources::User
|
|
31
|
+
}.freeze
|
|
13
32
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
33
|
+
# @!method groups
|
|
34
|
+
# @return [ResourceProxy] proxy for {Resources::Group}
|
|
35
|
+
# @!method organizations
|
|
36
|
+
# @return [ResourceProxy] proxy for {Resources::Organization}
|
|
37
|
+
# @!method tickets
|
|
38
|
+
# @return [ResourceProxy] proxy for {Resources::Ticket}
|
|
39
|
+
# @!method ticket_articles
|
|
40
|
+
# @return [ResourceProxy] proxy for {Resources::TicketArticle}
|
|
41
|
+
# @!method ticket_priorities
|
|
42
|
+
# @return [ResourceProxy] proxy for {Resources::TicketPriority}
|
|
43
|
+
# @!method ticket_states
|
|
44
|
+
# @return [ResourceProxy] proxy for {Resources::TicketState}
|
|
45
|
+
# @!method users
|
|
46
|
+
# @return [ResourceProxy] proxy for {Resources::User}
|
|
47
|
+
RESOURCES.each do |name, resource_class|
|
|
48
|
+
define_method(name) { @resources.fetch(resource_class) }
|
|
19
49
|
end
|
|
20
50
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
51
|
+
# Environment variables {.from_env} reads, mapped to the options they set.
|
|
52
|
+
ENV_OPTIONS = {
|
|
53
|
+
'ZAMMAD_URL' => :url,
|
|
54
|
+
'ZAMMAD_TOKEN' => :http_token,
|
|
55
|
+
'ZAMMAD_OAUTH2_TOKEN' => :oauth2_token,
|
|
56
|
+
'ZAMMAD_USER' => :user,
|
|
57
|
+
'ZAMMAD_PASSWORD' => :password
|
|
58
|
+
}.freeze
|
|
59
|
+
|
|
60
|
+
# Builds a client from the environment.
|
|
61
|
+
#
|
|
62
|
+
# Reads {ENV_OPTIONS}; a variable that is empty or blank counts as unset.
|
|
63
|
+
# Anything passed in wins over the environment, and credentials passed in
|
|
64
|
+
# replace the ones the environment holds.
|
|
65
|
+
#
|
|
66
|
+
# @example
|
|
67
|
+
# ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=secret ruby report.rb
|
|
68
|
+
#
|
|
69
|
+
# client = ZammadAPI::Client.from_env
|
|
70
|
+
# client = ZammadAPI::Client.from_env(timeout: 300) # for one bulk job
|
|
71
|
+
#
|
|
72
|
+
# @param overrides [Hash] any option accepted by {Config}
|
|
73
|
+
# @return [Client]
|
|
74
|
+
# @raise [ConfigurationError] when neither the environment nor +overrides+
|
|
75
|
+
# supply a URL and credentials
|
|
76
|
+
def self.from_env(**overrides)
|
|
77
|
+
from_environment = ENV_OPTIONS.filter_map do |name, option|
|
|
78
|
+
value = ENV.fetch(name, nil)
|
|
79
|
+
[option, value] if !value.to_s.strip.empty?
|
|
25
80
|
end
|
|
81
|
+
options = Config.merge_options(from_environment.to_h, overrides)
|
|
82
|
+
|
|
83
|
+
raise ConfigurationError, "missing url: set ZAMMAD_URL or pass url: to #{name}.from_env" if options[:url].to_s.empty?
|
|
84
|
+
|
|
85
|
+
new(**options)
|
|
26
86
|
end
|
|
27
87
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
88
|
+
# @param options [Hash] see {Config} for every supported option
|
|
89
|
+
# @option options [String] :url base URL of the Zammad instance
|
|
90
|
+
# @option options [String] :http_token access token
|
|
91
|
+
# @option options [String] :oauth2_token OAuth2 token
|
|
92
|
+
# @option options [String] :user login for basic authentication
|
|
93
|
+
# @option options [String] :password password for basic authentication
|
|
94
|
+
# @param transport [Transport, nil] the transport of the client this one
|
|
95
|
+
# is derived from, in place of options. For {#with} and {#on_behalf_of}.
|
|
96
|
+
# @raise [ConfigurationError] when the options are incomplete or invalid,
|
|
97
|
+
# or name more than one way to authenticate
|
|
98
|
+
def initialize(transport: nil, **options)
|
|
99
|
+
@transport = transport || Transport.new(Config.new(**options))
|
|
100
|
+
@resources = RESOURCES.values.to_h { [it, ResourceProxy.new(@transport, it)] }.freeze
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# @return [Config] the validated configuration, with credentials redacted
|
|
104
|
+
# from its +inspect+ output
|
|
105
|
+
def config = @transport.config
|
|
106
|
+
|
|
107
|
+
# The proxy for a resource, by name or by class. A class is the way to
|
|
108
|
+
# the parts of the API this gem does not model.
|
|
109
|
+
#
|
|
110
|
+
# @example A resource this gem does not model
|
|
111
|
+
# class Role < ZammadAPI::Resources::Base
|
|
112
|
+
# path 'api/v1/roles'
|
|
113
|
+
# end
|
|
114
|
+
#
|
|
115
|
+
# client.resource(Role).each { |role| puts role.name }
|
|
116
|
+
#
|
|
117
|
+
# @param name [Symbol, String, Class] a key of {RESOURCES}, or a subclass
|
|
118
|
+
# of {Resources::Base}
|
|
119
|
+
# @return [ResourceProxy]
|
|
120
|
+
# @raise [UnknownResourceError] when no resource has that name
|
|
121
|
+
def resource(name)
|
|
122
|
+
return @resources.fetch(name) { ResourceProxy.new(@transport, name) } if name.is_a?(Class)
|
|
123
|
+
|
|
124
|
+
resource_class = RESOURCES.fetch(name.to_sym) do
|
|
125
|
+
raise UnknownResourceError, "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}"
|
|
35
126
|
end
|
|
36
|
-
|
|
127
|
+
|
|
128
|
+
@resources.fetch(resource_class)
|
|
37
129
|
end
|
|
38
130
|
|
|
39
|
-
|
|
131
|
+
# @return [Array<Symbol>] every resource name this client supports
|
|
132
|
+
def resource_names = RESOURCES.keys
|
|
40
133
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
134
|
+
# The user these requests authenticate as, or the one {#on_behalf_of}
|
|
135
|
+
# scoped them to.
|
|
136
|
+
#
|
|
137
|
+
# @example Checking which account a token belongs to
|
|
138
|
+
# client.me.email # => "agent@example.com"
|
|
139
|
+
#
|
|
140
|
+
# @return [Resources::User]
|
|
141
|
+
# @raise [AuthenticationError] when the credentials are not valid
|
|
142
|
+
def me = users.find('me')
|
|
44
143
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
144
|
+
# The version of the Zammad instance, not of this gem — that is
|
|
145
|
+
# {ZammadAPI::VERSION}. Zammad serves it to administrators only.
|
|
146
|
+
#
|
|
147
|
+
# @example
|
|
148
|
+
# client.version # => "6.4.0"
|
|
149
|
+
#
|
|
150
|
+
# @return [String, nil] nil when the instance reported no version
|
|
151
|
+
# @raise [AuthorizationError] when the account is not an administrator
|
|
152
|
+
def version
|
|
153
|
+
@transport.get('api/v1/version').decoded(:object)[:version]&.to_s
|
|
154
|
+
end
|
|
48
155
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
156
|
+
# @!group Raw requests
|
|
157
|
+
|
|
158
|
+
# Performs a +GET+ against any endpoint of the Zammad API, with the
|
|
159
|
+
# client's authentication, retries, JSON decoding and error classes.
|
|
160
|
+
#
|
|
161
|
+
# @example An endpoint this gem does not model
|
|
162
|
+
# client.get('api/v1/roles').body
|
|
163
|
+
# # => [{id: 1, name: "Admin", ...}, ...]
|
|
164
|
+
#
|
|
165
|
+
# @example An endpoint that needs a header of its own
|
|
166
|
+
# client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'})
|
|
167
|
+
#
|
|
168
|
+
# @param path [String] path relative to {Config#url}; a leading slash is
|
|
169
|
+
# ignored, and an absolute URL is refused, so the client's credentials
|
|
170
|
+
# only ever go to the instance it was configured for
|
|
171
|
+
# @param query [Hash, nil] query string parameters
|
|
172
|
+
# @param headers [Hash, nil] request headers
|
|
173
|
+
# @return [Response]
|
|
174
|
+
# @raise [ResponseError] for any non-2xx response
|
|
175
|
+
# @raise [TransportError] when the request could not be completed
|
|
176
|
+
# @raise [ArgumentError] for a path that is an absolute URL
|
|
177
|
+
def get(path, query: nil, headers: nil) = @transport.get(path, query: query, headers: headers)
|
|
178
|
+
|
|
179
|
+
# Performs a +POST+ against any endpoint of the Zammad API.
|
|
180
|
+
#
|
|
181
|
+
# @example
|
|
182
|
+
# client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'})
|
|
183
|
+
#
|
|
184
|
+
# @param path [String] path relative to {Config#url}
|
|
185
|
+
# @param query [Hash, nil] query string parameters
|
|
186
|
+
# @param body [Hash, Array, String, nil] request payload; a Hash or Array is
|
|
187
|
+
# encoded as JSON, a String is sent as it is
|
|
188
|
+
# @param headers [Hash, nil] request headers
|
|
189
|
+
# @return [Response]
|
|
190
|
+
# @raise [ResponseError] for any non-2xx response
|
|
191
|
+
# @see #get
|
|
192
|
+
def post(path, query: nil, body: nil, headers: nil) = @transport.post(path, query: query, body: body, headers: headers)
|
|
193
|
+
|
|
194
|
+
# Performs a +PUT+ against any endpoint of the Zammad API.
|
|
195
|
+
#
|
|
196
|
+
# @param path [String] path relative to {Config#url}
|
|
197
|
+
# @param query [Hash, nil] query string parameters
|
|
198
|
+
# @param body [Hash, Array, String, nil] request payload; a Hash or Array is
|
|
199
|
+
# encoded as JSON, a String is sent as it is
|
|
200
|
+
# @param headers [Hash, nil] request headers
|
|
201
|
+
# @return [Response]
|
|
202
|
+
# @raise [ResponseError] for any non-2xx response
|
|
203
|
+
# @see #get
|
|
204
|
+
def put(path, query: nil, body: nil, headers: nil) = @transport.put(path, query: query, body: body, headers: headers)
|
|
205
|
+
|
|
206
|
+
# Performs a +DELETE+ against any endpoint of the Zammad API.
|
|
207
|
+
#
|
|
208
|
+
# @param path [String] path relative to {Config#url}
|
|
209
|
+
# @param query [Hash, nil] query string parameters
|
|
210
|
+
# @param headers [Hash, nil] request headers
|
|
211
|
+
# @return [Response]
|
|
212
|
+
# @raise [ResponseError] for any non-2xx response
|
|
213
|
+
# @see #get
|
|
214
|
+
def delete(path, query: nil, headers: nil) = @transport.delete(path, query: query, headers: headers)
|
|
52
215
|
|
|
53
|
-
|
|
216
|
+
# @!endgroup
|
|
54
217
|
|
|
55
|
-
|
|
218
|
+
# Returns a new client with some configuration options changed.
|
|
219
|
+
#
|
|
220
|
+
# The options are re-validated, and any {#on_behalf_of} scope is carried
|
|
221
|
+
# over. Naming credentials replaces the ones this client has.
|
|
222
|
+
#
|
|
223
|
+
# @example A longer timeout for one bulk job
|
|
224
|
+
# bulk = client.with(timeout: 300, retries: 5)
|
|
225
|
+
#
|
|
226
|
+
# @param options [Hash] any option accepted by {Config}
|
|
227
|
+
# @return [Client]
|
|
228
|
+
# @raise [ConfigurationError] when the resulting options are invalid
|
|
229
|
+
def with(**options)
|
|
230
|
+
self.class.new(transport: @transport.with_config(config.with(**options)))
|
|
56
231
|
end
|
|
57
232
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
233
|
+
# Performs requests on behalf of another user, through a new client.
|
|
234
|
+
#
|
|
235
|
+
# @example Scoped client
|
|
236
|
+
# support = client.on_behalf_of('agent@example.com')
|
|
237
|
+
# support.tickets.create(title: 'Help', group: 'Users', customer_id: 1)
|
|
238
|
+
#
|
|
239
|
+
# @example Block form
|
|
240
|
+
# client.on_behalf_of('agent@example.com') do |scoped|
|
|
241
|
+
# scoped.tickets.find(1)
|
|
242
|
+
# end
|
|
243
|
+
#
|
|
244
|
+
# @param identifier [String, Integer] login, email address or user id
|
|
245
|
+
# @yieldparam scoped [Client]
|
|
246
|
+
# @return [Client] when no block is given, otherwise the block's value
|
|
247
|
+
# @raise [ArgumentError] for an identifier that is nil or blank, which
|
|
248
|
+
# would quietly leave the requests unscoped
|
|
249
|
+
def on_behalf_of(identifier)
|
|
250
|
+
from = identifier.to_s.strip
|
|
251
|
+
raise ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{identifier.inspect}" if from.empty?
|
|
252
|
+
|
|
253
|
+
scoped = self.class.new(transport: @transport.with_on_behalf_of(from.freeze))
|
|
254
|
+
return scoped if !block_given?
|
|
255
|
+
|
|
256
|
+
yield scoped
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
def inspect
|
|
260
|
+
scope = @transport.on_behalf_of
|
|
261
|
+
|
|
262
|
+
"#<#{self.class.name} url=#{config.url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{scope.inspect}" if scope}>"
|
|
63
263
|
end
|
|
64
264
|
end
|
|
65
265
|
end
|