Class: RT_Client

Inherits:
Object
  • Object
show all
Defined in:
rt_client.rb

Overview

<img src=“” alt=“Gem Version” /> A ruby library API to Request Tracker’s REST interface. Requires the rubygem rest-client be installed. You can create a file name .rtclientrc in the same directory as client.rb with a default server/user/pass to connect to RT as, so that you don’t have to specify it/update it in lots of different scripts.

Thanks to Brian McArdle for patch dealing with spaces in Custom Fields. To reference custom fields in RT that have spaces with rt-client, use an underscore in the rt-client code, e.g. “CF.{Has_Space}”

Thanks to Robert Vinson for 1.9.x compatibility when I couldn’t be buggered and a great job of refactoring the old mess into something with much fewer dependencies.

Thanks to Steven Craig for a bug fix and feature additions to the usersearch() method.

TODO: Streaming, chunking attachments in compose method

See each method for sample usage. To use this, “gem install rt-client” and

require "rt/client"

Constant Summary collapse

UA =
"Mozilla/5.0 ruby RT Client Interface 0.7.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*params) ⇒ RT_Client

Create a new RT_Client object. Load up our stored cookie and check it. Log into RT again if needed and store the new cookie. You can specify login and cookie storage directories in 3 different ways:

  1. Explicity during object creation

  2. From a .rtclientrc file in the working directory of your ruby program

  3. From a .rtclientrc file in the same directory as the library itself

These are listed in order of priority; if you have explicit parameters, they are always used, even if you have .rtclientrc files. If there is both an .rtclientrc in your program’s working directory and in the library directory, the one from your program’s working directory is used. If no parameters are specified either explicity or by use of a .rtclientrc, then the defaults of “rt_user”, “rt_pass” are used with a default server of “localhost”, and cookies are stored in the directory where the library resides.

rt= RT_Client.new( :server  => "https://tickets.ambulance.com/",
                   :user    => "rt_user",
                   :pass    => "rt_pass",
                   :cookies => "/my/cookie/dir" )

rt= RT_Client.new # use defaults from .rtclientrc

.rtclientrc format:

server=<RT server>
user=<RT user>
pass=<RT password>
cookies=<directory>


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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'rt_client.rb', line 68

def initialize(*params)
  @boundary = "----xYzZY#{rand(1000000).to_s}xYzZY"
  @version = "0.7.1"
  @status = "Not connected"
  @server = "http://localhost/"
  @user = "rt_user"
  @pass = "rt_pass"
  @cookies = Dir.pwd
  config_file = Dir.pwd + "/.rtclientrc"
  config = ""
  if File.file?(config_file)
    config = File.read(config_file)
  else
    config_file = File.dirname(__FILE__) + "/.rtclientrc"
    config = File.read(config_file) if File.file?(config_file)
  end
  @server = $~[1] if config =~ /\s*server\s*=\s*(.*)$/i
  @user = $~[1] if config =~ /^\s*user\s*=\s*(.*)$/i
  @pass = $~[1] if config =~ /^\s*pass\s*=\s*(.*)$/i
  @cookies = $~[1] if config =~ /\s*cookies\s*=\s*(.*)$/i
  @resource = "#{@server}REST/1.0/"
  if params.class == Array && params[0].class == Hash
    param = params[0]
    @user = param[:user] if param.has_key? :user
    @pass = param[:pass] if param.has_key? :pass
    if param.has_key? :server
      @server = param[:server]
      @server += "/" if @server !~ /\/$/
      @resource = "#{@server}REST/1.0/"
    end
    @cookies  = param[:cookies] if param.has_key? :cookies
  end
  @login = { :user => @user, :pass => @pass }
  cookiejar = "#{@cookies}/RT_Client.#{@user}.cookie" # cookie location
  cookiejar.untaint
  if File.file? cookiejar
    @cookie = File.read(cookiejar).chomp
    headers = { 'User-Agent'   => UA,
    'Content-Type' => "application/x-www-form-urlencoded",
    'Cookie'       => @cookie }
  else
    headers = { 'User-Agent'   => UA,
    'Content-Type' => "application/x-www-form-urlencoded" }
    @cookie = ""
  end


  site = RestClient::Resource.new(@resource, :headers => headers, :timeout => 240)
  data = site.post "" # a null post just to check that we are logged in

  if @cookie.length == 0 or data =~ /401/ # we're not logged in
    data = site.post @login, :headers => headers
    #      puts data
    @cookie = data.headers[:set_cookie].first.split('; ')[0]
    # write the new cookie
    if @cookie !~ /nil/
      f = File.new(cookiejar,"w")
      f.puts @cookie
      f.close
    end
  end
  headers = { 'User-Agent'   => UA,
     'Content-Type' => "multipart/form-data; boundary=#{@boundary}",
  'Cookie'       => @cookie }
  @site = RestClient::Resource.new(@resource, :headers => headers)
  @status = data
  self.untaint
