Statistics
| Branch: | Tag: | Revision:

one / src / sunstone / routes / support.rb @ 84f5447b

History | View | Annotate | Download (7.97 KB)

1
# -------------------------------------------------------------------------- #
2
# Copyright 2010-2015, C12G Labs S.L.                                        #
3
#                                                                            #
4
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
5
# not use this file except in compliance with the License. You may obtain    #
6
# a copy of the License at                                                   #
7
#                                                                            #
8
# http://www.apache.org/licenses/LICENSE-2.0                                 #
9
#                                                                            #
10
# Unless required by applicable law or agreed to in writing, software        #
11
# distributed under the License is distributed on an "AS IS" BASIS,          #
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
13
# See the License for the specific language governing permissions and        #
14
# limitations under the License.                                             #
15
#--------------------------------------------------------------------------- #
16

    
17
UNSUPPORTED_RUBY = (RUBY_VERSION =~ /^1.8/) != nil
18

    
19
begin
20
    require 'zendesk_api'
21
rescue LoadError
22
    STDERR.puts "[OpenNebula Support] Missing zendesk_api gem"
23
    ZENDESK_API_GEM = false
24
else
25
    ZENDESK_API_GEM = true
26
end
27

    
28
helpers do
29
    def zendesk_client
30
        client = ZendeskAPI::Client.new do |config|
31
          # Mandatory:
32

    
33
          config.url = "https://opennebula.zendesk.com/api/v2" # e.g. https://mydesk.zendesk.com/api/v2
34

    
35
          # Basic / Token Authentication
36
          config.username = session["zendesk_email"]
37

    
38
          # Choose one of the following depending on your authentication choice
39
          # config.token = "your zendesk token"
40
          config.password = session["zendesk_password"]
41

    
42
          # OAuth Authentication
43
          # config.access_token = "your OAuth access token"
44

    
45
          # Optional:
46

    
47
          # Retry uses middleware to notify the user
48
          # when hitting the rate limit, sleep automatically,
49
          # then retry the request.
50
          config.retry = true
51

    
52
          # Logger prints to STDERR by default, to e.g. print to stdout:
53
          # require 'logger'
54
          # config.logger = Logger.new(STDOUT)
55

    
56
          # Changes Faraday adapter
57
          # config.adapter = :patron
58

    
59
          # Merged with the default client options hash
60
          if ENV['http_proxy']
61
            config.client_options = { :proxy => ENV['http_proxy'] }
62
          end
63

    
64
          # When getting the error 'hostname does not match the server certificate'
65
          # use the API at https://yoursubdomain.zendesk.com/api/v2
66
        end
67

    
68
        if client.current_user.nil? || client.current_user.id.nil?
69
            error 401, "Zendesk account credentials are incorrect"
70
        else
71
            return client
72
        end
73
    end
74

    
75
    def zrequest_to_one(zrequest)
76
        one_zrequest = {
77
            "id" => zrequest.id,
78
            "url" => zrequest.url,
79
            "subject" => zrequest.subject,
80
            "description" => zrequest.description,
81
            "status" => zrequest.status,
82
            "created_at" => zrequest.created_at,
83
            "updated_at" => zrequest.updated_at,
84
            "comments" => []
85
        }
86

    
87
        zrequest.custom_fields.each { |field|
88
            case field.id
89
            when 391130
90
                one_zrequest["opennebula_version"] = field.value
91
            when 391197
92
                one_zrequest["severity"] = field.value
93
            end
94
        }
95

    
96
        if zrequest.comments
97
            comment = zrequest.comments.delete_at(0)
98
            one_zrequest["html_description"] = comment.html_body
99

    
100
            zrequest.comments.each{ |comment|
101
                one_zrequest["comments"] << {
102
                    "created_at" => comment.created_at,
103
                    "html_body" => comment.html_body,
104
                    "author_id" => comment.author_id,
105
                    "body" => comment.body
106
                }
107
            }
108
        end
109

    
110
        return one_zrequest
111
    end
112

    
113
    def check_zendesk_api_gem
114
        if UNSUPPORTED_RUBY
115
            error 500, "Ruby version >= 1.9 is required"
116
        end
117

    
118
        if !ZENDESK_API_GEM
119
            error 500, "zendesk_api gem missing"
120
        end
121
    end
122
end
123

    
124
get '/support/request' do
125
    check_zendesk_api_gem
126

    
127
    zrequests = zendesk_client.requests({:status => "open,pending"})
128

    
129
    open_requests = 0
130
    pending_requests = 0
131
    one_zrequests = {
132
        "REQUEST_POOL" => {
133
        }
134
    }
