file_handling.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. module FileHandling
  2. extend ActiveSupport::Concern
  3. def get_file_pointer(file)
  4. { file_pointer: { file: file, agent_id: id } }
  5. end
  6. def has_file_pointer?(event)
  7. event.payload['file_pointer'] &&
  8. event.payload['file_pointer']['file'] &&
  9. event.payload['file_pointer']['agent_id']
  10. end
  11. def get_io(event)
  12. return nil unless has_file_pointer?(event)
  13. event.user.agents.find(event.payload['file_pointer']['agent_id']).get_io(event.payload['file_pointer']['file'])
  14. end
  15. def get_upload_io(event)
  16. Faraday::UploadIO.new(get_io(event), MIME::Types.type_for(File.basename(event.payload['file_pointer']['file'])).first.try(:content_type))
  17. end
  18. def emitting_file_handling_agent_description
  19. @emitting_file_handling_agent_description ||=
  20. "This agent only emits a 'file pointer', not the data inside the files, the following agents can consume the created events: `#{receiving_file_handling_agents.join('`, `')}`. Read more about the concept in the [wiki](https://github.com/huginn/huginn/wiki/How-Huginn-works-with-files)."
  21. end
  22. def receiving_file_handling_agent_description
  23. @receiving_file_handling_agent_description ||=
  24. "This agent can consume a 'file pointer' event from the following agents with no additional configuration: `#{emitting_file_handling_agents.join('`, `')}`. Read more about the concept in the [wiki](https://github.com/huginn/huginn/wiki/How-Huginn-works-with-files)."
  25. end
  26. private
  27. def emitting_file_handling_agents
  28. emitting_file_handling_agents = file_handling_agents.select { |a| a.emits_file_pointer? }
  29. emitting_file_handling_agents.map { |a| a.to_s.demodulize }
  30. end
  31. def receiving_file_handling_agents
  32. receiving_file_handling_agents = file_handling_agents.select { |a| a.consumes_file_pointer? }
  33. receiving_file_handling_agents.map { |a| a.to_s.demodulize }
  34. end
  35. def file_handling_agents
  36. @file_handling_agents ||= Agent.types.select{ |c| c.included_modules.include?(FileHandling) }.map { |d| d.name.constantize }
  37. end
  38. module ClassMethods
  39. def emits_file_pointer!
  40. @emits_file_pointer = true
  41. end
  42. def emits_file_pointer?
  43. !!@emits_file_pointer
  44. end
  45. def consumes_file_pointer!
  46. @consumes_file_pointer = true
  47. end
  48. def consumes_file_pointer?
  49. !!@consumes_file_pointer
  50. end
  51. end
  52. end