Nenhuma Descrição http://j1x-huginn.herokuapp.com

data_output_agent.rb 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. Values of the `link`, `title`, `description` and `icon` keys will be put into the <channel> section of RSS output. 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. # Liquid Templating
  34. In Liquid templating, the following variable is available:
  35. * `events`: An array of events being output, sorted in descending order up to `events_to_show` in number. For example, if source events contain a site title in the `site_title` key, you can refer to it in `template.title` by putting `{{events.first.site_title}}`.
  36. MD
  37. end
  38. def default_options
  39. {
  40. "secrets" => ["a-secret-key"],
  41. "expected_receive_period_in_days" => 2,
  42. "template" => {
  43. "title" => "XKCD comics as a feed",
  44. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  45. "item" => {
  46. "title" => "{{title}}",
  47. "description" => "Secret hovertext: {{hovertext}}",
  48. "link" => "{{url}}"
  49. }
  50. }
  51. }
  52. end
  53. def working?
  54. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  55. end
  56. def validate_options
  57. if options['secrets'].is_a?(Array) && options['secrets'].length > 0
  58. options['secrets'].each do |secret|
  59. case secret
  60. when %r{[/.]}
  61. errors.add(:base, "secret may not contain a slash or dot")
  62. when String
  63. else
  64. errors.add(:base, "secret must be a string")
  65. end
  66. end
  67. else
  68. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  69. end
  70. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  71. 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")
  72. end
  73. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  74. errors.add(:base, "Please provide template and template.item")
  75. end
  76. end
  77. def events_to_show
  78. (interpolated['events_to_show'].presence || 40).to_i
  79. end
  80. def feed_ttl
  81. (interpolated['ttl'].presence || 60).to_i
  82. end
  83. def feed_title
  84. interpolated['template']['title'].presence || "#{name} Event Feed"
  85. end
  86. def feed_link
  87. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  88. end
  89. def feed_url(options = {})
  90. feed_link + Rails.application.routes.url_helpers.
  91. web_requests_path(agent_id: id || '<id>',
  92. user_id: user_id,
  93. secret: options[:secret],
  94. format: options[:format])
  95. end
  96. def feed_icon
  97. interpolated['template']['icon'].presence || feed_link + '/favicon.ico'
  98. end
  99. def feed_description
  100. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  101. end
  102. def receive_web_request(params, method, format)
  103. unless interpolated['secrets'].include?(params['secret'])
  104. if format =~ /json/
  105. return [{ error: "Not Authorized" }, 401]
  106. else
  107. return ["Not Authorized", 401]
  108. end
  109. end
  110. source_events = received_events.order(id: :desc).limit(events_to_show).to_a
  111. interpolation_context.stack do
  112. interpolation_context['events'] = source_events
  113. items = source_events.map do |event|
  114. interpolated = interpolate_options(options['template']['item'], event)
  115. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  116. '_contents' => interpolated['guid'].presence || event.id}
  117. date_string = interpolated['pubDate'].to_s
  118. date =
  119. begin
  120. Time.zone.parse(date_string) # may return nil
  121. rescue => e
  122. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  123. nil
  124. end || event.created_at
  125. interpolated['pubDate'] = date.rfc2822.to_s
  126. interpolated
  127. end
  128. if format =~ /json/
  129. content = {
  130. 'title' => feed_title,
  131. 'description' => feed_description,
  132. 'pubDate' => Time.now,
  133. 'items' => simplify_item_for_json(items)
  134. }
  135. return [content, 200]
  136. else
  137. content = Utils.unindent(<<-XML)
  138. <?xml version="1.0" encoding="UTF-8" ?>
  139. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  140. <channel>
  141. <atom:link href=#{feed_url(secret: params['secret'], format: :xml).encode(xml: :attr)} rel="self" type="application/rss+xml" />
  142. <atom:icon>#{feed_icon.encode(xml: :text)}</atom:icon>
  143. <title>#{feed_title.encode(xml: :text)}</title>
  144. <description>#{feed_description.encode(xml: :text)}</description>
  145. <link>#{feed_link.encode(xml: :text)}</link>
  146. <lastBuildDate>#{Time.now.rfc2822.to_s.encode(xml: :text)}</lastBuildDate>
  147. <pubDate>#{Time.now.rfc2822.to_s.encode(xml: :text)}</pubDate>
  148. <ttl>#{feed_ttl}</ttl>
  149. XML
  150. content += simplify_item_for_xml(items).to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1).gsub(/^<\/?items>/, '').strip
  151. content += Utils.unindent(<<-XML)
  152. </channel>
  153. </rss>
  154. XML
  155. return [content, 200, 'text/xml']
  156. end
  157. end
  158. end
  159. private
  160. class XMLNode
  161. def initialize(tag_name, attributes, contents)
  162. @tag_name, @attributes, @contents = tag_name, attributes, contents
  163. end
  164. def to_xml(options)
  165. if @contents.is_a?(Hash)
  166. options[:builder].tag! @tag_name, @attributes do
  167. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  168. end
  169. else
  170. options[:builder].tag! @tag_name, @attributes, @contents
  171. end
  172. end
  173. end
  174. def simplify_item_for_xml(item)
  175. if item.is_a?(Hash)
  176. item.each.with_object({}) do |(key, value), memo|
  177. if value.is_a?(Hash)
  178. if value.key?('_attributes') || value.key?('_contents')
  179. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  180. else
  181. memo[key] = simplify_item_for_xml(value)
  182. end
  183. else
  184. memo[key] = value
  185. end
  186. end
  187. elsif item.is_a?(Array)
  188. item.map { |value| simplify_item_for_xml(value) }
  189. else
  190. item
  191. end
  192. end
  193. def simplify_item_for_json(item)
  194. if item.is_a?(Hash)
  195. item.each.with_object({}) do |(key, value), memo|
  196. if value.is_a?(Hash)
  197. if value.key?('_attributes') || value.key?('_contents')
  198. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  199. simplify_item_for_json(value['_contents'])
  200. elsif value['_contents']
  201. { "contents" => value['_contents'] }
  202. else
  203. {}
  204. end
  205. memo[key] = contents.merge(value['_attributes'] || {})
  206. else
  207. memo[key] = simplify_item_for_json(value)
  208. end
  209. else
  210. memo[key] = value
  211. end
  212. end
  213. elsif item.is_a?(Array)
  214. item.map { |value| simplify_item_for_json(value) }
  215. else
  216. item
  217. end
  218. end
  219. end
  220. end