channel.rb 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Channel < ApplicationModel
  3. include Channel::Assets
  4. belongs_to :group
  5. store :options
  6. store :preferences
  7. after_create :email_address_check
  8. after_update :email_address_check
  9. after_destroy :email_address_check
  10. # rubocop:disable Style/ClassVars
  11. @@channel_stream = {}
  12. @@channel_stream_started_till_at = {}
  13. # rubocop:enable Style/ClassVars
  14. =begin
  15. fetch all accounts
  16. Channel.fetch
  17. =end
  18. def self.fetch
  19. channels = Channel.where('active = ? AND area LIKE ?', true, '%::Account')
  20. channels.each(&:fetch)
  21. end
  22. =begin
  23. fetch one account
  24. channel = Channel.where(area: 'Email::Account').first
  25. channel.fetch
  26. =end
  27. def fetch(force = false)
  28. adapter = options[:adapter]
  29. adapter_options = options
  30. if options[:inbound] && options[:inbound][:adapter]
  31. adapter = options[:inbound][:adapter]
  32. adapter_options = options[:inbound][:options]
  33. end
  34. begin
  35. driver_class = self.class.driver_class(adapter)
  36. driver_instance = driver_class.new
  37. return if !force && !driver_instance.fetchable?(self)
  38. result = driver_instance.fetch(adapter_options, self)
  39. self.status_in = result[:result]
  40. self.last_log_in = result[:notice]
  41. preferences[:last_fetch] = Time.zone.now
  42. save!
  43. rescue => e
  44. error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}"
  45. logger.error error
  46. logger.error e.backtrace
  47. self.status_in = 'error'
  48. self.last_log_in = error
  49. preferences[:last_fetch] = Time.zone.now
  50. save!
  51. end
  52. end
  53. =begin
  54. stream instance of account
  55. channel = Channel.where(area: 'Twitter::Account').first
  56. stream_instance = channel.stream_instance
  57. # start stream
  58. stream_instance.stream
  59. =end
  60. def stream_instance
  61. adapter = options[:adapter]
  62. begin
  63. driver_class = self.class.driver_class(adapter)
  64. driver_instance = driver_class.new
  65. # check is stream exists
  66. return if !driver_instance.respond_to?(:stream_instance)
  67. driver_instance.stream_instance(self)
  68. # set scheduler job to active
  69. return driver_instance
  70. rescue => e
  71. error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}"
  72. logger.error error
  73. logger.error e.backtrace
  74. self.status_in = 'error'
  75. self.last_log_in = error
  76. save!
  77. end
  78. end
  79. =begin
  80. stream all accounts
  81. Channel.stream
  82. =end
  83. def self.stream
  84. Thread.abort_on_exception = true
  85. auto_reconnect_after = 180
  86. delay_before_reconnect = 70
  87. last_channels = []
  88. loop do
  89. logger.debug { 'stream controll loop' }
  90. current_channels = []
  91. channels = Channel.where('active = ? AND area LIKE ?', true, '%::Account')
  92. channels.each do |channel|
  93. adapter = channel.options[:adapter]
  94. next if adapter.blank?
  95. driver_class = self.driver_class(adapter)
  96. next if !driver_class.respond_to?(:streamable?)
  97. next if !driver_class.streamable?
  98. channel_id = channel.id.to_s
  99. current_channels.push channel_id
  100. # exit it channel has changed or connection is older then 180 minutes
  101. if @@channel_stream[channel_id].present?
  102. if @@channel_stream[channel_id][:options] != channel.options
  103. logger.info "channel options (#{channel.id}) has changed, stop stream thread"
  104. @@channel_stream[channel_id][:thread].exit
  105. @@channel_stream[channel_id][:thread].join
  106. @@channel_stream[channel_id][:stream_instance].disconnect
  107. @@channel_stream.delete(channel_id)
  108. @@channel_stream_started_till_at[channel_id] = Time.zone.now
  109. next
  110. elsif @@channel_stream[channel_id][:started_at] && @@channel_stream[channel_id][:started_at] < Time.zone.now - auto_reconnect_after.minutes
  111. logger.info "channel (#{channel.id}) reconnect - stream thread is older then #{auto_reconnect_after} minutes, restart thread"
  112. @@channel_stream[channel_id][:thread].exit
  113. @@channel_stream[channel_id][:thread].join
  114. @@channel_stream[channel_id][:stream_instance].disconnect
  115. @@channel_stream.delete(channel_id)
  116. @@channel_stream_started_till_at[channel_id] = Time.zone.now
  117. next
  118. end
  119. end
  120. local_delay_before_reconnect = delay_before_reconnect
  121. if channel.status_in == 'error'
  122. local_delay_before_reconnect = local_delay_before_reconnect * 2
  123. end
  124. if @@channel_stream[channel_id].blank? && @@channel_stream_started_till_at[channel_id].present?
  125. wait_in_seconds = @@channel_stream_started_till_at[channel_id] - (Time.zone.now - local_delay_before_reconnect.seconds)
  126. if wait_in_seconds.positive?
  127. logger.info "skipp channel (#{channel_id}) for streaming, already tried to connect or connection was active within the last #{local_delay_before_reconnect} seconds - wait another #{wait_in_seconds} seconds"
  128. next
  129. end
  130. end
  131. #logger.info "thread stream for channel (#{channel.id}) already running" if @@channel_stream[channel_id].present?
  132. next if @@channel_stream[channel_id].present?
  133. @@channel_stream[channel_id] = {
  134. options: channel.options,
  135. started_at: Time.zone.now,
  136. }
  137. # start channels with delay
  138. sleep @@channel_stream.count
  139. # start threads for each channel
  140. @@channel_stream[channel_id][:thread] = Thread.new do
  141. begin
  142. logger.info "Started stream channel for '#{channel.id}' (#{channel.area})..."
  143. channel.status_in = 'ok'
  144. channel.last_log_in = ''
  145. channel.save!
  146. @@channel_stream_started_till_at[channel_id] = Time.zone.now
  147. @@channel_stream[channel_id] ||= {}
  148. @@channel_stream[channel_id][:stream_instance] = channel.stream_instance
  149. @@channel_stream[channel_id][:stream_instance].stream
  150. @@channel_stream[channel_id][:stream_instance].disconnect
  151. @@channel_stream.delete(channel_id)
  152. @@channel_stream_started_till_at[channel_id] = Time.zone.now
  153. logger.info " ...stopped stream thread for '#{channel.id}'"
  154. rescue => e
  155. error = "Can't use stream for channel (#{channel.id}): #{e.inspect}"
  156. logger.error error
  157. logger.error e.backtrace
  158. channel.status_in = 'error'
  159. channel.last_log_in = error
  160. channel.save!
  161. @@channel_stream.delete(channel_id)
  162. @@channel_stream_started_till_at[channel_id] = Time.zone.now
  163. end
  164. end
  165. end
  166. # cleanup deleted channels
  167. last_channels.each do |channel_id|
  168. next if @@channel_stream[channel_id].blank?
  169. next if current_channels.include?(channel_id)
  170. logger.info "channel (#{channel_id}) not longer active, stop stream thread"
  171. @@channel_stream[channel_id][:thread].exit
  172. @@channel_stream[channel_id][:thread].join
  173. @@channel_stream[channel_id][:stream_instance].disconnect
  174. @@channel_stream.delete(channel_id)
  175. @@channel_stream_started_till_at[channel_id] = Time.zone.now
  176. end
  177. last_channels = current_channels
  178. sleep 20
  179. end
  180. end
  181. =begin
  182. send via account
  183. channel = Channel.where(area: 'Email::Account').first
  184. channel.deliver(params, notification)
  185. =end
  186. def deliver(params, notification = false)
  187. adapter = options[:adapter]
  188. adapter_options = options
  189. if options[:outbound] && options[:outbound][:adapter]
  190. adapter = options[:outbound][:adapter]
  191. adapter_options = options[:outbound][:options]
  192. end
  193. result = nil
  194. begin
  195. driver_class = self.class.driver_class(adapter)
  196. driver_instance = driver_class.new
  197. result = driver_instance.send(adapter_options, params, notification)
  198. self.status_out = 'ok'
  199. self.last_log_out = ''
  200. save!
  201. rescue => e
  202. error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}"
  203. logger.error error
  204. logger.error e.backtrace
  205. self.status_out = 'error'
  206. self.last_log_out = error
  207. save!
  208. raise error
  209. end
  210. result
  211. end
  212. =begin
  213. process via account
  214. channel = Channel.where(area: 'Email::Account').first
  215. channel.process(params)
  216. =end
  217. def process(params)
  218. adapter = options[:adapter]
  219. adapter_options = options
  220. if options[:inbound] && options[:inbound][:adapter]
  221. adapter = options[:inbound][:adapter]
  222. adapter_options = options[:inbound][:options]
  223. end
  224. result = nil
  225. begin
  226. driver_class = self.class.driver_class(adapter)
  227. driver_instance = driver_class.new
  228. result = driver_instance.process(adapter_options, params, self)
  229. self.status_in = 'ok'
  230. self.last_log_in = ''
  231. save!
  232. rescue => e
  233. error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}"
  234. logger.error error
  235. logger.error e.backtrace
  236. self.status_in = 'error'
  237. self.last_log_in = error
  238. save!
  239. raise e, error
  240. end
  241. result
  242. end
  243. =begin
  244. load channel driver and return class
  245. klass = Channel.driver_class('Imap')
  246. =end
  247. def self.driver_class(adapter)
  248. # we need to require each channel backend individually otherwise we get a
  249. # 'warning: toplevel constant Twitter referenced by Channel::Driver::Twitter' error e.g.
  250. # so we have to convert the channel name to the filename via Rails String.underscore
  251. # http://stem.ps/rails/2015/01/25/ruby-gotcha-toplevel-constant-referenced-by.html
  252. require_dependency "channel/driver/#{adapter.to_filename}"
  253. Object.const_get("::Channel::Driver::#{adapter.to_classname}")
  254. end
  255. =begin
  256. get instance of channel driver
  257. channel.driver_instance
  258. =end
  259. def driver_instance
  260. self.class.driver_class(options[:adapter])
  261. end
  262. private
  263. def email_address_check
  264. # reset non existing channel_ids
  265. EmailAddress.channel_cleanup
  266. end
  267. end