forked from pgericson/zendesk-api
/
main.rb
101 lines (89 loc) · 2.63 KB
/
main.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
module Zendesk
class Main
attr_accessor :main_url, :format
attr_reader :response_raw, :response
def initialize(account, username, password, options = {})
@account = account
@username = username
@password = password
@options = options
if options[:format] && ['xml','json'].any?{|f| f == options[:format]}
@format = options[:format]
else
@format = 'xml'
end
end
def main_url
url_prefix = @options[:ssl] ? "https://" : "http://"
url_postfix = ".zendesk.com/"
url = url_prefix + @account + url_postfix
end
def self.to_xml(function_name, input)
if input.is_a?(String)
input
else
input.to_xml({:root => function_name})
end
end
def make_request(end_url, body = {})
curl = Curl::Easy.new(main_url + end_url + ".#{@format}")
curl.userpwd = "#{@username}:#{@password}"
unless body.empty?
if body.values.first.is_a?(Hash)
final_body = body.values.first.to_xml
elsif body.values.first.is_a?(String)
final_body = body.values.first
end
if body[:create]
curl.headers = "Content-Type: application/xml"
curl.http_post(final_body)
elsif body[:update]
curl.headers = "Content-Type: application/xml"
curl.http_put(final_body)
elsif body[:destroy]
curl.http_delete(final_body)
elsif body[:list]
params = "?" + body[:list].to_a.map do |p|
"#{p[0]}=#{p[1]}"
end.join("&")
curl.url = curl.url + params
end
else
curl.perform
end
if curl.body_str == "<error>Couldn't authenticate you</error>"
return "string" #raise CouldNotAuthenticateYou
end
Response.new(curl)
end
class Response
attr_reader :status, :body, :headers_raw, :headers
def initialize(curl)
@status=curl.response_code
@body=curl.body_str
@headers_raw=curl.header_str
parse_headers
end
def parse_headers
hs={}
headers_raw.split("\r\n")[1..-1].each do |h|
# Rails.logger.info h
m=h.match(/([^:]+):\s?(.*)/)
next if m.nil? or m[2].nil?
# Rails.logger.info m.inspect
hs[m[1]]=m[2]
end
@headers=hs
end
end
include Zendesk::User
include Zendesk::Organization
include Zendesk::Group
include Zendesk::Ticket
include Zendesk::Attachment
include Zendesk::Tag
include Zendesk::Forum
include Zendesk::Entry
include Zendesk::Search
end
end