135

    
136
    if zrequests.size > 0
137
        one_zrequests["REQUEST_POOL"]["REQUEST"] = []
138
    end
139

    
140
    zrequests.each { |zrequest|
141
        if zrequest.status == "pending"
142
            pending_requests += 1
143
        elsif zrequest.status == "open"
144
            open_requests +=1
145
        end
146

    
147
        one_zrequests["REQUEST_POOL"]["REQUEST"] << zrequest_to_one(zrequest)
148
    }
149

    
150
    one_zrequests["open_requests"] = open_requests
151
    one_zrequests["pending_requests"] = pending_requests
152

    
153
    [200, JSON.pretty_generate(one_zrequests)]
154
end
155

    
156
get '/support/request/:id' do
157
    check_zendesk_api_gem
158

    
159
    zrequest = zendesk_client.requests.find(:id => params[:id])
160
    # TODO check error
161
    one_zrequest = {
162
        "REQUEST" => zrequest_to_one(zrequest)
163
    }
164

    
165
    [200, JSON.pretty_generate(one_zrequest)]
166
end
167

    
168
post '/support/request' do
169
    check_zendesk_api_gem
170

    
171
    body_hash = JSON.parse(@request_body)
172

    
173
    zrequest = ticket = ZendeskAPI::Request.new(zendesk_client, {
174
            :subject => body_hash['subject'],
175
            :comment => { :value => body_hash['description'] },
176
            :custom_fields => [
177
              {:id => 391197, :value => body_hash['severity']},
178
              {:id => 391130, :value => body_hash['opennebula_version']}
179
            ]
180
          })
181

    
182
    if zrequest.save
183
        [201, JSON.pretty_generate(zrequest_to_one(zrequest))]
184
    else
185
        [403, Error.new(zrequest.errors["base"][0]["description"]).to_json]
186
    end
187
end
188

    
189
post '/support/request/:id/action' do
190
    check_zendesk_api_gem
191

    
192
    body_hash = JSON.parse(@request_body)
193
    if body_hash["action"]["params"]['comment']
194
        comment_value = body_hash["action"]["params"]['comment']['value']
195
    else
196
        logger.error("[OpenNebula Support] Missing comment message")
197
        error = Error.new(e.message)
198
        error 403, error.to_json
199
    end
200

    
201
    zrequest = zendesk_client.requests.find(:id => params[:id])
202
    # TODO check error
203

    
204
    zrequest.comment = {"value" => body_hash["action"]["params"]['comment']['value']}
205
    zrequest.solved = true if body_hash["action"]["params"]["solved"]
206
    zrequest.save!
207

    
208
    one_zrequest = {
209
        "REQUEST" => zrequest_to_one(zrequest)
210
    }
211

    
212
    [201, JSON.pretty_generate(one_zrequest)]
213
end
214

    
215

    
216
post '/support/request/:id/upload' do
217
    check_zendesk_api_gem
218

    
219
    tmpfile = nil
220

    
221
    name = params[:tempfile]
222

    
223
    if !name
224
        [500, OpenNebula::Error.new("There was a problem uploading the file, " \
225
                "please check the permissions on the file").to_json]
226
    else
227
        tmpfile = File.join(Dir.tmpdir, name)
228

    
229
        zrequest = zendesk_client.requests.find(:id => params[:id])
230
        # TODO check error
231

    
232
        comment = ZendeskAPI::Request::Comment.new(zendesk_client, {"value" => name})
233
        comment.uploads << tmpfile
234

    
235
        zrequest.comment = comment
236
        zrequest.save
237

    
238
        one_zrequest = {
239
            "REQUEST" => zrequest_to_one(zrequest)
240
        }
241

    
242
        FileUtils.rm(tmpfile)
243

    
244
        [201, JSON.pretty_generate(one_zrequest)]
245
    end
246
end
247

    
248
post '/support/credentials' do
249
    check_zendesk_api_gem
250

    
251
    body_hash = JSON.parse(@request_body)
252
    if body_hash["email"].nil? || body_hash["password"].nil?
253
        error 401, "Zendesk credentials not provided"
254
    end
255

    
256
    session["zendesk_email"] = body_hash["email"]
257
    session["zendesk_password"] = body_hash["password"]
258

    
259
    zendesk_client
260

    
261
    [204, ""]
262
end
263

    
264
delete '/support/credentials' do
265
    check_zendesk_api_gem
266

    
267
    session["zendesk_email"] = nil
268
    session["zendesk_password"] = nil
269

    
270
    [204, ""]
271
end