data_output_agent.rb 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. module Agents
  2. class DataOutputAgent < Agent
  3. include WebRequestConcern
  4. cannot_be_scheduled!
  5. cannot_create_events!
  6. description do
  7. <<-MD
  8. The Data Output Agent outputs received events as either RSS or JSON. Use it to output a public or private stream of Huginn data.
  9. This Agent will output data at:
  10. `https://#{ENV['DOMAIN']}#{Rails.application.routes.url_helpers.web_requests_path(agent_id: ':id', user_id: user_id, secret: ':secret', format: :xml)}`
  11. where `:secret` is one of the allowed secrets specified in your options and the extension can be `xml` or `json`.
  12. You can setup multiple secrets so that you can individually authorize external systems to
  13. access your Huginn data.
  14. Options:
  15. * `secrets` - An array of tokens that the requestor must provide for light-weight authentication.
  16. * `expected_receive_period_in_days` - How often you expect data to be received by this Agent from other Agents.
  17. * `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. Value of the `self` key will be used as URL for this feed itself, which is useful when you serve it via reverse proxy. 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.
  18. * `events_to_show` - The number of events to output in RSS or JSON. (default: `40`)
  19. * `ttl` - A value for the \\<ttl\\> element in RSS output. (default: `60`)
  20. * `ns_media` - Add [yahoo media namespace](https://en.wikipedia.org/wiki/Media_RSS) in output xml
  21. * `ns_itunes` - Add [itunes compatible namespace](http://lists.apple.com/archives/syndication-dev/2005/Nov/msg00002.html) in output xml
  22. * `push_hubs` - Set to a list of PubSubHubbub endpoints you want to publish an update to every time this agent receives an event. (default: none) Popular hubs include [Superfeedr](https://pubsubhubbub.superfeedr.com/) and [Google](https://pubsubhubbub.appspot.com/). Note that publishing updates will make your feed URL known to the public, so if you want to keep it secret, set up a reverse proxy to serve your feed via a safe URL and specify it in `template.self`.
  23. If you'd like to output RSS tags with attributes, such as `enclosure`, use something like the following in your `template`:
  24. "enclosure": {
  25. "_attributes": {
  26. "url": "{{media_url}}",
  27. "length": "1234456789",
  28. "type": "audio/mpeg"
  29. }
  30. },
  31. "another_tag": {
  32. "_attributes": {
  33. "key": "value",
  34. "another_key": "another_value"
  35. },
  36. "_contents": "tag contents (can be an object for nesting)"
  37. }
  38. # Ordering events
  39. #{description_events_order('events')}
  40. DataOutputAgent will select the last `events_to_show` entries of its received events sorted in the order specified by `events_order`, which is defaulted to the event creation time.
  41. So, if you have multiple source agents that may create many events in a run, you may want to either increase `events_to_show` to have a larger "window", or specify the `events_order` option to an appropriate value (like `date_published`) so events from various sources are properly mixed in the resulted feed.
  42. There is also an option `events_list_order` that only controls the order of events listed in the final output, without attempting to maintain a total order of received events. It has the same format as `events_order` and is defaulted to `#{Utils.jsonify(DEFAULT_EVENTS_ORDER['events_list_order'])}` so the selected events are listed in reverse order like most popular RSS feeds list their articles.
  43. # Liquid Templating
  44. In Liquid templating, the following variable is available:
  45. * `events`: An array of events being output, sorted in the given 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}}`.
  46. MD
  47. end
  48. def default_options
  49. {
  50. "secrets" => ["a-secret-key"],
  51. "expected_receive_period_in_days" => 2,
  52. "template" => {
  53. "title" => "XKCD comics as a feed",
  54. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  55. "item" => {
  56. "title" => "{{title}}",
  57. "description" => "Secret hovertext: {{hovertext}}",
  58. "link" => "{{url}}"
  59. }
  60. },
  61. "ns_media" => "true"
  62. }
  63. end
  64. def working?
  65. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  66. end
  67. def validate_options
  68. if options['secrets'].is_a?(Array) && options['secrets'].length > 0
  69. options['secrets'].each do |secret|
  70. case secret
  71. when %r{[/.]}
  72. errors.add(:base, "secret may not contain a slash or dot")
  73. when String
  74. else
  75. errors.add(:base, "secret must be a string")
  76. end
  77. end
  78. else
  79. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  80. end
  81. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  82. 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")
  83. end
  84. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  85. errors.add(:base, "Please provide template and template.item")
  86. end
  87. case options['push_hubs']
  88. when nil
  89. when Array
  90. options['push_hubs'].each do |hub|
  91. case hub
  92. when /\{/
  93. # Liquid templating
  94. when String
  95. begin
  96. URI.parse(hub)
  97. rescue URI::Error
  98. errors.add(:base, "invalid URL found in push_hubs")
  99. break
  100. end
  101. else
  102. errors.add(:base, "push_hubs must be an array of endpoint URLs")
  103. break
  104. end
  105. end
  106. else
  107. errors.add(:base, "push_hubs must be an array")
  108. end
  109. end
  110. def events_to_show
  111. (interpolated['events_to_show'].presence || 40).to_i
  112. end
  113. def feed_ttl
  114. (interpolated['ttl'].presence || 60).to_i
  115. end
  116. def feed_title
  117. interpolated['template']['title'].presence || "#{name} Event Feed"
  118. end
  119. def feed_link
  120. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  121. end
  122. def feed_url(options = {})
  123. interpolated['template']['self'].presence ||
  124. feed_link + Rails.application.routes.url_helpers.
  125. web_requests_path(agent_id: id || ':id',
  126. user_id: user_id,
  127. secret: options[:secret],
  128. format: options[:format])
  129. end
  130. def feed_icon
  131. interpolated['template']['icon'].presence || feed_link + '/favicon.ico'
  132. end
  133. def feed_description
  134. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  135. end
  136. def xml_namespace
  137. namespaces = ['xmlns:atom="http://www.w3.org/2005/Atom"']
  138. if (boolify(interpolated['ns_media']))
  139. namespaces << 'xmlns:media="http://search.yahoo.com/mrss/"'
  140. end
  141. if (boolify(interpolated['ns_itunes']))
  142. namespaces << 'xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"'
  143. end
  144. namespaces.join(' ')
  145. end
  146. def push_hubs
  147. interpolated['push_hubs'].presence || []
  148. end
  149. DEFAULT_EVENTS_ORDER = {
  150. 'events_order' => nil,
  151. 'events_list_order' => [["{{_index_}}", "number", true]],
  152. }
  153. def events_order(key = SortableEvents::EVENTS_ORDER_KEY)
  154. super || DEFAULT_EVENTS_ORDER[key]
  155. end
  156. def latest_events(reload = false)
  157. received_events = received_events().reorder(id: :asc)
  158. events =
  159. if (event_ids = memory[:event_ids]) &&
  160. memory[:events_order] == events_order &&
  161. memory[:events_to_show] >= events_to_show
  162. received_events.where(id: event_ids).to_a
  163. else
  164. memory[:last_event_id] = nil
  165. reload = true
  166. []
  167. end
  168. if reload
  169. memory[:events_order] = events_order
  170. memory[:events_to_show] = events_to_show
  171. new_events =
  172. if last_event_id = memory[:last_event_id]
  173. received_events.where(Event.arel_table[:id].gt(last_event_id)).to_a
  174. else
  175. source_ids.flat_map { |source_id|
  176. # dig twice as many events as the number of
  177. # `events_to_show`
  178. received_events.where(agent_id: source_id).
  179. last(2 * events_to_show)
  180. }.sort_by(&:id)
  181. end
  182. unless new_events.empty?
  183. memory[:last_event_id] = new_events.last.id
  184. events.concat(new_events)
  185. end
  186. end
  187. events = sort_events(events).last(events_to_show)
  188. if reload
  189. memory[:event_ids] = events.map(&:id)
  190. end
  191. events
  192. end
  193. def receive_web_request(params, method, format)
  194. unless interpolated['secrets'].include?(params['secret'])
  195. if format =~ /json/
  196. return [{ error: "Not Authorized" }, 401]
  197. else
  198. return ["Not Authorized", 401]
  199. end
  200. end
  201. source_events = sort_events(latest_events(), 'events_list_order')
  202. interpolation_context.stack do
  203. interpolation_context['events'] = source_events
  204. items = source_events.map do |event|
  205. interpolated = interpolate_options(options['template']['item'], event)
  206. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  207. '_contents' => interpolated['guid'].presence || event.id}
  208. date_string = interpolated['pubDate'].to_s
  209. date =
  210. begin
  211. Time.zone.parse(date_string) # may return nil
  212. rescue => e
  213. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  214. nil
  215. end || event.created_at
  216. interpolated['pubDate'] = date.rfc2822.to_s
  217. interpolated
  218. end
  219. now = Time.now
  220. if format =~ /json/
  221. content = {
  222. 'title' => feed_title,
  223. 'description' => feed_description,
  224. 'pubDate' => now,
  225. 'items' => simplify_item_for_json(items)
  226. }
  227. return [content, 200]
  228. else
  229. hub_links = push_hubs.map { |hub|
  230. <<-XML
  231. <atom:link rel="hub" href=#{hub.encode(xml: :attr)}/>
  232. XML
  233. }.join
  234. items = simplify_item_for_xml(items)
  235. .to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1)
  236. .gsub(%r{^</?items>\n}, '')
  237. return [<<-XML, 200, 'text/xml']
  238. <?xml version="1.0" encoding="UTF-8" ?>
  239. <rss version="2.0" #{xml_namespace}>
  240. <channel>
  241. <atom:link href=#{feed_url(secret: params['secret'], format: :xml).encode(xml: :attr)} rel="self" type="application/rss+xml" />
  242. <atom:icon>#{feed_icon.encode(xml: :text)}</atom:icon>
  243. #{hub_links}
  244. <title>#{feed_title.encode(xml: :text)}</title>
  245. <description>#{feed_description.encode(xml: :text)}</description>
  246. <link>#{feed_link.encode(xml: :text)}</link>
  247. <lastBuildDate>#{now.rfc2822.to_s.encode(xml: :text)}</lastBuildDate>
  248. <pubDate>#{now.rfc2822.to_s.encode(xml: :text)}</pubDate>
  249. <ttl>#{feed_ttl}</ttl>
  250. #{items}
  251. </channel>
  252. </rss>
  253. XML
  254. end
  255. end
  256. end
  257. def receive(incoming_events)
  258. url = feed_url(secret: interpolated['secrets'].first, format: :xml)
  259. # Reload new events and update cache
  260. latest_events(true)
  261. push_hubs.each do |hub|
  262. push_to_hub(hub, url)
  263. end
  264. end
  265. private
  266. class XMLNode
  267. def initialize(tag_name, attributes, contents)
  268. @tag_name, @attributes, @contents = tag_name, attributes, contents
  269. end
  270. def to_xml(options)
  271. if @contents.is_a?(Hash)
  272. options[:builder].tag! @tag_name, @attributes do
  273. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  274. end
  275. else
  276. options[:builder].tag! @tag_name, @attributes, @contents
  277. end
  278. end
  279. end
  280. def simplify_item_for_xml(item)
  281. if item.is_a?(Hash)
  282. item.each.with_object({}) do |(key, value), memo|
  283. if value.is_a?(Hash)
  284. if value.key?('_attributes') || value.key?('_contents')
  285. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  286. else
  287. memo[key] = simplify_item_for_xml(value)
  288. end
  289. else
  290. memo[key] = value
  291. end
  292. end
  293. elsif item.is_a?(Array)
  294. item.map { |value| simplify_item_for_xml(value) }
  295. else
  296. item
  297. end
  298. end
  299. def simplify_item_for_json(item)
  300. if item.is_a?(Hash)
  301. item.each.with_object({}) do |(key, value), memo|
  302. if value.is_a?(Hash)
  303. if value.key?('_attributes') || value.key?('_contents')
  304. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  305. simplify_item_for_json(value['_contents'])
  306. elsif value['_contents']
  307. { "contents" => value['_contents'] }
  308. else
  309. {}
  310. end
  311. memo[key] = contents.merge(value['_attributes'] || {})
  312. else
  313. memo[key] = simplify_item_for_json(value)
  314. end
  315. else
  316. memo[key] = value
  317. end
  318. end
  319. elsif item.is_a?(Array)
  320. item.map { |value| simplify_item_for_json(value) }
  321. else
  322. item
  323. end
  324. end
  325. def push_to_hub(hub, url)
  326. hub_uri =
  327. begin
  328. URI.parse(hub)
  329. rescue URI::Error
  330. nil
  331. end
  332. if !hub_uri.is_a?(URI::HTTP)
  333. error "Invalid push endpoint: #{hub}"
  334. return
  335. end
  336. log "Pushing #{url} to #{hub_uri}"
  337. return if dry_run?
  338. begin
  339. faraday.post hub_uri, {
  340. 'hub.mode' => 'publish',
  341. 'hub.url' => url
  342. }
  343. rescue => e
  344. error "Push failed: #{e.message}"
  345. end
  346. end
  347. end
  348. end