Nessuna descrizione http://j1x-huginn.herokuapp.com

data_output_agent.rb 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 in the output
  39. #{description_events_order('events in the output')}
  40. # Liquid Templating
  41. In Liquid templating, the following variable is available:
  42. * `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}}`.
  43. MD
  44. end
  45. def default_options
  46. {
  47. "secrets" => ["a-secret-key"],
  48. "expected_receive_period_in_days" => 2,
  49. "template" => {
  50. "title" => "XKCD comics as a feed",
  51. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  52. "item" => {
  53. "title" => "{{title}}",
  54. "description" => "Secret hovertext: {{hovertext}}",
  55. "link" => "{{url}}"
  56. }
  57. },
  58. "ns_media" => "true"
  59. }
  60. end
  61. def working?
  62. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  63. end
  64. def validate_options
  65. if options['secrets'].is_a?(Array) && options['secrets'].length > 0
  66. options['secrets'].each do |secret|
  67. case secret
  68. when %r{[/.]}
  69. errors.add(:base, "secret may not contain a slash or dot")
  70. when String
  71. else
  72. errors.add(:base, "secret must be a string")
  73. end
  74. end
  75. else
  76. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  77. end
  78. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  79. 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")
  80. end
  81. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  82. errors.add(:base, "Please provide template and template.item")
  83. end
  84. case options['push_hubs']
  85. when nil
  86. when Array
  87. options['push_hubs'].each do |hub|
  88. case hub
  89. when /\{/
  90. # Liquid templating
  91. when String
  92. begin
  93. URI.parse(hub)
  94. rescue URI::Error
  95. errors.add(:base, "invalid URL found in push_hubs")
  96. break
  97. end
  98. else
  99. errors.add(:base, "push_hubs must be an array of endpoint URLs")
  100. break
  101. end
  102. end
  103. else
  104. errors.add(:base, "push_hubs must be an array")
  105. end
  106. end
  107. def events_to_show
  108. (interpolated['events_to_show'].presence || 40).to_i
  109. end
  110. def feed_ttl
  111. (interpolated['ttl'].presence || 60).to_i
  112. end
  113. def feed_title
  114. interpolated['template']['title'].presence || "#{name} Event Feed"
  115. end
  116. def feed_link
  117. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  118. end
  119. def feed_url(options = {})
  120. interpolated['template']['self'].presence ||
  121. feed_link + Rails.application.routes.url_helpers.
  122. web_requests_path(agent_id: id || ':id',
  123. user_id: user_id,
  124. secret: options[:secret],
  125. format: options[:format])
  126. end
  127. def feed_icon
  128. interpolated['template']['icon'].presence || feed_link + '/favicon.ico'
  129. end
  130. def feed_description
  131. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  132. end
  133. def xml_namespace
  134. namespaces = ['xmlns:atom="http://www.w3.org/2005/Atom"']
  135. if (boolify(interpolated['ns_media']))
  136. namespaces << 'xmlns:media="http://search.yahoo.com/mrss/"'
  137. end
  138. if (boolify(interpolated['ns_itunes']))
  139. namespaces << 'xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"'
  140. end
  141. namespaces.join(' ')
  142. end
  143. def push_hubs
  144. interpolated['push_hubs'].presence || []
  145. end
  146. def receive_web_request(params, method, format)
  147. unless interpolated['secrets'].include?(params['secret'])
  148. if format =~ /json/
  149. return [{ error: "Not Authorized" }, 401]
  150. else
  151. return ["Not Authorized", 401]
  152. end
  153. end
  154. source_events = sort_events(received_events.order(id: :desc).limit(events_to_show).to_a)
  155. interpolation_context.stack do
  156. interpolation_context['events'] = source_events
  157. items = source_events.map do |event|
  158. interpolated = interpolate_options(options['template']['item'], event)
  159. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  160. '_contents' => interpolated['guid'].presence || event.id}
  161. date_string = interpolated['pubDate'].to_s
  162. date =
  163. begin
  164. Time.zone.parse(date_string) # may return nil
  165. rescue => e
  166. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  167. nil
  168. end || event.created_at
  169. interpolated['pubDate'] = date.rfc2822.to_s
  170. interpolated
  171. end
  172. now = Time.now
  173. if format =~ /json/
  174. content = {
  175. 'title' => feed_title,
  176. 'description' => feed_description,
  177. 'pubDate' => now,
  178. 'items' => simplify_item_for_json(items)
  179. }
  180. return [content, 200]
  181. else
  182. hub_links = push_hubs.map { |hub|
  183. <<-XML
  184. <atom:link rel="hub" href=#{hub.encode(xml: :attr)}/>
  185. XML
  186. }.join
  187. items = simplify_item_for_xml(items)
  188. .to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1)
  189. .gsub(%r{^</?items>\n}, '')
  190. return [<<-XML, 200, 'text/xml']
  191. <?xml version="1.0" encoding="UTF-8" ?>
  192. <rss version="2.0" #{xml_namespace}>
  193. <channel>
  194. <atom:link href=#{feed_url(secret: params['secret'], format: :xml).encode(xml: :attr)} rel="self" type="application/rss+xml" />
  195. <atom:icon>#{feed_icon.encode(xml: :text)}</atom:icon>
  196. #{hub_links}
  197. <title>#{feed_title.encode(xml: :text)}</title>
  198. <description>#{feed_description.encode(xml: :text)}</description>
  199. <link>#{feed_link.encode(xml: :text)}</link>
  200. <lastBuildDate>#{now.rfc2822.to_s.encode(xml: :text)}</lastBuildDate>
  201. <pubDate>#{now.rfc2822.to_s.encode(xml: :text)}</pubDate>
  202. <ttl>#{feed_ttl}</ttl>
  203. #{items}
  204. </channel>
  205. </rss>
  206. XML
  207. end
  208. end
  209. end
  210. def receive(incoming_events)
  211. url = feed_url(secret: interpolated['secrets'].first, format: :xml)
  212. push_hubs.each do |hub|
  213. push_to_hub(hub, url)
  214. end
  215. end
  216. private
  217. class XMLNode
  218. def initialize(tag_name, attributes, contents)
  219. @tag_name, @attributes, @contents = tag_name, attributes, contents
  220. end
  221. def to_xml(options)
  222. if @contents.is_a?(Hash)
  223. options[:builder].tag! @tag_name, @attributes do
  224. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  225. end
  226. else
  227. options[:builder].tag! @tag_name, @attributes, @contents
  228. end
  229. end
  230. end
  231. def simplify_item_for_xml(item)
  232. if item.is_a?(Hash)
  233. item.each.with_object({}) do |(key, value), memo|
  234. if value.is_a?(Hash)
  235. if value.key?('_attributes') || value.key?('_contents')
  236. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  237. else
  238. memo[key] = simplify_item_for_xml(value)
  239. end
  240. else
  241. memo[key] = value
  242. end
  243. end
  244. elsif item.is_a?(Array)
  245. item.map { |value| simplify_item_for_xml(value) }
  246. else
  247. item
  248. end
  249. end
  250. def simplify_item_for_json(item)
  251. if item.is_a?(Hash)
  252. item.each.with_object({}) do |(key, value), memo|
  253. if value.is_a?(Hash)
  254. if value.key?('_attributes') || value.key?('_contents')
  255. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  256. simplify_item_for_json(value['_contents'])
  257. elsif value['_contents']
  258. { "contents" => value['_contents'] }
  259. else
  260. {}
  261. end
  262. memo[key] = contents.merge(value['_attributes'] || {})
  263. else
  264. memo[key] = simplify_item_for_json(value)
  265. end
  266. else
  267. memo[key] = value
  268. end
  269. end
  270. elsif item.is_a?(Array)
  271. item.map { |value| simplify_item_for_json(value) }
  272. else
  273. item
  274. end
  275. end
  276. def push_to_hub(hub, url)
  277. hub_uri =
  278. begin
  279. URI.parse(hub)
  280. rescue URI::Error
  281. nil
  282. end
  283. if !hub_uri.is_a?(URI::HTTP)
  284. error "Invalid push endpoint: #{hub}"
  285. return
  286. end
  287. log "Pushing #{url} to #{hub_uri}"
  288. return if dry_run?
  289. begin
  290. faraday.post hub_uri, {
  291. 'hub.mode' => 'publish',
  292. 'hub.url' => url
  293. }
  294. rescue => e
  295. error "Push failed: #{e.message}"
  296. end
  297. end
  298. end
  299. end