end

Instance Attribute Details

Returns the value of attribute cookie.



38
39
40
# File 'rt_client.rb', line 38

def cookie
  @cookie
end

#cookiesObject (readonly)

Returns the value of attribute cookies.



38
39
40
# File 'rt_client.rb', line 38

def cookies
  @cookies
end

#serverObject (readonly)

Returns the value of attribute server.



38
39
40
# File 'rt_client.rb', line 38

def server
  @server
end

#siteObject (readonly)

Returns the value of attribute site.



38
39
40
# File 'rt_client.rb', line 38

def site
  @site
end

#statusObject (readonly)

Returns the value of attribute status.



38
39
40
# File 'rt_client.rb', line 38

def status
  @status
end

#userObject (readonly)

Returns the value of attribute user.



38
39
40
# File 'rt_client.rb', line 38

def user
  @user
end

#versionObject (readonly)

Returns the value of attribute version.



38
39
40
# File 'rt_client.rb', line 38

def version
  @version
end

Instance Method Details

#add_watcher(*params) ⇒ Object

Add a watcher to a ticket, but only if not already a watcher. Takes a ticket ID, an email address (or array of email addresses), and an optional watcher type. If no watcher type is specified, its assumed to be “Cc”. Possible watcher types are ‘Requestors’, ‘Cc’, and ‘AdminCc’.

rt.add_watcher(123,"[email protected]")
rt.add_watcher(123,["[email protected]","[email protected]"])
rt.add_watcher(123,"[email protected]","Requestors")
rt.add_watcher(:id => 123, :addr => "[email protected]")
rt.add_watcher(:id => 123, :addr => ["[email protected]","[email protected]"])
rt.add_watcher(:id => 123, :addr => "[email protected]", :type => "AdminCc")


716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'rt_client.rb', line 716

def add_watcher(*params)
  tid = params[0]
  addr = []
  type = "cc"
  addr = params[1] if params.size > 1
  type = params[2] if params.size > 2
  if params[0].class == Hash
    params = params[0]
    tid = params[:id] if params.has_key? :id
    addr = params[:addr] if params.has_key? :addr
    type = params[:type] if params.has_key? :type
  end
  addr = addr.to_a.uniq # make it array if its just a string, and remove dups
  type.downcase!
  tobj = show(tid) # get current watchers
  ccs = tobj["cc"].split(", ")
  accs = tobj["admincc"].split(", ")
  reqs = tobj["requestors"].split(", ")
  watchers = ccs | accs | reqs # union of all watchers
  addr.each do |e|
    case type
      when "cc"
        ccs.push(e) if not watchers.include?(e)
      when "admincc"
        accs.push(e) if not watchers.include?(e)
      when "requestors"
        reqs.push(e) if not watchers.include?(e)
    end
  end
  case type
    when "cc"
      edit(:id => tid, :Cc => ccs.join(","))
    when "admincc"
      edit(:id => tid, :AdminCc => accs.join(","))
    when "requestors"
      edit(:id => tid, :Requestors => reqs.join(","))
  end
end

#attachments(*params) ⇒ Object

Get a list of attachments related to a ticket. Requires a ticket id, returns an array of hashes where each hash represents one attachment. Hash keys are :id, :name, :type, :size. You can optionally request that unnamed attachments be included, the default is to not include them.



609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'rt_client.rb', line 609

