data_output_agent.rb 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. module Agents
  2. class DataOutputAgent < Agent
  3. cannot_be_scheduled!
  4. description do
  5. <<-MD
  6. The Agent outputs received events as either RSS or JSON. Use it to output a public or private stream of Huginn data.
  7. This Agent will output data at:
  8. `https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || '<id>'}/:secret.xml`
  9. where `:secret` is one of the allowed secrets specified in your options and the extension can be `xml` or `json`.
  10. You can setup multiple secrets so that you can individually authorize external systems to
  11. access your Huginn data.
  12. Options:
  13. * `secrets` - An array of tokens that the requestor must provide for light-weight authentication.
  14. * `expected_receive_period_in_days` - How often you expect data to be received by this Agent from other Agents.
  15. * `template` - A JSON object representing a mapping between item output keys and incoming event values. Use [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to format the values. The `item` key will be repeated for every Event. The `pubDate` key for each item will have the creation time of the Event unless given.
  16. * `events_to_show` - The number of events to output in RSS or JSON. (default: `40`)
  17. * `ttl` - A value for the <ttl> element in RSS output. (default: `60`)
  18. If you'd like to output RSS tags with attributes, such as `enclosure`, use something like the following in your `template`:
  19. "enclosure": {
  20. "_attributes": {
  21. "url": "{{media_url}}",
  22. "length": "1234456789",
  23. "type": "audio/mpeg"
  24. }
  25. },
  26. "another_tag": {
  27. "_attributes": {
  28. "key": "value",
  29. "another_key": "another_value"
  30. },
  31. "_contents": "tag contents (can be an object for nesting)"
  32. }
  33. MD
  34. end
  35. def default_options
  36. {
  37. "secrets" => ["a-secret-key"],
  38. "expected_receive_period_in_days" => 2,
  39. "template" => {
  40. "title" => "XKCD comics as a feed",
  41. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  42. "item" => {
  43. "title" => "{{title}}",
  44. "description" => "Secret hovertext: {{hovertext}}",
  45. "link" => "{{url}}"
  46. }
  47. }
  48. }
  49. end
  50. def working?
  51. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  52. end
  53. def validate_options
  54. unless options['secrets'].is_a?(Array) && options['secrets'].length > 0
  55. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  56. end
  57. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  58. errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
  59. end
  60. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  61. errors.add(:base, "Please provide template and template.item")
  62. end
  63. end
  64. def events_to_show
  65. (interpolated['events_to_show'].presence || 40).to_i
  66. end
  67. def feed_ttl
  68. (interpolated['ttl'].presence || 60).to_i
  69. end
  70. def feed_title
  71. interpolated['template']['title'].presence || "#{name} Event Feed"
  72. end
  73. def feed_link
  74. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  75. end
  76. def feed_description
  77. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  78. end
  79. def receive_web_request(params, method, format)
  80. if interpolated['secrets'].include?(params['secret'])
  81. items = received_events.order('id desc').limit(events_to_show).map do |event|
  82. interpolated = interpolate_options(options['template']['item'], event)
  83. interpolated['guid'] = event.id
  84. date_string = interpolated['pubDate'].to_s
  85. date =
  86. begin
  87. Time.zone.parse(date_string) # may return nil
  88. rescue => e
  89. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  90. nil
  91. end || event.created_at
  92. interpolated['pubDate'] = date.rfc2822.to_s
  93. interpolated
  94. end
  95. if format =~ /json/
  96. content = {
  97. 'title' => feed_title,
  98. 'description' => feed_description,
  99. 'pubDate' => Time.now,
  100. 'items' => simplify_item_for_json(items)
  101. }
  102. return [content, 200]
  103. else
  104. content = Utils.unindent(<<-XML)
  105. <?xml version="1.0" encoding="UTF-8" ?>
  106. <rss version="2.0">
  107. <channel>
  108. <title>#{feed_title.encode(:xml => :text)}</title>
  109. <description>#{feed_description.encode(:xml => :text)}</description>
  110. <link>#{feed_link.encode(:xml => :text)}</link>
  111. <lastBuildDate>#{Time.now.rfc2822.to_s.encode(:xml => :text)}</lastBuildDate>
  112. <pubDate>#{Time.now.rfc2822.to_s.encode(:xml => :text)}</pubDate>
  113. <ttl>#{feed_ttl}</ttl>
  114. XML
  115. content += simplify_item_for_xml(items).to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1).gsub(/^<\/?items>/, '').strip
  116. content += Utils.unindent(<<-XML)
  117. </channel>
  118. </rss>
  119. XML
  120. return [content, 200, 'text/xml']
  121. end
  122. else
  123. if format =~ /json/
  124. return [{ :error => "Not Authorized" }, 401]
  125. else
  126. return ["Not Authorized", 401]
  127. end
  128. end
  129. end
  130. private
  131. class XMLNode
  132. def initialize(tag_name, attributes, contents)
  133. @tag_name, @attributes, @contents = tag_name, attributes, contents
  134. end
  135. def to_xml(options)
  136. if @contents.is_a?(Hash)
  137. options[:builder].tag! @tag_name, @attributes do
  138. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  139. end
  140. else
  141. options[:builder].tag! @tag_name, @attributes, @contents
  142. end
  143. end
  144. end
  145. def simplify_item_for_xml(item)
  146. if item.is_a?(Hash)
  147. item.each.with_object({}) do |(key, value), memo|
  148. if value.is_a?(Hash)
  149. if value.key?('_attributes') || value.key?('_contents')
  150. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  151. else
  152. memo[key] = simplify_item_for_xml(value)
  153. end
  154. else
  155. memo[key] = value
  156. end
  157. end
  158. elsif item.is_a?(Array)
  159. item.map { |value| simplify_item_for_xml(value) }
  160. else
  161. item
  162. end
  163. end
  164. def simplify_item_for_json(item)
  165. if item.is_a?(Hash)
  166. item.each.with_object({}) do |(key, value), memo|
  167. if value.is_a?(Hash)
  168. if value.key?('_attributes') || value.key?('_contents')
  169. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  170. simplify_item_for_json(value['_contents'])
  171. elsif value['_contents']
  172. { "contents" => value['_contents'] }
  173. else
  174. {}
  175. end
  176. memo[key] = contents.merge(value['_attributes'] || {})
  177. else
  178. memo[key] = simplify_item_for_json(value)
  179. end
  180. else
  181. memo[key] = value
  182. end
  183. end
  184. elsif item.is_a?(Array)
  185. item.map { |value| simplify_item_for_json(value) }
  186. else
  187. item
  188. end
  189. end
  190. end
  191. end