def attachments(*params)
  id = params[0]
  unnamed = params[1]
  if params[0].class == Hash
    params = params[0]
    id = params[:id] if params.has_key? :id
    unnamed = params[:unnamed] if params.has_key? :unnamed
  end
  unnamed = false if unnamed.to_s == "0"
  id = $~[1] if id =~ /ticket\/(\d+)/
  resp = @site["ticket/#{id}/attachments"].get
  resp.gsub!(/RT\/\d+\.\d+\.\d+\s\d{3}\s.*\n\n/,"") # toss the HTTP response
  resp.gsub!(/^\n/m,"") # toss blank lines
  while resp.match(/CF\.\{[\w_ ]*[ ]+[\w ]*\}/) #replace CF spaces with underscores
    resp.gsub!(/CF\.\{([\w_ ]*)([ ]+)([\w ]*)\}/, 'CF.{\1_\3}')
  end
  th = response_to_h(resp)
  list = []
  pattern = /(\d+:\s.*?\)),/
  match = pattern.match(th['attachments'].to_s)
  while match != nil
    list.push match[0]
    s = match.post_match
    match = pattern.match(s)
  end
  attachments = []
  list.each do |v|
    attachment = {}
    m=v.match(/(\d+):\s+(.*?)\s+\((.*?)\s+\/\s+(.*?)\)/)
    if m.class == MatchData
      next if m[2] == "(Unnamed)" and !unnamed
      attachment[:id] = m[1]
      attachment[:name] = m[2]
      attachment[:type] = m[3]
      attachment[:size] = m[4]
      attachments.push attachment
    end
  end
  attachments
end

#comment(field_hash) ⇒ Object

Comment on a ticket. Requires a hash, which must have an :id key containing the ticket number. Returns the REST response. For a list of fields you can use in a comment, try “/opt/rt3/bin/rt comment ticket/1”

rt.comment( :id   => id,
            :Text => "Oh dear, I wonder if the hip smells like almonds?",
            :Attachment => "/tmp/almonds.gif" )


294
295
296
297
298
299
300
301
302
303
# File 'rt_client.rb', line 294

def comment(field_hash)
  if field_hash.has_key? :id
    id = field_hash[:id]
  else
    raise "RT_Client.comment requires a Ticket number in the 'id' key."
  end
  field_hash[:Action] = "comment"
  payload = compose(field_hash)
  @site["ticket/#{id}/comment"].post payload
end

#compose(fields) ⇒ Object

Helper for composing RT’s “forms”. Requires a hash where the keys are field names for an RT form. If there’s a :Text key, the value is modified to insert whitespace on continuation lines. If there’s an :Attachment key, the value is assumed to be a comma-separated list of filenames to attach. It returns a hash to be used with rest-client’s payload class



798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
# File 'rt_client.rb', line 798

def compose(fields) # :nodoc:
  if fields.class != Hash
    raise "RT_Client.compose requires parameters as a hash."
  end

  payload = { :multipart => true }

  # attachments
  if fields.has_key? :Attachments
    fields[:Attachment] = fields[:Attachments]
    fields.delete :Attachments
  end
  if fields.has_key? :Attachment
    filenames = fields[:Attachment].split(',')
    attachment_num = 1
    filenames.each do |f|
      payload["attachment_#{attachment_num.to_s}"] = File.new(f)
      attachment_num += 1
    end
    # strip paths from filenames
    fields[:Attachment] = filenames.map {|f| File.basename(f)}.join(',') 
  end

  # fixup Text field for RFC822 compliance
  if fields.has_key? :Text
    fields[:Text].gsub!(/\n/,"\n ") # insert a space on continuation lines.
  end

  field_array = fields.map { |k,v| "#{k}: #{v}" }
  content = field_array.join("\n") # our form
  payload["content"] = content

  return payload
end

#correspond(field_hash) ⇒ Object

correspond on a ticket. Requires a hash, which must have an :id key containing the ticket number. Returns the REST response. For a list of fields you can use in correspondence, try “/opt/rt3/bin/rt correspond ticket/1”

rt.correspond( :id   => id,
               :Text => "We're sending help right away.",
               :Attachment => "/tmp/admittance.doc" )


337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'rt_client.rb', line 337

def correspond(field_hash)
  if field_hash.has_key? :id
    if field_hash[:id] =~ /ticket\/(\d+)/
      id = $~[1]
    else
      id = field_hash[:id]
    end
  else
    raise "RT_Client.correspond requires a Ticket number in the 'id' key."
  end
  field_hash[:Action] = "correspond"
  payload = compose(field_hash)
  @site["ticket/#{id}/comment"].post payload
end

#create(field_hash) ⇒ Object

Creates a new ticket. Requires a hash that contains RT form fields as the keys. Capitalization is important; use :Queue, not :queue. You will need at least :Queue to create a ticket. For a full list of fields you can use, try “/opt/rt3/bin/rt edit ticket/1”. Returns the newly created ticket number, or a complete REST response.

id = rt.create( :Queue   => "Customer Service",
                :Cc      => "somebody\@email.com",
                :Subject => "I've fallen and I can't get up",
                :Text    => "I think my hip is broken.\nPlease help.",
                :"CF.{CustomField}" => "Urgent",


204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'rt_client.rb', line 204

def create(field_hash)
  field_hash[:id] = "ticket/new"
  payload = compose(field_hash)
#    puts "Payload for new ticket:"
#    puts payload
  resp = @site['ticket/new/edit'].post payload
  new_id = resp.match(/Ticket\s*(\d+)/)
  if new_id.class == MatchData
    new_ticket = new_id[1]
  else
    new_ticket = resp
  end
  new_ticket # return the ticket number, or the full REST response
end

#create_user(field_hash) ⇒ Object

create a new user. Requires a hash of RT fields => values. Returns the newly created user ID, or the full REST response if there is an error. For a full list of possible parameters that you can specify, look at “/opt/rt/bin/rt edit user/1”

new_id = rt.create_user(:Name => "Joe_Smith", :EmailAddress => "joes\@here.com")


225
226
227
228
229
230
231
232
233
234
235
236
# File 'rt_client.rb', line 225

def create_user(field_hash)
  field_hash[:id] = "user/new"
  payload = compose(field_hash)
  resp = @site['user/new/edit'].post payload
  new_id = resp.match(/User\s*(\d+)/)
  if new_id.class == MatchData
    new_user = new_id[1]
  else
    new_user = resp
  end
  new_user # return the new user id or the full REST response
end

#edit(field_hash) ⇒ Object

edit an existing ticket/user. Requires a hash containing RT form fields as keys. the key :id is required. returns the complete REST response, whatever it is. If the id supplied contains “user/”, it edits a user, otherwise it edits a ticket. For a full list of fields you can edit, try “/opt/rt3/bin/rt edit ticket/1”

resp = rt.edit(:id => 822, :Status => "resolved")
resp = rt.edit(:id => ticket_id, :"CF.{CustomField}" => var)
resp = rt.edit(:id => "user/someone", :EMailAddress => "[email protected]")
resp = rt.edit(:id => "user/bossman", :Password => "mypass")
resp = rt.edit(:id => "user/4306", :Disabled => "1")


270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'rt_client.rb', line 270

def edit(field_hash)
  if field_hash.has_key? :id
    id = field_hash[:id]
  else
    raise "RT_Client.edit requires a user or ticket id in the 'id' key."
  end
  type = "ticket"
  sid = id
  if id =~ /(\w+)\/(.+)/
    type = $~[1]
    sid = $~[2]
  end
  payload = compose(field_hash)
  resp = @site["#{type}/#{sid}/edit"].post payload
  resp
end

#edit_or_create_user(field_hash) ⇒ Object

edit or create a user. If the user exists, edits the user as “edit” would. If the user doesn’t exist, creates it as “create_user” would.



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'rt_client.rb', line 240

def edit_or_create_user(field_hash)
  if field_hash.has_key? :id
    id = field_hash[:id]
    if id !~ /^user\//
      id = "user/#{id}"
      field_hash[:id] = id
    end
  else
    raise "RT_Client.edit_or_create_user require a user id in the 'id' key."
  end
  resp1 =  "not called"
  resp2 =  "not called"
  resp1 = edit(field_hash)
  resp2 = create_user(field_hash) if resp1 =~ /does not exist./
  resp = "Edit: #{resp1}\nCreate:#{resp2}"
  resp
end

#get_attachment(*params) ⇒ Object

Get attachment content for single attachment. Requires a ticket ID and an attachment ID, which must be related. If a directory parameter is supplied, the attachment is written to that directory. If not, the attachment content is returned in the hash returned by the function as the key ‘content’, along with some other keys you always get:

transaction

the transaction id

creator

the user id number who attached it

id

the attachment id

filename

the name of the file

contenttype

MIME content type of the attachment

created

date of the attachment

parent

an attachment id if this was an embedded MIME attachment

x = get_attachment(21,3879)
x = get_attachment(:ticket => 21, :attachment => 3879)
x = get_attachment(:ticket => 21, :attachment => 3879, :dir = "/some/dir")


667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'rt_client.rb', line 667

def get_attachment(*params)
  tid = params[0]
  aid = params[1]
  dir = nil
  dir = params[2] if params.size > 2
  if params[0].class == Hash
    params = params[0]
    tid = params[:ticket] if params.has_key? :ticket
    aid = params[:attachment] if params.has_key? :attachment
    dir = params[:dir] if params.has_key? :dir
  end
  tid = $~[1] if tid =~ /ticket\/(\d+)/
  resp = @site["ticket/#{tid}/attachments/#{aid}"].get
  resp.gsub!(/RT\/\d+\.\d+\.\d+\s\d{3}\s.*\n\n/,"") # toss HTTP response
  while resp.match(/CF\.\{[\w_ ]*[ ]+[\w ]*\}/) #replace CF spaces with underscores
    resp.gsub!(/CF\.\{([\w_ ]*)([ ]+)([\w ]*)\}/, 'CF.{\1_\3}')
  end
  headers = response_to_h(resp)
  reply = {}
  headers.each do |k,v|
    reply["#{k}"] = v.to_s
  end
  content = resp.match(/Content:\s+(.*)/m)[1]
  content.gsub!(/\n\s{9}/,"\n") # strip leading spaces on each line
  content.chomp! 
  content.chomp! 
  content.chomp! # 3 carriage returns at the end
  binary = Iconv.conv("ISO-8859-1","UTF-8",content) # convert encoding
  if dir
    fh = File.new("#{dir}/#{headers['Filename'].to_s}","wb")
    fh.write binary
    fh.close
  else
    reply["content"] = binary
  end
  reply
end

#history(*params) ⇒ Object

an optional format parameter. If the format is ommitted, the short format is assumed. If the short format is requested, it returns an array of 2 element arrays, where each 2-element array is [ticket_id, description]. If the long format is requested, it returns an array of hashes, where each hash contains the keys:

id

(history-id)

Ticket

(Ticket this history item belongs to)

TimeTaken

(time entered by the actor that generated this item)

Type

(what type of history item this is)

Field

(what field is affected by this item, if any)

OldValue

(the old value of the Field)

NewValue

(the new value of the Field)

Data

(Additional data about the item)

Description

(Description of this item; same as short format)

Content

(The content of this item)

Creator

(the RT user that created this item)

Created

(Date/time this item was created)

Attachments

(a hash describing attachments to this item)

history = rt.history(881)
history = rt.history(881,"short")
=> [["10501"," Ticket created by blah"],["10510"," Comments added by userX"]]
history = rt.history(881,"long")
history = rt.history(:id => 881, :format => "long")
=> [{"id" => "6171", "ticket" => "881" ....}, {"id" => "6180", ...} ]


464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'rt_client.rb', line 464

def history(*params)
  id = params[0]
  format = "short"
  format = params[1].downcase if params.size > 1
  comments = false
  comments = params[2] if params.size > 2
  if params[0].class == Hash
     params = params[0]
     id = params[:id] if params.has_key? :id
     format = params[:format].downcase if params.has_key? :format
     comments = params[:comments] if params.has_key? :comments
  end
  id = id.to_s
  id = $~[1] if id =~ /ticket\/(\d+)/
  resp = @site["ticket/#{id}/history?format=#{format[0,1]}"].get
  resp.gsub!(0x1C.chr,'[FS]')
  resp.gsub!(0x1D.chr,'[GS]')
  resp.gsub!(0x1E.chr,'[RS]')
  resp.gsub!(0x1F.chr,'[US]')

  if format[0,1] == "s"
    if comments
      h = resp.split("\n").select{ |l| l =~ /^\d+:/ }
    else
      h = resp.split("\n").select{ |l| l =~ /^\d+: [^Comments]/ }
      h.select!{ |l| l !~ /Outgoing email about a comment/ }
    end
    list = h.map { |l| l.split(":") }
  else
    resp.gsub!(/RT\/\d+\.\d+\.\d+\s\d{3}\s.*\n\n/,"") # toss the HTTP response
    resp.gsub!(/^#.*?\n\n/,"") # toss the 'total" line
    resp.gsub!(/^\n/m,"") # toss blank lines
    while resp.match(/CF\.\{[\w_ ]*[ ]+[\w ]*\}/) #replace CF spaces with underscores
      resp.gsub!(/CF\.\{([\w_ ]*)([ ]+)([\w ]*)\}/, 'CF.{\1_\3}')
    end
                    
    items = resp.split("\n--\n") 
    list = []
    items.each do |item|
      th = response_to_h(item)
      next if not comments and th["type"].to_s =~ /Comment/ # skip comments
      reply = {}
      th.each do |k,v|
        attachments = []
        case k
          when "attachments"
            temp = item.match(/Attachments:\s*(.*)/m)
            if temp.class != NilClass
              atarr = temp[1].split("\n")
              atarr.map { |a| a.gsub!(/^\s*/,"") }
              atarr.each do |a|
                i = a.match(/(\d+):\s*(.*)/)
                s={}
                s[:id] = i[1].to_s
                s[:name] = i[2].to_s
                sz = i[2].match(/(.*?)\s*\((.*?)\)/)
                if sz.class == MatchData
                  s[:name] = sz[1].to_s
                  s[:size] = sz[2].to_s
                end
                attachments.push s
              end
              reply["attachments"] = attachments
            end
          when "content"
            reply["content"] = v.to_s
            temp = item.match(/^Content: (.*?)^\w+:/m) 
            reply["content"] = temp[1] if temp.class != NilClass
          else
            reply["#{k}"] = v.to_s
        end
      end
      list.push reply
    end        
  end
  list
end

#history_item(*params) ⇒ Object

Get the detail for a single history item. Needs a ticket ID and a history item ID, returns a hash of RT Fields => values. The hash also contains a special key named “attachments”, whose value is an array of hashes, where each hash represents an attachment. The hash keys are :id, :name, and :size.

x = rt.history_item(21, 6692)
x = rt.history_item(:id => 21, :history => 6692)
=> x = {"ticket" => "21", "creator" => "somebody", "description" => 
=>      "something happened", "attachments" => [{:name=>"file.txt",
=>      :id=>"3289", size=>"651b"}, {:name=>"another.doc"... }]}


553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'rt_client.rb', line 553

def history_item(*params)
  id = params[0]
  history = params[1]
  if params[0].class == Hash
    params = params[0]
    id = params[:id] if params.has_key? :id
    history = params[:history] if params.has_key? :history
  end
  reply = {}
  resp = @site["ticket/#{id}/history/id/#{history}"].get
  return reply if resp =~ /not related/ # history id must be related to the ticket id
  resp.gsub!(/RT\/\d+\.\d+\.\d+\s\d{3}\s.*\n\n/,"") # toss the HTTP response
  resp.gsub!(/^#.*?\n\n/,"") # toss the 'total" line
  resp.gsub!(/^\n/m,"") # toss blank lines
  while resp.match(/CF\.\{[\w_ ]*[ ]+[\w ]*\}/) #replace CF spaces with underscores
    resp.gsub!(/CF\.\{([\w_ ]*)([ ]+)([\w ]*)\}/, 'CF.{\1_\3}')
  end
  th = response_to_h(resp)
  attachments = []
  th.each do |k,v|
    case k
      when "attachments"
        temp = resp.match(/Attachments:\s*(.*)[^\w|$]/m)
        if temp.class != NilClass
          atarr = temp[1].split("\n")
          atarr.map { |a| a.gsub!(/^\s*/,"") }
          atarr.each do |a|
            i = a.match(/(\d+):\s*(.*)/)
            s={}
            s[:id] = i[1]
            s[:name] = i[2]
            sz = i[2].match(/(.*?)\s*\((.*?)\)/)
            if sz.class == MatchData
              s[:name] = sz[1]
              s[:size] = sz[2]
            end
            attachments.push s
          end
          reply["#{k}"] = attachments
        end
      when "content"
        reply["content"] = v.to_s
        temp = resp.match(/^Content: (.*?)^\w+:/m) 
        reply["content"] = temp[1] if temp.class != NilClass
      else
        reply["#{k}"] = v.to_s
    end
  end
  reply
end

#inspectObject

don’t give up the password when the object is inspected



757
758
759
760
761
# File 'rt_client.rb', line 757

def inspect # :nodoc:
  mystr = super()
  mystr.gsub!(/(.)pass=.*?([,\}])/,"\\1pass=<hidden>\\2")
  mystr
end

takes a single parameter containing the ticket id, and returns a hash of RT Fields => values

hash = rt.links(822)
hash = rt.links("822")
hash = rt.links("ticket/822")
hash = rt.links(:id => 822)
hash = rt.links(:id => "822")
hash = rt.links(:id => "ticket/822")


178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'rt_client.rb', line 178

def links(id)
  id = id[:id] if id.class == Hash
  id = id.to_s
  type = "ticket"
  sid = id
  if id =~ /(\w+)\/(.+)/
    type = $~[1]
    sid = $~[2]
  end
  reply = {}
  resp = @site["ticket/#{sid}/links/show"].get
  return {:error => resp, }  if resp =~ /does not exist./
  reply = response_to_h(resp)
end

#list(*params) ⇒ Object

Get a list of tickets matching some criteria. Takes a string Ticket-SQL query and an optional “order by” parameter. The order by is an RT field, prefix it with + for ascending or - for descending. Returns a nested array of arrays containing [ticket number, subject] The outer array is in the order requested.

hash = rt.list(:query => "Queue = 'Sales'")
hash = rt.list("Queue='Sales'")
hash = rt.list(:query => "Queue = 'Sales'", :order => "-Id")
hash = rt.list("Queue='Sales'","-Id")


363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'rt_client.rb', line 363

def list(*params)
  query = params[0]
  order = ""
  if params.size > 1
    order = params[1]
  end
  if params[0].class == Hash
    params = params[0]
    query = params[:query] if params.has_key? :query
    order = params[:order] if params.has_key? :order
  end
  reply = []
  resp = @site["search/ticket/?query=#{URI.escape(query)}&orderby=#{order}&format=s"].get
  raise "Invalid query (#{query})" if resp =~ /Invalid query/
  resp = resp.split("\n") # convert to array of lines
  resp.each do |line|
    f = line.match(/^(\d+):\s*(.*)/)
    reply.push [f[1],f[2]] if f.class == MatchData
  end
  reply
end

#query(*params) ⇒ Object

A more extensive(expensive) query then the list method. Takes the same parameters as the list method; a string Ticket-SQL query and optional order, but returns a lot more information. Instead of just the ID and subject, you get back an array of hashes, where each hash represents one ticket, indentical to what you get from the show method (which only acts on one ticket). Use with caution; this can take a long time to execute.

array = rt.query("Queue='Sales'")
array = rt.query(:query => "Queue='Sales'",:order => "+Id")
array = rt.query("Queue='Sales'","+Id")
=> array[0] = { "id" => "123", "requestors" => "someone@..", etc etc }
=> array[1] = { "id" => "126", "requestors" => "someone@else..", etc etc }
=> array[0]["id"] = "123"


399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'rt_client.rb', line 399

def query(*params)
  query = params[0]
  order = ""
  if params.size > 1
    order = params[1]
  end
  if params[0].class == Hash
    params = params[0]
    query = params[:query] if params.has_key? :query
    order = params[:order] if params.has_key? :order
  end
  replies = []
  resp = @site["search/ticket/?query=#{URI.escape(query)}&orderby=#{order}&format=l"].get
  return replies if resp =~/No matching results./
  raise "Invalid query (#{query})" if resp =~ /Invalid query/
  resp.gsub!(/RT\/\d+\.\d+\.\d+\s\d{3}\s.*\n\n/,"") # strip HTTP response
  tickets = resp.split("\n--\n") # -- occurs between each ticket
  tickets.each do |ticket|
    ticket_h = response_to_h(ticket)
    reply = {}
    ticket_h.each do |k,v|
      case k
      when 'created','due','told','lastupdated','started'
        begin
          vv = DateTime.parse(v.to_s)
          reply["#{k}"] = vv.strftime("%Y-%m-%d %H:%M:%S")
        rescue ArgumentError
          reply["#{k}"] = v.to_s
        end
      else
        reply["#{k}"] = v.to_s
      end
    end
    replies.push reply
  end
  replies
end

#response_to_h(resp) ⇒ Object

helper to convert responses from RT REST to a hash



764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'rt_client.rb', line 764

def response_to_h(resp) # :nodoc:
  resp.gsub!(/RT\/\d+\.\d+\.\d+\s\d{3}\s.*\n\n/,"") # toss the HTTP response
  #resp.gsub!(/\n\n/,"\n") # remove double spacing, TMail stops at a blank line

  # unfold folded fields
  # A newline followed by one or more spaces is treated as a
  # single space
  resp.gsub!(/\n +/, " ")
  
  #replace CF spaces with underscores
  while resp.match(/CF\.\{[\w_ ]*[ ]+[\w ]*\}/) 
    resp.gsub!(/CF\.\{([\w_ ]*)([ ]+)([\w ]*)\}/, 'CF.{\1_\3}')
  end
  return {:error => resp }  if resp =~ /does not exist./

  # convert fields to key value pairs
  ret = {}
  resp.each_line do |ln|
    next unless ln =~ /^.+?:/
    ln_a = ln.split(/:/,2)
    ln_a.map! {|item| item.strip}
    ln_a[0].downcase!
    ret[ln_a[0]] = ln_a[1]
  end

  return ret
end

#show(id) ⇒ Object

gets the detail for a single ticket/user. If its a ticket, its without history or attachments (to get those use the history method) . If no type is specified, ticket is assumed. takes a single parameter containing the ticket/user id, and returns a hash of RT Fields => values

hash = rt.show(822)
hash = rt.show("822")
hash = rt.show("ticket/822")
hash = rt.show(:id => 822)
hash = rt.show(:id => "822")
hash = rt.show(:id => "ticket/822")
hash = rt.show("user/#{login}")
email = rt.show("user/somebody")["emailaddress"]


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'rt_client.rb', line 150

def show(id)
  id = id[:id] if id.class == Hash
  id = id.to_s
  type = "ticket"
  sid = id
  if id =~ /(\w+)\/(.+)/
    type = $~[1]
    sid = $~[2]
  end
  reply = {}
  if type.downcase == 'user'
    resp = @site["#{type}/#{sid}"].get
  else
    resp = @site["#{type}/#{sid}/show"].get
  end
  reply = response_to_h(resp)
end

#usernamesearch(field_hash) ⇒ Object

An alias for usersearch()



325
326
327
# File 'rt_client.rb', line 325

def usernamesearch(field_hash)
  usersearch(field_hash)
end

#usersearch(field_hash) ⇒ Object

Find RT user details from an email address or a name

rt.usersearch(:EmailAddress => ‘[email protected]’) rt.usersearch(:Name => username) -> {“name”=>“rtlogin”, “realname”=>“John Smith”, “address1”=>“123 Main”, etc }



310
311
312
313
314
315
316
317
318
319
320
321
# File 'rt_client.rb', line 310

def usersearch(field_hash)
  key = nil
  key = field_hash[:EmailAddress] if field_hash.has_key? :EmailAddress
  key = field_hash[:Name] if field_hash.has_key? :Name
  if key == nil
    raise "RT_Client.usersearch requires an RT user email in the 'EmailAddress' key or an RT username in the 'Name' key"
  end
  reply = {}
  resp = @site["user/#{key}"].get
  return reply if resp =~ /No user named/
  reply = response_to_h(resp)
end