Merge branch 'develop' of git.znuny.com:zammad/zammad into develop

This commit is contained in:
Martin Edenhofer 2017-10-02 15:07:22 +02:00
commit 4c7309303f
287 changed files with 2093 additions and 2021 deletions

View file

@ -99,14 +99,6 @@ Style/EmptyLinesAroundModuleBody:
Description: "Keeps track of empty lines around module bodies." Description: "Keeps track of empty lines around module bodies."
Enabled: false Enabled: false
Style/BlockDelimiters:
Description: >-
Avoid using {...} for multi-line blocks (multiline chaining is
always ugly).
Prefer {...} over do...end for single-line blocks.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks'
Enabled: false
Style/MultilineBlockChain: Style/MultilineBlockChain:
Description: 'Avoid multi-line chains of blocks.' Description: 'Avoid multi-line chains of blocks.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks' StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks'

View file

@ -44,12 +44,12 @@ module ApplicationController::HandlesErrors
respond_to do |format| respond_to do |format|
format.json { render json: humanize_error(e.message), status: status } format.json { render json: humanize_error(e.message), status: status }
format.any { format.any do
@exception = e @exception = e
@traceback = !Rails.env.production? @traceback = !Rails.env.production?
file = File.open(Rails.root.join('public', "#{status_code}.html"), 'r') file = File.open(Rails.root.join('public', "#{status_code}.html"), 'r')
render inline: file.read, status: status render inline: file.read, status: status
} end
end end
end end

View file

@ -22,14 +22,14 @@ module ApplicationController::LogsHttpAccess
content_encoding: request.headers['Content-Encoding'], content_encoding: request.headers['Content-Encoding'],
source: request.headers['User-Agent'] || request.headers['Server'], source: request.headers['User-Agent'] || request.headers['Server'],
} }
request.headers.each { |key, value| request.headers.each do |key, value|
next if key[0, 5] != 'HTTP_' next if key[0, 5] != 'HTTP_'
request_data[:content] += if key == 'HTTP_COOKIE' request_data[:content] += if key == 'HTTP_COOKIE'
"#{key}: xxxxx\n" "#{key}: xxxxx\n"
else else
"#{key}: #{value}\n" "#{key}: #{value}\n"
end end
} end
body = request.body.read body = request.body.read
if body if body
request_data[:content] += "\n" + body request_data[:content] += "\n" + body
@ -44,9 +44,9 @@ module ApplicationController::LogsHttpAccess
content_encoding: nil, content_encoding: nil,
source: nil, source: nil,
} }
response.headers.each { |key, value| response.headers.each do |key, value|
response_data[:content] += "#{key}: #{value}\n" response_data[:content] += "#{key}: #{value}\n"
} end
body = response.body body = response.body
if body if body
response_data[:content] += "\n" + body response_data[:content] += "\n" + body

View file

@ -111,9 +111,9 @@ module ApplicationController::RendersModels
if params[:expand] if params[:expand]
list = [] list = []
generic_objects.each { |generic_object| generic_objects.each do |generic_object|
list.push generic_object.attributes_with_association_names list.push generic_object.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -121,10 +121,10 @@ module ApplicationController::RendersModels
if params[:full] if params[:full]
assets = {} assets = {}
item_ids = [] item_ids = []
generic_objects.each { |item| generic_objects.each do |item|
item_ids.push item.id item_ids.push item.id
assets = item.assets(assets) assets = item.assets(assets)
} end
render json: { render json: {
record_ids: item_ids, record_ids: item_ids,
assets: assets, assets: assets,
@ -133,9 +133,9 @@ module ApplicationController::RendersModels
end end
generic_objects_with_associations = [] generic_objects_with_associations = []
generic_objects.each { |item| generic_objects.each do |item|
generic_objects_with_associations.push item.attributes_with_association_ids generic_objects_with_associations.push item.attributes_with_association_ids
} end
model_index_render_result(generic_objects_with_associations) model_index_render_result(generic_objects_with_associations)
end end

View file

@ -8,7 +8,7 @@ class ApplicationsController < ApplicationController
if params[:full] if params[:full]
assets = {} assets = {}
item_ids = [] item_ids = []
all.each { |item| all.each do |item|
item_ids.push item.id item_ids.push item.id
if !assets[:Application] if !assets[:Application]
assets[:Application] = {} assets[:Application] = {}
@ -16,7 +16,7 @@ class ApplicationsController < ApplicationController
application = item.attributes application = item.attributes
application[:clients] = Doorkeeper::AccessToken.where(application_id: item.id).count application[:clients] = Doorkeeper::AccessToken.where(application_id: item.id).count
assets[:Application][item.id] = application assets[:Application][item.id] = application
} end
render json: { render json: {
record_ids: item_ids, record_ids: item_ids,
assets: assets, assets: assets,

View file

@ -8,10 +8,10 @@ class CalendarsController < ApplicationController
# calendars # calendars
assets = {} assets = {}
calendar_ids = [] calendar_ids = []
Calendar.all.order(:name, :created_at).each { |calendar| Calendar.all.order(:name, :created_at).each do |calendar|
calendar_ids.push calendar.id calendar_ids.push calendar.id
assets = calendar.assets(assets) assets = calendar.assets(assets)
} end
ical_feeds = Calendar.ical_feeds ical_feeds = Calendar.ical_feeds
timezones = Calendar.timezones timezones = Calendar.timezones

View file

@ -11,12 +11,12 @@ class ChannelsEmailController < ApplicationController
not_used_email_address_ids = [] not_used_email_address_ids = []
accounts_fixed = [] accounts_fixed = []
assets = {} assets = {}
Channel.order(:id).each { |channel| Channel.order(:id).each do |channel|
if system_online_service && channel.preferences && channel.preferences['online_service_disable'] if system_online_service && channel.preferences && channel.preferences['online_service_disable']
email_addresses = EmailAddress.where(channel_id: channel.id) email_addresses = EmailAddress.where(channel_id: channel.id)
email_addresses.each { |email_address| email_addresses.each do |email_address|
accounts_fixed.push email_address accounts_fixed.push email_address
} end
next next
end end
if channel.area == 'Email::Account' if channel.area == 'Email::Account'
@ -26,15 +26,15 @@ class ChannelsEmailController < ApplicationController
notification_channel_ids.push channel.id notification_channel_ids.push channel.id
assets = channel.assets(assets) assets = channel.assets(assets)
end end
} end
EmailAddress.all.each { |email_address| EmailAddress.all.each do |email_address|
next if system_online_service && email_address.preferences && email_address.preferences['online_service_disable'] next if system_online_service && email_address.preferences && email_address.preferences['online_service_disable']
email_address_ids.push email_address.id email_address_ids.push email_address.id
assets = email_address.assets(assets) assets = email_address.assets(assets)
if !email_address.channel_id || !email_address.active || !Channel.find_by(id: email_address.channel_id) if !email_address.channel_id || !email_address.active || !Channel.find_by(id: email_address.channel_id)
not_used_email_address_ids.push email_address.id not_used_email_address_ids.push email_address.id
end end
} end
render json: { render json: {
accounts_fixed: accounts_fixed, accounts_fixed: accounts_fixed,
assets: assets, assets: assets,
@ -224,7 +224,7 @@ class ChannelsEmailController < ApplicationController
# save settings # save settings
if result[:result] == 'ok' if result[:result] == 'ok'
Channel.where(area: 'Email::Notification').each { |channel| Channel.where(area: 'Email::Notification').each do |channel|
active = false active = false
if adapter =~ /^#{channel.options[:outbound][:adapter]}$/i if adapter =~ /^#{channel.options[:outbound][:adapter]}$/i
active = true active = true
@ -239,7 +239,7 @@ class ChannelsEmailController < ApplicationController
end end
channel.active = active channel.active = active
channel.save channel.save
} end
end end
render json: result render json: result
end end
@ -247,7 +247,7 @@ class ChannelsEmailController < ApplicationController
private private
def account_duplicate?(result, channel_id = nil) def account_duplicate?(result, channel_id = nil)
Channel.where(area: 'Email::Account').each { |channel| Channel.where(area: 'Email::Account').each do |channel|
next if !channel.options next if !channel.options
next if !channel.options[:inbound] next if !channel.options[:inbound]
next if !channel.options[:inbound][:adapter] next if !channel.options[:inbound][:adapter]
@ -261,7 +261,7 @@ class ChannelsEmailController < ApplicationController
message: 'Account already exists!', message: 'Account already exists!',
} }
return true return true
} end
false false
end end

View file

@ -5,14 +5,14 @@ class ChannelsFacebookController < ApplicationController
def index def index
assets = {} assets = {}
ExternalCredential.where(name: 'facebook').each { |external_credential| ExternalCredential.where(name: 'facebook').each do |external_credential|
assets = external_credential.assets(assets) assets = external_credential.assets(assets)
} end
channel_ids = [] channel_ids = []
Channel.where(area: 'Facebook::Account').order(:id).each { |channel| Channel.where(area: 'Facebook::Account').order(:id).each do |channel|
assets = channel.assets(assets) assets = channel.assets(assets)
channel_ids.push channel.id channel_ids.push channel.id
} end
render json: { render json: {
assets: assets, assets: assets,
channel_ids: channel_ids, channel_ids: channel_ids,

View file

@ -7,10 +7,10 @@ class ChannelsTelegramController < ApplicationController
def index def index
assets = {} assets = {}
channel_ids = [] channel_ids = []
Channel.where(area: 'Telegram::Bot').order(:id).each { |channel| Channel.where(area: 'Telegram::Bot').order(:id).each do |channel|
assets = channel.assets(assets) assets = channel.assets(assets)
channel_ids.push channel.id channel_ids.push channel.id
} end
render json: { render json: {
assets: assets, assets: assets,
channel_ids: channel_ids channel_ids: channel_ids

View file

@ -5,14 +5,14 @@ class ChannelsTwitterController < ApplicationController
def index def index
assets = {} assets = {}
ExternalCredential.where(name: 'twitter').each { |external_credential| ExternalCredential.where(name: 'twitter').each do |external_credential|
assets = external_credential.assets(assets) assets = external_credential.assets(assets)
} end
channel_ids = [] channel_ids = []
Channel.where(area: 'Twitter::Account').order(:id).each { |channel| Channel.where(area: 'Twitter::Account').order(:id).each do |channel|
assets = channel.assets(assets) assets = channel.assets(assets)
channel_ids.push channel.id channel_ids.push channel.id
} end
render json: { render json: {
assets: assets, assets: assets,
channel_ids: channel_ids, channel_ids: channel_ids,

View file

@ -6,10 +6,10 @@ class ChatsController < ApplicationController
def index def index
chat_ids = [] chat_ids = []
assets = {} assets = {}
Chat.order(:id).each { |chat| Chat.order(:id).each do |chat|
chat_ids.push chat.id chat_ids.push chat.id
assets = chat.assets(assets) assets = chat.assets(assets)
} end
setting = Setting.find_by(name: 'chat') setting = Setting.find_by(name: 'chat')
assets = setting.assets(assets) assets = setting.assets(assets)
render json: { render json: {

View file

@ -62,7 +62,7 @@ module CreatesTicketArticles
article.save! article.save!
# store inline attachments # store inline attachments
attachments_inline.each { |attachment| attachments_inline.each do |attachment|
Store.add( Store.add(
object: 'Ticket::Article', object: 'Ticket::Article',
o_id: article.id, o_id: article.id,
@ -70,24 +70,24 @@ module CreatesTicketArticles
filename: attachment[:filename], filename: attachment[:filename],
preferences: attachment[:preferences], preferences: attachment[:preferences],
) )
} end
# add attachments as param # add attachments as param
if params[:attachments].present? if params[:attachments].present?
params[:attachments].each_with_index { |attachment, index| params[:attachments].each_with_index do |attachment, index|
# validation # validation
['mime-type', 'filename', 'data'].each { |key| ['mime-type', 'filename', 'data'].each do |key|
next if attachment[key] next if attachment[key]
raise Exceptions::UnprocessableEntity, "Attachment needs '#{key}' param for attachment with index '#{index}'" raise Exceptions::UnprocessableEntity, "Attachment needs '#{key}' param for attachment with index '#{index}'"
} end
preferences = {} preferences = {}
['charset', 'mime-type'].each { |key| ['charset', 'mime-type'].each do |key|
next if !attachment[key] next if !attachment[key]
store_key = key.tr('-', '_').camelize.gsub(/(.+)([A-Z])/, '\1_\2').tr('_', '-') store_key = key.tr('-', '_').camelize.gsub(/(.+)([A-Z])/, '\1_\2').tr('_', '-')
preferences[store_key] = attachment[key] preferences[store_key] = attachment[key]
} end
if attachment[:data] !~ %r{^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$} if attachment[:data] !~ %r{^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$}
raise Exceptions::UnprocessableEntity, "Invalid base64 for attachment with index '#{index}'" raise Exceptions::UnprocessableEntity, "Invalid base64 for attachment with index '#{index}'"
@ -100,7 +100,7 @@ module CreatesTicketArticles
filename: attachment[:filename], filename: attachment[:filename],
preferences: preferences, preferences: preferences,
) )
} end
end end
# account time # account time

View file

@ -16,7 +16,7 @@ module TicketStats
volume_by_year = [] volume_by_year = []
now = Time.zone.now now = Time.zone.now
(0..11).each { |month_back| (0..11).each do |month_back|
date_to_check = now - month_back.month date_to_check = now - month_back.month
date_start = "#{date_to_check.year}-#{date_to_check.month}-01 00:00:00" date_start = "#{date_to_check.year}-#{date_to_check.month}-01 00:00:00"
date_end = "#{date_to_check.year}-#{date_to_check.month}-#{date_to_check.end_of_month.day} 00:00:00" date_end = "#{date_to_check.year}-#{date_to_check.month}-#{date_to_check.end_of_month.day} 00:00:00"
@ -41,7 +41,7 @@ module TicketStats
closed: closed, closed: closed,
} }
volume_by_year.push data volume_by_year.push data
} end
volume_by_year volume_by_year
end end

View file

@ -243,14 +243,14 @@ class FirstStepsController < ApplicationController
test_ticket_active = false test_ticket_active = false
end end
return result if test_ticket_active return result if test_ticket_active
result.each { |item| result.each do |item|
items = [] items = []
item[:items].each { |local_item| item[:items].each do |local_item|
next if local_item[:name] == 'Create a Test Ticket' next if local_item[:name] == 'Create a Test Ticket'
items.push local_item items.push local_item
} end
item[:items] = items item[:items] = items
} end
result result
end end

View file

@ -128,7 +128,7 @@ class FormController < ApplicationController
if params[:file] if params[:file]
params[:file].each { |file| params[:file].each do |file|
Store.add( Store.add(
object: 'Ticket::Article', object: 'Ticket::Article',
o_id: article.id, o_id: article.id,
@ -138,7 +138,7 @@ class FormController < ApplicationController
'Mime-Type' => file.content_type, 'Mime-Type' => file.content_type,
} }
) )
} end
end end
UserInfo.current_user_id = 1 UserInfo.current_user_id = 1

View file

@ -174,9 +174,9 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password}
end end
# set changed settings # set changed settings
settings.each { |key, value| settings.each do |key, value|
Setting.set(key, value) Setting.set(key, value)
} end
render json: { render json: {
result: 'ok', result: 'ok',

View file

@ -25,11 +25,11 @@ class ImportOtrsController < ApplicationController
response = UserAgent.request(params[:url]) response = UserAgent.request(params[:url])
if !response.success? && response.code.to_s !~ /^40.$/ if !response.success? && response.code.to_s !~ /^40.$/
message_human = '' message_human = ''
translation_map.each { |key, message| translation_map.each do |key, message|
if response.error.to_s =~ /#{Regexp.escape(key)}/i if response.error.to_s =~ /#{Regexp.escape(key)}/i
message_human = message message_human = message
end end
} end
render json: { render json: {
result: 'invalid', result: 'invalid',
message_human: message_human, message_human: message_human,
@ -128,20 +128,20 @@ class ImportOtrsController < ApplicationController
# check count of dynamic fields # check count of dynamic fields
dynamic_field_count = 0 dynamic_field_count = 0
dynamic_fields = Import::OTRS::Requester.load('DynamicField') dynamic_fields = Import::OTRS::Requester.load('DynamicField')
dynamic_fields.each { |dynamic_field| dynamic_fields.each do |dynamic_field|
next if dynamic_field['ValidID'].to_i != 1 next if dynamic_field['ValidID'].to_i != 1
dynamic_field_count += 1 dynamic_field_count += 1
} end
if dynamic_field_count > 20 if dynamic_field_count > 20
issues.push 'otrsDynamicFields' issues.push 'otrsDynamicFields'
end end
# check if process exsists # check if process exsists
sys_configs = Import::OTRS::Requester.load('SysConfig') sys_configs = Import::OTRS::Requester.load('SysConfig')
sys_configs.each { |sys_config| sys_configs.each do |sys_config|
next if sys_config['Key'] != 'Process' next if sys_config['Key'] != 'Process'
issues.push 'otrsProcesses' issues.push 'otrsProcesses'
} end
result = 'ok' result = 'ok'
if !issues.empty? if !issues.empty?

View file

@ -27,11 +27,11 @@ class ImportZendeskController < ApplicationController
if !response.success? if !response.success?
message_human = '' message_human = ''
translation_map.each { |key, message| translation_map.each do |key, message|
if response.error.to_s =~ /#{Regexp.escape(key)}/i if response.error.to_s =~ /#{Regexp.escape(key)}/i
message_human = message message_human = message
end end
} end
render json: { render json: {
result: 'invalid', result: 'invalid',
message_human: message_human, message_human: message_human,

View file

@ -25,7 +25,7 @@ class Integration::CheckMkController < ApplicationController
open_states = Ticket::State.by_category(:open) open_states = Ticket::State.by_category(:open)
ticket_ids = Ticket.where(state: open_states).order(created_at: :desc).limit(5000).pluck(:id) ticket_ids = Ticket.where(state: open_states).order(created_at: :desc).limit(5000).pluck(:id)
ticket_ids_found = [] ticket_ids_found = []
ticket_ids.each { |ticket_id| ticket_ids.each do |ticket_id|
ticket = Ticket.find_by(id: ticket_id) ticket = Ticket.find_by(id: ticket_id)
next if !ticket next if !ticket
next if !ticket.preferences next if !ticket.preferences
@ -36,7 +36,7 @@ class Integration::CheckMkController < ApplicationController
# found open ticket for service+host # found open ticket for service+host
ticket_ids_found.push ticket.id ticket_ids_found.push ticket.id
} end
# new ticket, set meta data # new ticket, set meta data
title = "#{params[:host]} is #{params[:state]}" title = "#{params[:host]} is #{params[:state]}"
@ -51,7 +51,7 @@ UserAgent: #{request.env['HTTP_USER_AGENT']}
# add article # add article
if params[:state].present? && ticket_ids_found.present? if params[:state].present? && ticket_ids_found.present?
ticket_ids_found.each { |ticket_id| ticket_ids_found.each do |ticket_id|
ticket = Ticket.find_by(id: ticket_id) ticket = Ticket.find_by(id: ticket_id)
next if !ticket next if !ticket
article = Ticket::Article.create!( article = Ticket::Article.create!(
@ -62,7 +62,7 @@ UserAgent: #{request.env['HTTP_USER_AGENT']}
subject: title, subject: title,
internal: false, internal: false,
) )
} end
if (!auto_close && params[:state].match(/#{state_recovery_match}/i)) || !params[:state].match(/#{state_recovery_match}/i) if (!auto_close && params[:state].match(/#{state_recovery_match}/i)) || !params[:state].match(/#{state_recovery_match}/i)
render json: { render json: {
result: 'ticket already open, added note', result: 'ticket already open, added note',
@ -81,12 +81,12 @@ UserAgent: #{request.env['HTTP_USER_AGENT']}
return return
end end
state = Ticket::State.lookup(id: auto_close_state_id) state = Ticket::State.lookup(id: auto_close_state_id)
ticket_ids_found.each { |ticket_id| ticket_ids_found.each do |ticket_id|
ticket = Ticket.find_by(id: ticket_id) ticket = Ticket.find_by(id: ticket_id)
next if !ticket next if !ticket
ticket.state_id = auto_close_state_id ticket.state_id = auto_close_state_id
ticket.save! ticket.save!
} end
render json: { render json: {
result: "closed tickets with ids #{ticket_ids_found.join(',')}", result: "closed tickets with ids #{ticket_ids_found.join(',')}",
ticket_ids: ticket_ids_found, ticket_ids: ticket_ids_found,

View file

@ -13,7 +13,7 @@ class Integration::SipgateController < ApplicationController
block_caller_ids = config_inbound[:block_caller_ids] || [] block_caller_ids = config_inbound[:block_caller_ids] || []
# check if call need to be blocked # check if call need to be blocked
block_caller_ids.each { |item| block_caller_ids.each do |item|
next unless item[:caller_id] == params['from'] next unless item[:caller_id] == params['from']
xml = Builder::XmlMarkup.new(indent: 2) xml = Builder::XmlMarkup.new(indent: 2)
xml.instruct! xml.instruct!
@ -30,7 +30,7 @@ class Integration::SipgateController < ApplicationController
end end
Cti::Log.process(params) Cti::Log.process(params)
return true return true
} end
end end
Cti::Log.process(params) Cti::Log.process(params)
@ -54,7 +54,7 @@ class Integration::SipgateController < ApplicationController
to = params[:to] to = params[:to]
from = nil from = nil
if to if to
config_outbound.each { |row| config_outbound.each do |row|
dest = row[:dest].gsub(/\*/, '.+?') dest = row[:dest].gsub(/\*/, '.+?')
next if to !~ /^#{dest}$/ next if to !~ /^#{dest}$/
from = row[:caller_id] from = row[:caller_id]
@ -62,7 +62,7 @@ class Integration::SipgateController < ApplicationController
xml.Dial(callerId: from) { xml.Number(params[:to]) } xml.Dial(callerId: from) { xml.Number(params[:to]) }
end end
break break
} end
if !content && default_caller_id if !content && default_caller_id
from = default_caller_id from = default_caller_id
content = xml.Response(onHangup: url, onAnswer: url) do content = xml.Response(onHangup: url, onAnswer: url) do

View file

@ -12,13 +12,13 @@ class LinksController < ApplicationController
assets = {} assets = {}
link_list = [] link_list = []
links.each { |item| links.each do |item|
link_list.push item link_list.push item
if item['link_object'] == 'Ticket' if item['link_object'] == 'Ticket'
ticket = Ticket.lookup(id: item['link_object_value']) ticket = Ticket.lookup(id: item['link_object_value'])
assets = ticket.assets(assets) assets = ticket.assets(assets)
end end
} end
# return result # return result
render json: { render json: {

View file

@ -63,9 +63,9 @@ class LongPollingController < ApplicationController
begin begin
# update last ping # update last ping
4.times { 4.times do
sleep 0.25 sleep 0.25
} end
#sleep 1 #sleep 1
Sessions.touch(client_id) Sessions.touch(client_id)
@ -82,9 +82,9 @@ class LongPollingController < ApplicationController
render json: queue render json: queue
return return
end end
8.times { 8.times do
sleep 0.25 sleep 0.25
} end
#sleep 2 #sleep 2
if count.zero? if count.zero?
render json: { event: 'pong' } render json: { event: 'pong' }

View file

@ -34,15 +34,15 @@ curl http://localhost/api/v1/monitoring/health_check?token=XXX
# channel check # channel check
last_run_tolerance = Time.zone.now - 1.hour last_run_tolerance = Time.zone.now - 1.hour
Channel.where(active: true).each { |channel| Channel.where(active: true).each do |channel|
# inbound channel # inbound channel
if channel.status_in == 'error' if channel.status_in == 'error'
message = "Channel: #{channel.area} in " message = "Channel: #{channel.area} in "
%w(host user uid).each { |key| %w(host user uid).each do |key|
next if !channel.options[key] || channel.options[key].empty? next if !channel.options[key] || channel.options[key].empty?
message += "key:#{channel.options[key]};" message += "key:#{channel.options[key]};"
} end
issues.push "#{message} #{channel.last_log_in}" issues.push "#{message} #{channel.last_log_in}"
end end
if channel.preferences && channel.preferences['last_fetch'] && channel.preferences['last_fetch'] < last_run_tolerance if channel.preferences && channel.preferences['last_fetch'] && channel.preferences['last_fetch'] < last_run_tolerance
@ -52,32 +52,32 @@ curl http://localhost/api/v1/monitoring/health_check?token=XXX
# outbound channel # outbound channel
next if channel.status_out != 'error' next if channel.status_out != 'error'
message = "Channel: #{channel.area} out " message = "Channel: #{channel.area} out "
%w(host user uid).each { |key| %w(host user uid).each do |key|
next if !channel.options[key] || channel.options[key].empty? next if !channel.options[key] || channel.options[key].empty?
message += "key:#{channel.options[key]};" message += "key:#{channel.options[key]};"
} end
issues.push "#{message} #{channel.last_log_out}" issues.push "#{message} #{channel.last_log_out}"
} end
# unprocessable mail check # unprocessable mail check
directory = "#{Rails.root}/tmp/unprocessable_mail" directory = "#{Rails.root}/tmp/unprocessable_mail"
if File.exist?(directory) if File.exist?(directory)
count = 0 count = 0
Dir.glob("#{directory}/*.eml") { |_entry| Dir.glob("#{directory}/*.eml") do |_entry|
count += 1 count += 1
} end
if count.nonzero? if count.nonzero?
issues.push "unprocessable mails: #{count}" issues.push "unprocessable mails: #{count}"
end end
end end
# scheduler check # scheduler check
Scheduler.where(active: true).where.not(last_run: nil).each { |scheduler| Scheduler.where(active: true).where.not(last_run: nil).each do |scheduler|
next if scheduler.period <= 300 next if scheduler.period <= 300
next if scheduler.last_run + scheduler.period.seconds > Time.zone.now - 5.minutes next if scheduler.last_run + scheduler.period.seconds > Time.zone.now - 5.minutes
issues.push 'scheduler not running' issues.push 'scheduler not running'
break break
} end
if Scheduler.where(active: true, last_run: nil).count == Scheduler.where(active: true).count if Scheduler.where(active: true, last_run: nil).count == Scheduler.where(active: true).count
issues.push 'scheduler not running' issues.push 'scheduler not running'
end end
@ -158,13 +158,13 @@ curl http://localhost/api/v1/monitoring/status?token=XXX
tickets: Ticket, tickets: Ticket,
ticket_articles: Ticket::Article, ticket_articles: Ticket::Article,
} }
map.each { |key, class_name| map.each do |key, class_name|
status[:counts][key] = class_name.count status[:counts][key] = class_name.count
last = class_name.last last = class_name.last
status[:last_created_at][key] = if last status[:last_created_at][key] = if last
last.created_at last.created_at
end end
} end
render json: status render json: status
end end

View file

@ -71,9 +71,9 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password}
if params[:expand] if params[:expand]
list = [] list = []
organizations.each { |organization| organizations.each do |organization|
list.push organization.attributes_with_association_names list.push organization.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -81,10 +81,10 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password}
if params[:full] if params[:full]
assets = {} assets = {}
item_ids = [] item_ids = []
organizations.each { |item| organizations.each do |item|
item_ids.push item.id item_ids.push item.id
assets = item.assets(assets) assets = item.assets(assets)
} end
render json: { render json: {
record_ids: item_ids, record_ids: item_ids,
assets: assets, assets: assets,
@ -92,9 +92,9 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password}
return return
end end
list = [] list = []
organizations.each { |organization| organizations.each do |organization|
list.push organization.attributes_with_association_ids list.push organization.attributes_with_association_ids
} end
render json: list render json: list
end end
@ -257,9 +257,9 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co
if params[:expand] if params[:expand]
list = [] list = []
organization_all.each { |organization| organization_all.each do |organization|
list.push organization.attributes_with_association_names list.push organization.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -267,10 +267,10 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co
# build result list # build result list
if params[:label] if params[:label]
organizations = [] organizations = []
organization_all.each { |organization| organization_all.each do |organization|
a = { id: organization.id, label: organization.name, value: organization.name } a = { id: organization.id, label: organization.name, value: organization.name }
organizations.push a organizations.push a
} end
# return result # return result
render json: organizations render json: organizations
@ -280,10 +280,10 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co
if params[:full] if params[:full]
organization_ids = [] organization_ids = []
assets = {} assets = {}
organization_all.each { |organization| organization_all.each do |organization|
assets = organization.assets(assets) assets = organization.assets(assets)
organization_ids.push organization.id organization_ids.push organization.id
} end
# return result # return result
render json: { render json: {
@ -294,9 +294,9 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co
end end
list = [] list = []
organization_all.each { |organization| organization_all.each do |organization|
list.push organization.attributes_with_association_ids list.push organization.attributes_with_association_ids
} end
render json: list, status: :ok render json: list, status: :ok
end end

View file

@ -25,7 +25,7 @@ class ReportsController < ApplicationController
return if !get_params return if !get_params
result = {} result = {}
get_params[:metric][:backend].each { |backend| get_params[:metric][:backend].each do |backend|
condition = get_params[:profile].condition condition = get_params[:profile].condition
if backend[:condition] if backend[:condition]
backend[:condition].merge(condition) backend[:condition].merge(condition)
@ -40,7 +40,7 @@ class ReportsController < ApplicationController
selector: backend[:condition], selector: backend[:condition],
params: backend[:params], params: backend[:params],
) )
} end
#created = aggs(start, stop, range, 'created_at', profile.condition) #created = aggs(start, stop, range, 'created_at', profile.condition)
#closed = aggs(start, stop, range, 'close_at', profile.condition) #closed = aggs(start, stop, range, 'close_at', profile.condition)
@ -76,7 +76,7 @@ class ReportsController < ApplicationController
# get data # get data
result = {} result = {}
get_params[:metric][:backend].each { |backend| get_params[:metric][:backend].each do |backend|
next if params[:downloadBackendSelected] != backend[:name] next if params[:downloadBackendSelected] != backend[:name]
condition = get_params[:profile].condition condition = get_params[:profile].condition
if backend[:condition] if backend[:condition]
@ -103,7 +103,7 @@ class ReportsController < ApplicationController
type: 'application/vnd.ms-excel', type: 'application/vnd.ms-excel',
disposition: 'attachment' disposition: 'attachment'
) )
} end
return if params[:sheet] return if params[:sheet]
render json: result render json: result
@ -117,10 +117,10 @@ class ReportsController < ApplicationController
if params[:profile_id] if params[:profile_id]
profile = Report::Profile.find(params[:profile_id]) profile = Report::Profile.find(params[:profile_id])
else else
params[:profiles].each { |profile_id, active| params[:profiles].each do |profile_id, active|
next if !active next if !active
profile = Report::Profile.find(profile_id) profile = Report::Profile.find(profile_id)
} end
end end
if !profile if !profile
raise Exceptions::UnprocessableEntity, 'No such active profile' raise Exceptions::UnprocessableEntity, 'No such active profile'

View file

@ -29,14 +29,14 @@ class SearchController < ApplicationController
# get priorities of result # get priorities of result
objects_in_order = [] objects_in_order = []
objects_in_order_hash = {} objects_in_order_hash = {}
objects.each { |object| objects.each do |object|
preferences = object.constantize.search_preferences(current_user) preferences = object.constantize.search_preferences(current_user)
next if !preferences next if !preferences
objects_in_order_hash[preferences[:prio]] = object objects_in_order_hash[preferences[:prio]] = object
} end
objects_in_order_hash.keys.sort.reverse_each { |prio| objects_in_order_hash.keys.sort.reverse_each do |prio|
objects_in_order.push objects_in_order_hash[prio] objects_in_order.push objects_in_order_hash[prio]
} end
# try search index backend # try search index backend
assets = {} assets = {}
@ -46,7 +46,7 @@ class SearchController < ApplicationController
# get direct search index based objects # get direct search index based objects
objects_with_direct_search_index = [] objects_with_direct_search_index = []
objects_without_direct_search_index = [] objects_without_direct_search_index = []
objects.each { |object| objects.each do |object|
preferences = object.constantize.search_preferences(current_user) preferences = object.constantize.search_preferences(current_user)
next if !preferences next if !preferences
if preferences[:direct_search_index] if preferences[:direct_search_index]
@ -54,48 +54,48 @@ class SearchController < ApplicationController
else else
objects_without_direct_search_index.push object objects_without_direct_search_index.push object
end end
} end
# do only one query to index search backend # do only one query to index search backend
if objects_with_direct_search_index.present? if objects_with_direct_search_index.present?
items = SearchIndexBackend.search(query, limit, objects_with_direct_search_index) items = SearchIndexBackend.search(query, limit, objects_with_direct_search_index)
items.each { |item| items.each do |item|
require item[:type].to_filename require item[:type].to_filename
record = Kernel.const_get(item[:type]).lookup(id: item[:id]) record = Kernel.const_get(item[:type]).lookup(id: item[:id])
next if !record next if !record
assets = record.assets(assets) assets = record.assets(assets)
result.push item result.push item
} end
end end
# e. g. do ticket query by Ticket class to handle ticket permissions # e. g. do ticket query by Ticket class to handle ticket permissions
objects_without_direct_search_index.each { |object| objects_without_direct_search_index.each do |object|
object_result = search_generic_backend(object, query, limit, current_user, assets) object_result = search_generic_backend(object, query, limit, current_user, assets)
if object_result.present? if object_result.present?
result = result.concat(object_result) result = result.concat(object_result)
end end
} end
# sort order by object priority # sort order by object priority
result_in_order = [] result_in_order = []
objects_in_order.each { |object| objects_in_order.each do |object|
result.each { |item| result.each do |item|
next if item[:type] != object next if item[:type] != object
item[:id] = item[:id].to_i item[:id] = item[:id].to_i
result_in_order.push item result_in_order.push item
} end
} end
result = result_in_order result = result_in_order
else else
# do query # do query
objects_in_order.each { |object| objects_in_order.each do |object|
object_result = search_generic_backend(object, query, limit, current_user, assets) object_result = search_generic_backend(object, query, limit, current_user, assets)
if object_result.present? if object_result.present?
result = result.concat(object_result) result = result.concat(object_result)
end end
} end
end end
render json: { render json: {

View file

@ -7,9 +7,9 @@ module ExtraCollection
collections[ Locale.to_app_model ] = Locale.where(active: true) collections[ Locale.to_app_model ] = Locale.where(active: true)
collections[ Taskbar.to_app_model ] = Taskbar.where(user_id: user.id) collections[ Taskbar.to_app_model ] = Taskbar.where(user_id: user.id)
collections[ Taskbar.to_app_model ].each { |item| collections[ Taskbar.to_app_model ].each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ OnlineNotification.to_app_model ] = OnlineNotification.list(user, 200) collections[ OnlineNotification.to_app_model ] = OnlineNotification.list(user, 200)
assets = ApplicationModel.assets_of_object_list(collections[ OnlineNotification.to_app_model ], assets) assets = ApplicationModel.assets_of_object_list(collections[ OnlineNotification.to_app_model ], assets)
@ -18,25 +18,25 @@ module ExtraCollection
assets = RecentView.assets_of_object_list(collections[ RecentView.to_app_model ], assets) assets = RecentView.assets_of_object_list(collections[ RecentView.to_app_model ], assets)
collections[ Permission.to_app_model ] = [] collections[ Permission.to_app_model ] = []
Permission.all.each { |item| Permission.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Role.to_app_model ] = [] collections[ Role.to_app_model ] = []
Role.all.each { |item| Role.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Group.to_app_model ] = [] collections[ Group.to_app_model ] = []
Group.all.each { |item| Group.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Organization.to_app_model ] = [] collections[ Organization.to_app_model ] = []
if user.organization_id if user.organization_id
Organization.where(id: user.organization_id).each { |item| Organization.where(id: user.organization_id).each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
end end
[collections, assets] [collections, assets]

View file

@ -5,42 +5,42 @@ module ExtraCollection
# all ticket stuff # all ticket stuff
collections[ Macro.to_app_model ] = [] collections[ Macro.to_app_model ] = []
Macro.all.each { |item| Macro.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Ticket::StateType.to_app_model ] = [] collections[ Ticket::StateType.to_app_model ] = []
Ticket::StateType.all.each { |item| Ticket::StateType.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Ticket::State.to_app_model ] = [] collections[ Ticket::State.to_app_model ] = []
Ticket::State.all.each { |item| Ticket::State.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Ticket::Priority.to_app_model ] = [] collections[ Ticket::Priority.to_app_model ] = []
Ticket::Priority.all.each { |item| Ticket::Priority.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Ticket::Article::Type.to_app_model ] = [] collections[ Ticket::Article::Type.to_app_model ] = []
Ticket::Article::Type.all.each { |item| Ticket::Article::Type.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
collections[ Ticket::Article::Sender.to_app_model ] = [] collections[ Ticket::Article::Sender.to_app_model ] = []
Ticket::Article::Sender.all.each { |item| Ticket::Article::Sender.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
if user.permissions?(['ticket.agent', 'admin.channel_email']) if user.permissions?(['ticket.agent', 'admin.channel_email'])
# all signatures # all signatures
collections[ Signature.to_app_model ] = [] collections[ Signature.to_app_model ] = []
Signature.all.each { |item| Signature.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
# all email addresses # all email addresses
collections[ EmailAddress.to_app_model ] = [] collections[ EmailAddress.to_app_model ] = []
EmailAddress.all.each { |item| EmailAddress.all.each do |item|
assets = item.assets(assets) assets = item.assets(assets)
} end
end end
[collections, assets] [collections, assets]
end end

View file

@ -281,14 +281,14 @@ class SessionsController < ApplicationController
permission_check('admin.session') permission_check('admin.session')
assets = {} assets = {}
sessions_clean = [] sessions_clean = []
SessionHelper.list.each { |session| SessionHelper.list.each do |session|
next if session.data['user_id'].blank? next if session.data['user_id'].blank?
sessions_clean.push session sessions_clean.push session
next if session.data['user_id'] next if session.data['user_id']
user = User.lookup(id: session.data['user_id']) user = User.lookup(id: session.data['user_id'])
next if !user next if !user
assets = user.assets(assets) assets = user.assets(assets)
} end
render json: { render json: {
sessions: sessions_clean, sessions: sessions_clean,
assets: assets, assets: assets,
@ -307,12 +307,12 @@ class SessionsController < ApplicationController
# config # config
config = {} config = {}
Setting.select('name, preferences').where(frontend: true).each { |setting| Setting.select('name, preferences').where(frontend: true).each do |setting|
next if setting.preferences[:authentication] == true && !current_user next if setting.preferences[:authentication] == true && !current_user
value = Setting.get(setting.name) value = Setting.get(setting.name)
next if !current_user && (value == false || value.nil?) next if !current_user && (value == false || value.nil?)
config[setting.name] = value config[setting.name] = value
} end
# remember if we can to swich back to user # remember if we can to swich back to user
if session[:switched_from_user_id] if session[:switched_from_user_id]

View file

@ -6,10 +6,10 @@ class SettingsController < ApplicationController
# GET /settings # GET /settings
def index def index
list = [] list = []
Setting.all.each { |setting| Setting.all.each do |setting|
next if setting.preferences[:permission] && !current_user.permissions?(setting.preferences[:permission]) next if setting.preferences[:permission] && !current_user.permissions?(setting.preferences[:permission])
list.push setting list.push setting
} end
render json: list, status: :ok render json: list, status: :ok
end end
@ -93,13 +93,13 @@ class SettingsController < ApplicationController
def keep_certain_attributes def keep_certain_attributes
setting = Setting.find(params[:id]) setting = Setting.find(params[:id])
[:name, :area, :state_initial, :frontend, :options].each { |key| [:name, :area, :state_initial, :frontend, :options].each do |key|
params.delete(key) params.delete(key)
} end
if !params[:preferences].empty? if !params[:preferences].empty?
[:online_service_disable, :permission, :render].each { |key| [:online_service_disable, :permission, :render].each do |key|
params[:preferences].delete(key) params[:preferences].delete(key)
} end
params[:preferences].merge!(setting.preferences) params[:preferences].merge!(setting.preferences)
end end
params params

View file

@ -53,16 +53,16 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password}
# calendars # calendars
assets = {} assets = {}
calendar_ids = [] calendar_ids = []
Calendar.all.each { |calendar| Calendar.all.each do |calendar|
assets = calendar.assets(assets) assets = calendar.assets(assets)
} end
# slas # slas
sla_ids = [] sla_ids = []
Sla.all.each { |item| Sla.all.each do |item|
sla_ids.push item.id sla_ids.push item.id
assets = item.assets(assets) assets = item.assets(assets)
} end
render json: { render json: {
record_ids: sla_ids, record_ids: sla_ids,
assets: assets, assets: assets,

View file

@ -7,13 +7,13 @@ class TagsController < ApplicationController
def search def search
list = Tag::Item.where('name_downcase LIKE ?', "#{params[:term].strip.downcase}%").order('name ASC').limit(params[:limit] || 10) list = Tag::Item.where('name_downcase LIKE ?', "#{params[:term].strip.downcase}%").order('name ASC').limit(params[:limit] || 10)
results = [] results = []
list.each { |item| list.each do |item|
result = { result = {
id: item.id, id: item.id,
value: item.name, value: item.name,
} }
results.push result results.push result
} end
render json: results render json: results
end end
@ -63,14 +63,14 @@ class TagsController < ApplicationController
permission_check('admin.tag') permission_check('admin.tag')
list = Tag::Item.order('name ASC').limit(params[:limit] || 1000) list = Tag::Item.order('name ASC').limit(params[:limit] || 1000)
results = [] results = []
list.each { |item| list.each do |item|
result = { result = {
id: item.id, id: item.id,
name: item.name, name: item.name,
count: Tag.where(tag_item_id: item.id).count count: Tag.where(tag_item_id: item.id).count
} }
results.push result results.push result
} end
render json: results render json: results
end end

View file

@ -39,13 +39,13 @@ class TicketArticlesController < ApplicationController
articles = [] articles = []
if params[:expand] if params[:expand]
ticket.articles.each { |article| ticket.articles.each do |article|
# ignore internal article if customer is requesting # ignore internal article if customer is requesting
next if article.internal == true && current_user.permissions?('ticket.customer') next if article.internal == true && current_user.permissions?('ticket.customer')
result = article.attributes_with_association_names result = article.attributes_with_association_names
articles.push result articles.push result
} end
render json: articles, status: :ok render json: articles, status: :ok
return return
@ -54,14 +54,14 @@ class TicketArticlesController < ApplicationController
if params[:full] if params[:full]
assets = {} assets = {}
record_ids = [] record_ids = []
ticket.articles.each { |article| ticket.articles.each do |article|
# ignore internal article if customer is requesting # ignore internal article if customer is requesting
next if article.internal == true && current_user.permissions?('ticket.customer') next if article.internal == true && current_user.permissions?('ticket.customer')
record_ids.push article.id record_ids.push article.id
assets = article.assets({}) assets = article.assets({})
} end
render json: { render json: {
record_ids: record_ids, record_ids: record_ids,
assets: assets, assets: assets,
@ -69,12 +69,12 @@ class TicketArticlesController < ApplicationController
return return
end end
ticket.articles.each { |article| ticket.articles.each do |article|
# ignore internal article if customer is requesting # ignore internal article if customer is requesting
next if article.internal == true && current_user.permissions?('ticket.customer') next if article.internal == true && current_user.permissions?('ticket.customer')
articles.push article.attributes_with_association_names articles.push article.attributes_with_association_names
} end
render json: articles render json: articles
end end
@ -224,11 +224,11 @@ class TicketArticlesController < ApplicationController
list = article.attachments || [] list = article.attachments || []
access = false access = false
list.each { |item| list.each do |item|
if item.id.to_i == params[:id].to_i if item.id.to_i == params[:id].to_i
access = true access = true
end end
} end
raise Exceptions::NotAuthorized, 'Requested file id is not linked with article_id.' if !access raise Exceptions::NotAuthorized, 'Requested file id is not linked with article_id.' if !access
# find file # find file

View file

@ -12,7 +12,7 @@ class TicketOverviewsController < ApplicationController
if !params[:view] if !params[:view]
index_and_lists = Ticket::Overviews.index(current_user) index_and_lists = Ticket::Overviews.index(current_user)
indexes = [] indexes = []
index_and_lists.each { |index| index_and_lists.each do |index|
assets = {} assets = {}
overview = Overview.lookup(id: index[:overview][:id]) overview = Overview.lookup(id: index[:overview][:id])
meta = { meta = {
@ -22,7 +22,7 @@ class TicketOverviewsController < ApplicationController
count: index[:count], count: index[:count],
} }
indexes.push meta indexes.push meta
} end
render json: indexes render json: indexes
return return
end end
@ -31,17 +31,17 @@ class TicketOverviewsController < ApplicationController
assets = {} assets = {}
result = {} result = {}
index_and_lists.each { |index| index_and_lists.each do |index|
next if index[:overview][:view] != params[:view] next if index[:overview][:view] != params[:view]
overview = Overview.lookup(id: index[:overview][:id]) overview = Overview.lookup(id: index[:overview][:id])
assets = overview.assets(assets) assets = overview.assets(assets)
index[:tickets].each { |ticket_meta| index[:tickets].each do |ticket_meta|
ticket = Ticket.lookup(id: ticket_meta[:id]) ticket = Ticket.lookup(id: ticket_meta[:id])
assets = ticket.assets(assets) assets = ticket.assets(assets)
} end
result = index result = index
} end
render json: { render json: {
assets: assets, assets: assets,

View file

@ -25,9 +25,9 @@ class TicketsController < ApplicationController
if params[:expand] if params[:expand]
list = [] list = []
tickets.each { |ticket| tickets.each do |ticket|
list.push ticket.attributes_with_association_names list.push ticket.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -35,10 +35,10 @@ class TicketsController < ApplicationController
if params[:full] if params[:full]
assets = {} assets = {}
item_ids = [] item_ids = []
tickets.each { |item| tickets.each do |item|
item_ids.push item.id item_ids.push item.id
assets = item.assets(assets) assets = item.assets(assets)
} end
render json: { render json: {
record_ids: item_ids, record_ids: item_ids,
assets: assets, assets: assets,
@ -80,9 +80,9 @@ class TicketsController < ApplicationController
# overwrite params # overwrite params
if !current_user.permissions?('ticket.agent') if !current_user.permissions?('ticket.agent')
[:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each { |key| [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each do |key|
clean_params.delete(key) clean_params.delete(key)
} end
clean_params[:customer_id] = current_user.id clean_params[:customer_id] = current_user.id
end end
@ -124,9 +124,9 @@ class TicketsController < ApplicationController
# create tags if given # create tags if given
if params[:tags].present? if params[:tags].present?
tags = params[:tags].split(/,/) tags = params[:tags].split(/,/)
tags.each { |tag| tags.each do |tag|
ticket.tag_add(tag) ticket.tag_add(tag)
} end
end end
# create article if given # create article if given
@ -145,11 +145,11 @@ class TicketsController < ApplicationController
if params[:links].present? if params[:links].present?
link = params[:links].permit!.to_h link = params[:links].permit!.to_h
raise Exceptions::UnprocessableEntity, 'Invalid link structure' if !link.is_a? Hash raise Exceptions::UnprocessableEntity, 'Invalid link structure' if !link.is_a? Hash
link.each { |target_object, link_types_with_object_ids| link.each do |target_object, link_types_with_object_ids|
raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object)' if !link_types_with_object_ids.is_a? Hash raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object)' if !link_types_with_object_ids.is_a? Hash
link_types_with_object_ids.each { |link_type, object_ids| link_types_with_object_ids.each do |link_type, object_ids|
raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object->LinkType)' if !object_ids.is_a? Array raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object->LinkType)' if !object_ids.is_a? Array
object_ids.each { |local_object_id| object_ids.each do |local_object_id|
link = Link.add( link = Link.add(
link_type: link_type, link_type: link_type,
link_object_target: target_object, link_object_target: target_object,
@ -157,9 +157,9 @@ class TicketsController < ApplicationController
link_object_source: 'Ticket', link_object_source: 'Ticket',
link_object_source_value: ticket.id, link_object_source_value: ticket.id,
) )
} end
} end
} end
end end
if params[:expand] if params[:expand]
@ -186,9 +186,9 @@ class TicketsController < ApplicationController
# overwrite params # overwrite params
if !current_user.permissions?('ticket.agent') if !current_user.permissions?('ticket.agent')
[:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each { |key| [:owner, :owner_id, :customer, :customer_id, :organization, :organization_id, :preferences].each do |key|
clean_params.delete(key) clean_params.delete(key)
} end
end end
ticket.with_lock do ticket.with_lock do
@ -285,20 +285,20 @@ class TicketsController < ApplicationController
# get related assets # get related assets
ticket_ids_by_customer = [] ticket_ids_by_customer = []
ticket_lists.each { |ticket_list| ticket_lists.each do |ticket_list|
ticket_ids_by_customer.push ticket_list.id ticket_ids_by_customer.push ticket_list.id
assets = ticket_list.assets(assets) assets = ticket_list.assets(assets)
} end
ticket_ids_recent_viewed = [] ticket_ids_recent_viewed = []
recent_views = RecentView.list(current_user, 8, 'Ticket').delete_if { |object| object['o_id'] == ticket.id } recent_views = RecentView.list(current_user, 8, 'Ticket').delete_if { |object| object['o_id'] == ticket.id }
recent_views.each { |recent_view| recent_views.each do |recent_view|
next if recent_view['object'] != 'Ticket' next if recent_view['object'] != 'Ticket'
ticket_ids_recent_viewed.push recent_view['o_id'] ticket_ids_recent_viewed.push recent_view['o_id']
recent_view_ticket = Ticket.find(recent_view['o_id']) recent_view_ticket = Ticket.find(recent_view['o_id'])
next if recent_view_ticket.state.state_type.name == 'merged' next if recent_view_ticket.state.state_type.name == 'merged'
assets = recent_view_ticket.assets(assets) assets = recent_view_ticket.assets(assets)
} end
# return result # return result
render json: { render json: {
@ -405,9 +405,9 @@ class TicketsController < ApplicationController
if params[:expand] if params[:expand]
list = [] list = []
tickets.each { |ticket| tickets.each do |ticket|
list.push ticket.attributes_with_association_names list.push ticket.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -490,9 +490,9 @@ class TicketsController < ApplicationController
}, },
}, },
} }
conditions.each { |key, local_condition| conditions.each do |key, local_condition|
user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets) user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
} end
# generate stats by user # generate stats by user
condition = { condition = {
@ -531,9 +531,9 @@ class TicketsController < ApplicationController
}, },
}, },
} }
conditions.each { |key, local_condition| conditions.each do |key, local_condition|
org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets) org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
} end
# generate stats by org # generate stats by org
condition = { condition = {
@ -566,14 +566,14 @@ class TicketsController < ApplicationController
# get related users # get related users
article_ids = [] article_ids = []
ticket.articles.each { |article| ticket.articles.each do |article|
# ignore internal article if customer is requesting # ignore internal article if customer is requesting
next if article.internal == true && current_user.permissions?('ticket.customer') next if article.internal == true && current_user.permissions?('ticket.customer')
article_ids.push article.id article_ids.push article.id
assets = article.assets(assets) assets = article.assets(assets)
} end
# get links # get links
links = Link.list( links = Link.list(
@ -581,13 +581,13 @@ class TicketsController < ApplicationController
link_object_value: ticket.id, link_object_value: ticket.id,
) )
link_list = [] link_list = []
links.each { |item| links.each do |item|
link_list.push item link_list.push item
if item['link_object'] == 'Ticket' if item['link_object'] == 'Ticket'
linked_ticket = Ticket.lookup(id: item['link_object_value']) linked_ticket = Ticket.lookup(id: item['link_object_value'])
assets = linked_ticket.assets(assets) assets = linked_ticket.assets(assets)
end end
} end
# get tags # get tags
tags = ticket.tag_list tags = ticket.tag_list

View file

@ -12,7 +12,7 @@ class TimeAccountingsController < ApplicationController
end_periode = start_periode.end_of_month end_periode = start_periode.end_of_month
time_unit = {} time_unit = {}
Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each { |record| Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each do |record|
if !time_unit[record[0]] if !time_unit[record[0]]
time_unit[record[0]] = { time_unit[record[0]] = {
time_unit: 0, time_unit: 0,
@ -20,12 +20,12 @@ class TimeAccountingsController < ApplicationController
} }
end end
time_unit[record[0]][:time_unit] += record[1] time_unit[record[0]][:time_unit] += record[1]
} end
customers = {} customers = {}
organizations = {} organizations = {}
agents = {} agents = {}
results = [] results = []
time_unit.each { |ticket_id, local_time_unit| time_unit.each do |ticket_id, local_time_unit|
ticket = Ticket.lookup(id: ticket_id) ticket = Ticket.lookup(id: ticket_id)
next if !ticket next if !ticket
if !customers[ticket.customer_id] if !customers[ticket.customer_id]
@ -61,7 +61,7 @@ class TimeAccountingsController < ApplicationController
agent: agents[local_time_unit[:agent_id]], agent: agents[local_time_unit[:agent_id]],
} }
results.push result results.push result
} end
if params[:download] if params[:download]
header = [ header = [
@ -163,13 +163,13 @@ class TimeAccountingsController < ApplicationController
}, },
] ]
result = [] result = []
results.each { |row| results.each do |row|
row[:ticket].keys.each { |field| row[:ticket].keys.each do |field|
next if row[:ticket][field].blank? next if row[:ticket][field].blank?
next if !row[:ticket][field].is_a?(ActiveSupport::TimeWithZone) next if !row[:ticket][field].is_a?(ActiveSupport::TimeWithZone)
row[:ticket][field] = row[:ticket][field].iso8601 row[:ticket][field] = row[:ticket][field].iso8601
} end
result_row = [ result_row = [
row[:ticket]['number'], row[:ticket]['number'],
@ -198,7 +198,7 @@ class TimeAccountingsController < ApplicationController
row[:ticket]['escalation_at'], row[:ticket]['escalation_at'],
] ]
result.push result_row result.push result_row
} end
content = sheet("By Ticket #{year}-#{month}", header, result) content = sheet("By Ticket #{year}-#{month}", header, result)
send_data( send_data(
content, content,
@ -221,7 +221,7 @@ class TimeAccountingsController < ApplicationController
end_periode = start_periode.end_of_month end_periode = start_periode.end_of_month
time_unit = {} time_unit = {}
Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each { |record| Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each do |record|
if !time_unit[record[0]] if !time_unit[record[0]]
time_unit[record[0]] = { time_unit[record[0]] = {
time_unit: 0, time_unit: 0,
@ -229,10 +229,10 @@ class TimeAccountingsController < ApplicationController
} }
end end
time_unit[record[0]][:time_unit] += record[1] time_unit[record[0]][:time_unit] += record[1]
} end
customers = {} customers = {}
time_unit.each { |ticket_id, local_time_unit| time_unit.each do |ticket_id, local_time_unit|
ticket = Ticket.lookup(id: ticket_id) ticket = Ticket.lookup(id: ticket_id)
next if !ticket next if !ticket
if !customers[ticket.customer_id] if !customers[ticket.customer_id]
@ -248,11 +248,11 @@ class TimeAccountingsController < ApplicationController
next next
end end
customers[ticket.customer_id][:time_unit] += local_time_unit[:time_unit] customers[ticket.customer_id][:time_unit] += local_time_unit[:time_unit]
} end
results = [] results = []
customers.each { |_customer_id, content| customers.each do |_customer_id, content|
results.push content results.push content
} end
if params[:download] if params[:download]
header = [ header = [
@ -270,7 +270,7 @@ class TimeAccountingsController < ApplicationController
} }
] ]
result = [] result = []
results.each { |row| results.each do |row|
customer_name = User.find(row[:customer]['id']).fullname customer_name = User.find(row[:customer]['id']).fullname
organization_name = '' organization_name = ''
if row[:organization].present? if row[:organization].present?
@ -278,7 +278,7 @@ class TimeAccountingsController < ApplicationController
end end
result_row = [customer_name, organization_name, row[:time_unit]] result_row = [customer_name, organization_name, row[:time_unit]]
result.push result_row result.push result_row
} end
content = sheet("By Customer #{year}-#{month}", header, result) content = sheet("By Customer #{year}-#{month}", header, result)
send_data( send_data(
content, content,
@ -301,7 +301,7 @@ class TimeAccountingsController < ApplicationController
end_periode = start_periode.end_of_month end_periode = start_periode.end_of_month
time_unit = {} time_unit = {}
Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each { |record| Ticket::TimeAccounting.where('created_at >= ? AND created_at <= ?', start_periode, end_periode).pluck(:ticket_id, :time_unit, :created_by_id).each do |record|
if !time_unit[record[0]] if !time_unit[record[0]]
time_unit[record[0]] = { time_unit[record[0]] = {
time_unit: 0, time_unit: 0,
@ -309,10 +309,10 @@ class TimeAccountingsController < ApplicationController
} }
end end
time_unit[record[0]][:time_unit] += record[1] time_unit[record[0]][:time_unit] += record[1]
} end
organizations = {} organizations = {}
time_unit.each { |ticket_id, local_time_unit| time_unit.each do |ticket_id, local_time_unit|
ticket = Ticket.lookup(id: ticket_id) ticket = Ticket.lookup(id: ticket_id)
next if !ticket next if !ticket
next if !ticket.organization_id next if !ticket.organization_id
@ -324,11 +324,11 @@ class TimeAccountingsController < ApplicationController
next next
end end
organizations[ticket.organization_id][:time_unit] += local_time_unit[:time_unit] organizations[ticket.organization_id][:time_unit] += local_time_unit[:time_unit]
} end
results = [] results = []
organizations.each { |_customer_id, content| organizations.each do |_customer_id, content|
results.push content results.push content
} end
if params[:download] if params[:download]
header = [ header = [
@ -342,14 +342,14 @@ class TimeAccountingsController < ApplicationController
} }
] ]
result = [] result = []
results.each { |row| results.each do |row|
organization_name = '' organization_name = ''
if row[:organization].present? if row[:organization].present?
organization_name = row[:organization]['name'] organization_name = row[:organization]['name']
end end
result_row = [organization_name, row[:time_unit]] result_row = [organization_name, row[:time_unit]]
result.push result_row result.push result_row
} end
content = sheet("By Organization #{year}-#{month}", header, result) content = sheet("By Organization #{year}-#{month}", header, result)
send_data( send_data(
content, content,
@ -389,23 +389,23 @@ class TimeAccountingsController < ApplicationController
format_header.set_bg_color('gray') format_header.set_bg_color('gray')
format_header.set_color('white') format_header.set_color('white')
count = 0 count = 0
header.each { |item| header.each do |item|
if item[:width] if item[:width]
worksheet.set_column(count, count, item[:width]) worksheet.set_column(count, count, item[:width])
end end
worksheet.write(2, count, item[:name], format_header) worksheet.write(2, count, item[:name], format_header)
count += 1 count += 1
} end
row_count = 2 row_count = 2
result.each { |row| result.each do |row|
row_count += 1 row_count += 1
row_item_count = 0 row_item_count = 0
row.each { |item| row.each do |item|
worksheet.write(row_count, row_item_count, item) worksheet.write(row_count, row_item_count, item)
row_item_count += 1 row_item_count += 1
} end
} end
workbook.close workbook.close

View file

@ -6,34 +6,34 @@ class UserAccessTokenController < ApplicationController
def index def index
tokens = Token.where(action: 'api', persistent: true, user_id: current_user.id).order('updated_at DESC, label ASC') tokens = Token.where(action: 'api', persistent: true, user_id: current_user.id).order('updated_at DESC, label ASC')
token_list = [] token_list = []
tokens.each { |token| tokens.each do |token|
attributes = token.attributes attributes = token.attributes
attributes.delete('persistent') attributes.delete('persistent')
attributes.delete('name') attributes.delete('name')
token_list.push attributes token_list.push attributes
} end
local_permissions = current_user.permissions local_permissions = current_user.permissions
local_permissions_new = {} local_permissions_new = {}
local_permissions.each { |key, _value| local_permissions.each do |key, _value|
keys = Object.const_get('Permission').with_parents(key) keys = Object.const_get('Permission').with_parents(key)
keys.each { |local_key| keys.each do |local_key|
next if local_permissions_new.key?([local_key]) next if local_permissions_new.key?([local_key])
if local_permissions[local_key] == true if local_permissions[local_key] == true
local_permissions_new[local_key] = true local_permissions_new[local_key] = true
next next
end end
local_permissions_new[local_key] = false local_permissions_new[local_key] = false
} end
} end
permissions = [] permissions = []
Permission.all.where(active: true).order(:name).each { |permission| Permission.all.where(active: true).order(:name).each do |permission|
next if !local_permissions_new.key?(permission.name) && !current_user.permissions?(permission.name) next if !local_permissions_new.key?(permission.name) && !current_user.permissions?(permission.name)
permission_attributes = permission.attributes permission_attributes = permission.attributes
if local_permissions_new[permission.name] == false if local_permissions_new[permission.name] == false
permission_attributes['preferences']['disabled'] = true permission_attributes['preferences']['disabled'] = true
end end
permissions.push permission_attributes permissions.push permission_attributes
} end
render json: { render json: {
tokens: token_list, tokens: token_list,

View file

@ -6,7 +6,7 @@ class UserDevicesController < ApplicationController
def index def index
devices = UserDevice.where(user_id: current_user.id).order('updated_at DESC, name ASC') devices = UserDevice.where(user_id: current_user.id).order('updated_at DESC, name ASC')
devices_full = [] devices_full = []
devices.each { |device| devices.each do |device|
attributes = device.attributes attributes = device.attributes
if device.location_details['city_name'] && !device.location_details['city_name'].empty? if device.location_details['city_name'] && !device.location_details['city_name'].empty?
attributes['location'] += ", #{device.location_details['city_name']}" attributes['location'] += ", #{device.location_details['city_name']}"
@ -21,7 +21,7 @@ class UserDevicesController < ApplicationController
attributes['current'] = true attributes['current'] = true
end end
devices_full.push attributes devices_full.push attributes
} end
model_index_render_result(devices_full) model_index_render_result(devices_full)
end end
@ -32,12 +32,12 @@ class UserDevicesController < ApplicationController
# delete device and session's # delete device and session's
if user_device if user_device
SessionHelper.list.each { |session| SessionHelper.list.each do |session|
next if !session.data['user_id'] next if !session.data['user_id']
next if !session.data['user_device_id'] next if !session.data['user_device_id']
next if session.data['user_device_id'] != user_device.id next if session.data['user_device_id'] != user_device.id
SessionHelper.destroy( session.id ) SessionHelper.destroy( session.id )
} end
user_device.destroy user_device.destroy
end end
render json: {}, status: :ok render json: {}, status: :ok

View file

@ -34,9 +34,9 @@ class UsersController < ApplicationController
if params[:expand] if params[:expand]
list = [] list = []
users.each { |user| users.each do |user|
list.push user.attributes_with_association_names list.push user.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -44,10 +44,10 @@ class UsersController < ApplicationController
if params[:full] if params[:full]
assets = {} assets = {}
item_ids = [] item_ids = []
users.each { |item| users.each do |item|
item_ids.push item.id item_ids.push item.id
assets = item.assets(assets) assets = item.assets(assets)
} end
render json: { render json: {
record_ids: item_ids, record_ids: item_ids,
assets: assets, assets: assets,
@ -56,9 +56,9 @@ class UsersController < ApplicationController
end end
users_all = [] users_all = []
users.each { |user| users.each do |user|
users_all.push User.lookup(id: user.id).attributes_with_association_ids users_all.push User.lookup(id: user.id).attributes_with_association_ids
} end
render json: users_all, status: :ok render json: users_all, status: :ok
end end
@ -145,12 +145,12 @@ class UsersController < ApplicationController
group_ids = [] group_ids = []
role_ids = [] role_ids = []
if count <= 2 if count <= 2
Role.where(name: %w(Admin Agent)).each { |role| Role.where(name: %w(Admin Agent)).each do |role|
role_ids.push role.id role_ids.push role.id
} end
Group.all().each { |group| Group.all().each do |group|
group_ids.push group.id group_ids.push group.id
} end
# everybody else will go as customer per default # everybody else will go as customer per default
else else
@ -384,9 +384,9 @@ class UsersController < ApplicationController
if params[:expand] if params[:expand]
list = [] list = []
user_all.each { |user| user_all.each do |user|
list.push user.attributes_with_association_names list.push user.attributes_with_association_names
} end
render json: list, status: :ok render json: list, status: :ok
return return
end end
@ -394,14 +394,14 @@ class UsersController < ApplicationController
# build result list # build result list
if params[:label] if params[:label]
users = [] users = []
user_all.each { |user| user_all.each do |user|
realname = user.firstname.to_s + ' ' + user.lastname.to_s realname = user.firstname.to_s + ' ' + user.lastname.to_s
if user.email && user.email.to_s != '' if user.email && user.email.to_s != ''
realname = realname + ' <' + user.email.to_s + '>' realname = realname + ' <' + user.email.to_s + '>'
end end
a = { id: user.id, label: realname, value: realname } a = { id: user.id, label: realname, value: realname }
users.push a users.push a
} end
# return result # return result
render json: users render json: users
@ -411,10 +411,10 @@ class UsersController < ApplicationController
if params[:full] if params[:full]
user_ids = [] user_ids = []
assets = {} assets = {}
user_all.each { |user| user_all.each do |user|
assets = user.assets(assets) assets = user.assets(assets)
user_ids.push user.id user_ids.push user.id
} end
# return result # return result
render json: { render json: {
@ -425,9 +425,9 @@ class UsersController < ApplicationController
end end
list = [] list = []
user_all.each { |user| user_all.each do |user|
list.push user.attributes_with_association_ids list.push user.attributes_with_association_ids
} end
render json: list, status: :ok render json: list, status: :ok
end end
@ -464,14 +464,14 @@ class UsersController < ApplicationController
# build result list # build result list
if !params[:full] if !params[:full]
users = [] users = []
user_all.each { |user| user_all.each do |user|
realname = user.firstname.to_s + ' ' + user.lastname.to_s realname = user.firstname.to_s + ' ' + user.lastname.to_s
if user.email && user.email.to_s != '' if user.email && user.email.to_s != ''
realname = realname + ' <' + user.email.to_s + '>' realname = realname + ' <' + user.email.to_s + '>'
end end
a = { id: user.id, label: realname, value: realname } a = { id: user.id, label: realname, value: realname }
users.push a users.push a
} end
# return result # return result
render json: users render json: users
@ -480,10 +480,10 @@ class UsersController < ApplicationController
user_ids = [] user_ids = []
assets = {} assets = {}
user_all.each { |user| user_all.each do |user|
assets = user.assets(assets) assets = user.assets(assets)
user_ids.push user.id user_ids.push user.id
} end
# return result # return result
render json: { render json: {
@ -806,9 +806,9 @@ curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Co
if params[:user] if params[:user]
user = User.find(current_user.id) user = User.find(current_user.id)
user.with_lock do user.with_lock do
params[:user].each { |key, value| params[:user].each do |key, value|
user.preferences[key.to_sym] = value user.preferences[key.to_sym] = value
} end
user.save! user.save!
end end
end end

View file

@ -33,13 +33,13 @@ returns
return data if !self['created_by_id'] && !self['updated_by_id'] return data if !self['created_by_id'] && !self['updated_by_id']
app_model_user = User.to_app_model app_model_user = User.to_app_model
%w(created_by_id updated_by_id).each { |local_user_id| %w(created_by_id updated_by_id).each do |local_user_id|
next if !self[ local_user_id ] next if !self[ local_user_id ]
next if data[ app_model_user ] && data[ app_model_user ][ self[ local_user_id ] ] next if data[ app_model_user ] && data[ app_model_user ][ self[ local_user_id ] ]
user = User.lookup(id: self[ local_user_id ]) user = User.lookup(id: self[ local_user_id ])
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
data data
end end
@ -57,7 +57,7 @@ get assets and record_ids of selector
# get assets of condition # get assets of condition
models = Models.all models = Models.all
send(selector).each { |item, content| send(selector).each do |item, content|
attribute = item.split(/\./) attribute = item.split(/\./)
next if !attribute[1] next if !attribute[1]
begin begin
@ -74,19 +74,19 @@ get assets and record_ids of selector
next if !models[attribute_class][:reflections][reflection].klass next if !models[attribute_class][:reflections][reflection].klass
attribute_ref_class = models[attribute_class][:reflections][reflection].klass attribute_ref_class = models[attribute_class][:reflections][reflection].klass
if content['value'].instance_of?(Array) if content['value'].instance_of?(Array)
content['value'].each { |item_id| content['value'].each do |item_id|
attribute_object = attribute_ref_class.find_by(id: item_id) attribute_object = attribute_ref_class.find_by(id: item_id)
if attribute_object if attribute_object
assets = attribute_object.assets(assets) assets = attribute_object.assets(assets)
end end
} end
else else
attribute_object = attribute_ref_class.find_by(id: content['value']) attribute_object = attribute_ref_class.find_by(id: content['value'])
if attribute_object if attribute_object
assets = attribute_object.assets(assets) assets = attribute_object.assets(assets)
end end
end end
} end
assets assets
end end
@ -134,7 +134,7 @@ get assets of object list
=end =end
def assets_of_object_list(list, assets = {}) def assets_of_object_list(list, assets = {})
list.each { |item| list.each do |item|
require item['object'].to_filename require item['object'].to_filename
record = Kernel.const_get(item['object']).find(item['o_id']) record = Kernel.const_get(item['object']).find(item['o_id'])
assets = record.assets(assets) assets = record.assets(assets)
@ -146,7 +146,7 @@ get assets of object list
user = User.find(item['updated_by_id']) user = User.find(item['updated_by_id'])
assets = user.assets(assets) assets = user.assets(assets)
end end
} end
assets assets
end end
end end

View file

@ -29,7 +29,7 @@ returns
end end
# set relations by id/verify if ref exists # set relations by id/verify if ref exists
self.class.reflect_on_all_associations.map { |assoc| self.class.reflect_on_all_associations.map do |assoc|
assoc_name = assoc.name assoc_name = assoc.name
next if association_attributes_ignored.include?(assoc_name) next if association_attributes_ignored.include?(assoc_name)
real_ids = assoc_name[0, assoc_name.length - 1] + '_ids' real_ids = assoc_name[0, assoc_name.length - 1] + '_ids'
@ -40,7 +40,7 @@ returns
list_of_items = [ params[real_ids] ] list_of_items = [ params[real_ids] ]
end end
list = [] list = []
list_of_items.each { |item_id| list_of_items.each do |item_id|
next if !item_id next if !item_id
lookup = assoc.klass.lookup(id: item_id) lookup = assoc.klass.lookup(id: item_id)
@ -49,12 +49,12 @@ returns
raise ArgumentError, "No value found for '#{assoc_name}' with id #{item_id.inspect}" raise ArgumentError, "No value found for '#{assoc_name}' with id #{item_id.inspect}"
end end
list.push item_id list.push item_id
} end
send("#{real_ids}=", list) send("#{real_ids}=", list)
} end
# set relations by name/lookup # set relations by name/lookup
self.class.reflect_on_all_associations.map { |assoc| self.class.reflect_on_all_associations.map do |assoc|
assoc_name = assoc.name assoc_name = assoc.name
next if association_attributes_ignored.include?(assoc_name) next if association_attributes_ignored.include?(assoc_name)
real_ids = assoc_name[0, assoc_name.length - 1] + '_ids' real_ids = assoc_name[0, assoc_name.length - 1] + '_ids'
@ -66,7 +66,7 @@ returns
next if !params[real_values].instance_of?(Array) next if !params[real_values].instance_of?(Array)
list = [] list = []
class_object = assoc.klass class_object = assoc.klass
params[real_values].each { |value| params[real_values].each do |value|
lookup = nil lookup = nil
if class_object == User if class_object == User
if !lookup if !lookup
@ -84,9 +84,9 @@ returns
raise ArgumentError, "No lookup value found for '#{assoc_name}': #{value.inspect}" raise ArgumentError, "No lookup value found for '#{assoc_name}': #{value.inspect}"
end end
list.push lookup.id list.push lookup.id
} end
send("#{real_ids}=", list) send("#{real_ids}=", list)
} end
end end
=begin =begin
@ -110,12 +110,12 @@ returns
# get relations # get relations
attributes = self.attributes attributes = self.attributes
self.class.reflect_on_all_associations.map { |assoc| self.class.reflect_on_all_associations.map do |assoc|
next if association_attributes_ignored.include?(assoc.name) next if association_attributes_ignored.include?(assoc.name)
real_ids = assoc.name.to_s[0, assoc.name.to_s.length - 1] + '_ids' real_ids = assoc.name.to_s[0, assoc.name.to_s.length - 1] + '_ids'
next if !respond_to?(real_ids) next if !respond_to?(real_ids)
attributes[real_ids] = send(real_ids) attributes[real_ids] = send(real_ids)
} end
# special handling for group access associations # special handling for group access associations
if respond_to?(:group_ids_access_map) if respond_to?(:group_ids_access_map)
@ -145,21 +145,21 @@ returns
# get relations # get relations
attributes = attributes_with_association_ids attributes = attributes_with_association_ids
self.class.reflect_on_all_associations.map { |assoc| self.class.reflect_on_all_associations.map do |assoc|
next if !respond_to?(assoc.name) next if !respond_to?(assoc.name)
next if association_attributes_ignored.include?(assoc.name) next if association_attributes_ignored.include?(assoc.name)
ref = send(assoc.name) ref = send(assoc.name)
next if !ref next if !ref
if ref.respond_to?(:first) if ref.respond_to?(:first)
attributes[assoc.name.to_s] = [] attributes[assoc.name.to_s] = []
ref.each { |item| ref.each do |item|
if item[:login] if item[:login]
attributes[assoc.name.to_s].push item[:login] attributes[assoc.name.to_s].push item[:login]
next next
end end
next if !item[:name] next if !item[:name]
attributes[assoc.name.to_s].push item[:name] attributes[assoc.name.to_s].push item[:name]
} end
if ref.count.positive? && attributes[assoc.name.to_s].empty? if ref.count.positive? && attributes[assoc.name.to_s].empty?
attributes.delete(assoc.name.to_s) attributes.delete(assoc.name.to_s)
end end
@ -171,7 +171,7 @@ returns
end end
next if !ref[:name] next if !ref[:name]
attributes[assoc.name.to_s] = ref[:name] attributes[assoc.name.to_s] = ref[:name]
} end
# special handling for group access associations # special handling for group access associations
if respond_to?(:group_names_access_map) if respond_to?(:group_names_access_map)
@ -182,12 +182,12 @@ returns
{ {
'created_by_id' => 'created_by', 'created_by_id' => 'created_by',
'updated_by_id' => 'updated_by', 'updated_by_id' => 'updated_by',
}.each { |source, destination| }.each do |source, destination|
next if !attributes[source] next if !attributes[source]
user = User.lookup(id: attributes[source]) user = User.lookup(id: attributes[source])
next if !user next if !user
attributes[destination] = user.login attributes[destination] = user.login
} end
filter_attributes(attributes) filter_attributes(attributes)
@ -196,9 +196,9 @@ returns
def filter_attributes(attributes) def filter_attributes(attributes)
# remove forbitten attributes # remove forbitten attributes
%w(password token tokens token_ids).each { |item| %w(password token tokens token_ids).each do |item|
attributes.delete(item) attributes.delete(item)
} end
end end
=begin =begin
@ -217,22 +217,22 @@ returns
def association_id_validation(attribute_id, value) def association_id_validation(attribute_id, value)
return true if value.nil? return true if value.nil?
attributes.each { |key, _value| attributes.each do |key, _value|
next if key != attribute_id next if key != attribute_id
# check if id is assigned # check if id is assigned
next if !key.end_with?('_id') next if !key.end_with?('_id')
key_short = key.chomp('_id') key_short = key.chomp('_id')
self.class.reflect_on_all_associations.map { |assoc| self.class.reflect_on_all_associations.map do |assoc|
next if assoc.name.to_s != key_short next if assoc.name.to_s != key_short
item = assoc.class_name.constantize item = assoc.class_name.constantize
return false if !item.respond_to?(:find_by) return false if !item.respond_to?(:find_by)
ref_object = item.find_by(id: value) ref_object = item.find_by(id: value)
return false if !ref_object return false if !ref_object
return true return true
} end
} end
true true
end end
@ -298,13 +298,13 @@ returns
end end
data = {} data = {}
params.each { |key, value| params.each do |key, value|
data[key.to_sym] = value data[key.to_sym] = value
} end
data.symbolize_keys! data.symbolize_keys!
available_attributes = attribute_names available_attributes = attribute_names
reflect_on_all_associations.map { |assoc| reflect_on_all_associations.map do |assoc|
assoc_name = assoc.name assoc_name = assoc.name
value = data[assoc_name] value = data[assoc_name]
@ -360,7 +360,7 @@ returns
# get association class and do lookup # get association class and do lookup
class_object = assoc.klass class_object = assoc.klass
lookup_ids = [] lookup_ids = []
value.each { |item| value.each do |item|
lookup = nil lookup = nil
if class_object == User if class_object == User
if item.instance_of?(String) if item.instance_of?(String)
@ -382,14 +382,14 @@ returns
raise ArgumentError, "No lookup value found for '#{assoc_name}': #{item.inspect}" raise ArgumentError, "No lookup value found for '#{assoc_name}': #{item.inspect}"
end end
lookup_ids.push lookup.id lookup_ids.push lookup.id
} end
# release data value # release data value
data.delete(assoc_name) data.delete(assoc_name)
# remember id reference # remember id reference
data[ref_names.to_sym] = lookup_ids data[ref_names.to_sym] = lookup_ids
} end
data data
end end

View file

@ -32,9 +32,9 @@ returns
end end
data = {} data = {}
params.each { |key, value| params.each do |key, value|
data[key.to_sym] = value data[key.to_sym] = value
} end
# ignore id for new objects # ignore id for new objects
if new_object && params[:id] if new_object && params[:id]
@ -43,11 +43,11 @@ returns
# only use object attributes # only use object attributes
clean_params = {} clean_params = {}
new.attributes.each { |attribute, _value| new.attributes.each do |attribute, _value|
next if !data.key?(attribute.to_sym) next if !data.key?(attribute.to_sym)
# check reference records, referenced by _id attributes # check reference records, referenced by _id attributes
reflect_on_all_associations.map { |assoc| reflect_on_all_associations.map do |assoc|
class_name = assoc.options[:class_name] class_name = assoc.options[:class_name]
next if !class_name next if !class_name
name = "#{assoc.name}_id".to_sym name = "#{assoc.name}_id".to_sym
@ -55,9 +55,9 @@ returns
next if data[name].blank? next if data[name].blank?
next if assoc.klass.lookup(id: data[name]) next if assoc.klass.lookup(id: data[name])
raise ArgumentError, "Invalid value for param '#{name}': #{data[name].inspect}" raise ArgumentError, "Invalid value for param '#{name}': #{data[name].inspect}"
} end
clean_params[attribute.to_sym] = data[attribute.to_sym] clean_params[attribute.to_sym] = data[attribute.to_sym]
} end
# we do want to set this via database # we do want to set this via database
filter_unused_params(clean_params) filter_unused_params(clean_params)
@ -80,9 +80,9 @@ returns
def filter_unused_params(data) def filter_unused_params(data)
# we do want to set this via database # we do want to set this via database
[:action, :controller, :updated_at, :created_at, :updated_by_id, :created_by_id, :updated_by, :created_by].each { |key| [:action, :controller, :updated_at, :created_at, :updated_by_id, :created_by_id, :updated_by, :created_by].each do |key|
data.delete(key) data.delete(key)
} end
data data
end end

View file

@ -29,9 +29,9 @@ returns
else else
where(name: data[:name]) where(name: data[:name])
end end
records.each { |loop_record| records.each do |loop_record|
return loop_record if loop_record.name == data[:name] return loop_record if loop_record.name == data[:name]
} end
elsif data[:login] elsif data[:login]
# do lookup with == to handle case insensitive databases # do lookup with == to handle case insensitive databases
@ -40,9 +40,9 @@ returns
else else
where(login: data[:login]) where(login: data[:login])
end end
records.each { |loop_record| records.each do |loop_record|
return loop_record if loop_record.login == data[:login] return loop_record if loop_record.login == data[:login]
} end
elsif data[:email] elsif data[:email]
# do lookup with == to handle case insensitive databases # do lookup with == to handle case insensitive databases
@ -51,9 +51,9 @@ returns
else else
where(email: data[:email]) where(email: data[:email])
end end
records.each { |loop_record| records.each do |loop_record|
return loop_record if loop_record.email == data[:email] return loop_record if loop_record.email == data[:email]
} end
elsif data[:locale] && data[:source] elsif data[:locale] && data[:source]
# do lookup with == to handle case insensitive databases # do lookup with == to handle case insensitive databases
@ -62,9 +62,9 @@ returns
else else
where(locale: data[:locale], source: data[:source]) where(locale: data[:locale], source: data[:source])
end end
records.each { |loop_record| records.each do |loop_record|
return loop_record if loop_record.source == data[:source] return loop_record if loop_record.source == data[:source]
} end
end end
create(data) create(data)
end end
@ -133,12 +133,12 @@ returns
else else
where(name: data[:name]) where(name: data[:name])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.name == data[:name] if loop_record.name == data[:name]
loop_record.update!(data) loop_record.update!(data)
return loop_record return loop_record
end end
} end
record = new(data) record = new(data)
record.save record.save
return record return record
@ -150,12 +150,12 @@ returns
else else
where(login: data[:login]) where(login: data[:login])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.login.casecmp(data[:login]).zero? if loop_record.login.casecmp(data[:login]).zero?
loop_record.update!(data) loop_record.update!(data)
return loop_record return loop_record
end end
} end
record = new(data) record = new(data)
record.save record.save
return record return record
@ -167,12 +167,12 @@ returns
else else
where(email: data[:email]) where(email: data[:email])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.email.casecmp(data[:email]).zero? if loop_record.email.casecmp(data[:email]).zero?
loop_record.update!(data) loop_record.update!(data)
return loop_record return loop_record
end end
} end
record = new(data) record = new(data)
record.save record.save
return record return record
@ -184,12 +184,12 @@ returns
else else
where(locale: data[:locale]) where(locale: data[:locale])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.locale.casecmp(data[:locale]).zero? if loop_record.locale.casecmp(data[:locale]).zero?
loop_record.update!(data) loop_record.update!(data)
return loop_record return loop_record
end end
} end
record = new(data) record = new(data)
record.save record.save
return record return record

View file

@ -38,12 +38,12 @@ returns
else else
where(name: data[:name]) where(name: data[:name])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.name == data[:name] if loop_record.name == data[:name]
cache_set(data[:name], loop_record) cache_set(data[:name], loop_record)
return loop_record return loop_record
end end
} end
return return
elsif data[:login] elsif data[:login]
cache = cache_get(data[:login]) cache = cache_get(data[:login])
@ -55,12 +55,12 @@ returns
else else
where(login: data[:login]) where(login: data[:login])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.login == data[:login] if loop_record.login == data[:login]
cache_set(data[:login], loop_record) cache_set(data[:login], loop_record)
return loop_record return loop_record
end end
} end
return return
elsif data[:email] elsif data[:email]
cache = cache_get(data[:email]) cache = cache_get(data[:email])
@ -72,12 +72,12 @@ returns
else else
where(email: data[:email]) where(email: data[:email])
end end
records.each { |loop_record| records.each do |loop_record|
if loop_record.email == data[:email] if loop_record.email == data[:email]
cache_set(data[:email], loop_record) cache_set(data[:email], loop_record)
return loop_record return loop_record
end end
} end
return return
end end

View file

@ -18,7 +18,7 @@ returns
def search_index_attribute_lookup def search_index_attribute_lookup
attributes = self.attributes attributes = self.attributes
self.attributes.each { |key, value| self.attributes.each do |key, value|
next if !value next if !value
# get attribute name # get attribute name
@ -52,14 +52,14 @@ returns
# save name of ref object # save name of ref object
attributes[ attribute_name ] = value attributes[ attribute_name ] = value
} end
ignored_attributes = self.class.instance_variable_get(:@search_index_attributes_ignored) || [] ignored_attributes = self.class.instance_variable_get(:@search_index_attributes_ignored) || []
return attributes if ignored_attributes.blank? return attributes if ignored_attributes.blank?
ignored_attributes.each { |attribute| ignored_attributes.each do |attribute|
attributes.delete(attribute.to_s) attributes.delete(attribute.to_s)
} end
attributes attributes
end end

View file

@ -17,7 +17,7 @@ module ApplicationModel::ChecksAttributeValuesAndLength
def check_attribute_values_and_length def check_attribute_values_and_length
columns = self.class.columns_hash columns = self.class.columns_hash
attributes.each { |name, value| attributes.each do |name, value|
next if value.blank? next if value.blank?
next if !value.instance_of?(String) next if !value.instance_of?(String)
column = columns[name] column = columns[name]
@ -52,7 +52,7 @@ module ApplicationModel::ChecksAttributeValuesAndLength
# strip 4 bytes utf8 chars if needed (mysql/mariadb will complain it) # strip 4 bytes utf8 chars if needed (mysql/mariadb will complain it)
next if self[name].blank? next if self[name].blank?
self[name] = self[name].utf8_to_3bytesutf8 self[name] = self[name].utf8_to_3bytesutf8
} end
true true
end end
end end

View file

@ -36,9 +36,9 @@ module ApplicationModel::HasCache
keys.push "#{self.class}::#{login}" keys.push "#{self.class}::#{login}"
end end
keys.each { |key| keys.each do |key|
Cache.delete(key) Cache.delete(key)
} end
# delete old name / login caches # delete old name / login caches
if saved_changes? if saved_changes?

View file

@ -108,11 +108,11 @@ returns
def self.timezones def self.timezones
list = {} list = {}
TZInfo::Timezone.all_country_zone_identifiers.each { |timezone| TZInfo::Timezone.all_country_zone_identifiers.each do |timezone|
t = TZInfo::Timezone.get(timezone) t = TZInfo::Timezone.get(timezone)
diff = t.current_period.utc_total_offset / 60 / 60 diff = t.current_period.utc_total_offset / 60 / 60
list[ timezone ] = diff list[ timezone ] = diff
} end
list list
end end
@ -168,14 +168,14 @@ returns
end end
# remove old ical entries if feed has changed # remove old ical entries if feed has changed
public_holidays.each { |day, meta| public_holidays.each do |day, meta|
next if !public_holidays[day]['feed'] next if !public_holidays[day]['feed']
next if meta['feed'] == Digest::MD5.hexdigest(ical_url) next if meta['feed'] == Digest::MD5.hexdigest(ical_url)
public_holidays.delete(day) public_holidays.delete(day)
} end
# sync new ical feed dates # sync new ical feed dates
events.each { |day, summary| events.each do |day, summary|
if !public_holidays[day] if !public_holidays[day]
public_holidays[day] = {} public_holidays[day] = {}
end end
@ -189,7 +189,7 @@ returns
summary: summary, summary: summary,
feed: Digest::MD5.hexdigest(ical_url) feed: Digest::MD5.hexdigest(ical_url)
} }
} end
self.last_log = nil self.last_log = nil
if id if id
Cache.write( Cache.write(
@ -223,7 +223,7 @@ returns
cals = Icalendar::Calendar.parse(cal_file) cals = Icalendar::Calendar.parse(cal_file)
cal = cals.first cal = cals.first
events = {} events = {}
cal.events.each { |event| cal.events.each do |event|
if event.rrule if event.rrule
# loop till days # loop till days
@ -231,11 +231,11 @@ returns
interval_frame_end = Date.parse("#{Time.zone.now + 3.years}-12-31") interval_frame_end = Date.parse("#{Time.zone.now + 3.years}-12-31")
occurrences = event.occurrences_between(interval_frame_start, interval_frame_end) occurrences = event.occurrences_between(interval_frame_start, interval_frame_end)
if occurrences.present? if occurrences.present?
occurrences.each { |occurrence| occurrences.each do |occurrence|
result = Calendar.day_and_comment_by_event(event, occurrence.start_time) result = Calendar.day_and_comment_by_event(event, occurrence.start_time)
next if !result next if !result
events[result[0]] = result[1] events[result[0]] = result[1]
} end
end end
end end
next if event.dtstart < Time.zone.now - 1.year next if event.dtstart < Time.zone.now - 1.year
@ -243,7 +243,7 @@ returns
result = Calendar.day_and_comment_by_event(event, event.dtstart) result = Calendar.day_and_comment_by_event(event, event.dtstart)
next if !result next if !result
events[result[0]] = result[1] events[result[0]] = result[1]
} end
events.sort.to_h events.sort.to_h
end end
@ -266,12 +266,12 @@ returns
# if changed calendar is default, set all others default to false # if changed calendar is default, set all others default to false
def sync_default def sync_default
return true if !default return true if !default
Calendar.find_each { |calendar| Calendar.find_each do |calendar|
next if calendar.id == id next if calendar.id == id
next if !calendar.default next if !calendar.default
calendar.default = false calendar.default = false
calendar.save calendar.save
} end
true true
end end
@ -286,7 +286,7 @@ returns
# check if sla's are refer to an existing calendar # check if sla's are refer to an existing calendar
default_calendar = Calendar.find_by(default: true) default_calendar = Calendar.find_by(default: true)
Sla.find_each { |sla| Sla.find_each do |sla|
if !sla.calendar_id if !sla.calendar_id
sla.calendar_id = default_calendar.id sla.calendar_id = default_calendar.id
sla.save! sla.save!
@ -296,7 +296,7 @@ returns
sla.calendar_id = default_calendar.id sla.calendar_id = default_calendar.id
sla.save! sla.save!
end end
} end
true true
end end
@ -311,7 +311,7 @@ returns
# fillup feed info # fillup feed info
before = public_holidays_was before = public_holidays_was
public_holidays.each { |day, meta| public_holidays.each do |day, meta|
if before && before[day] && before[day]['feed'] if before && before[day] && before[day]['feed']
meta['feed'] = before[day]['feed'] meta['feed'] = before[day]['feed']
end end
@ -320,7 +320,7 @@ returns
else else
false false
end end
} end
true true
end end
end end

View file

@ -15,6 +15,7 @@ class Channel < ApplicationModel
# rubocop:disable Style/ClassVars # rubocop:disable Style/ClassVars
@@channel_stream = {} @@channel_stream = {}
@@channel_stream_started_till_at = {}
# rubocop:enable Style/ClassVars # rubocop:enable Style/ClassVars
=begin =begin
@ -63,7 +64,7 @@ fetch one account
self.status_in = result[:result] self.status_in = result[:result]
self.last_log_in = result[:notice] self.last_log_in = result[:notice]
preferences[:last_fetch] = Time.zone.now preferences[:last_fetch] = Time.zone.now
save save!
rescue => e rescue => e
error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}" error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}"
logger.error error logger.error error
@ -71,7 +72,7 @@ fetch one account
self.status_in = 'error' self.status_in = 'error'
self.last_log_in = error self.last_log_in = error
preferences[:last_fetch] = Time.zone.now preferences[:last_fetch] = Time.zone.now
save save!
end end
end end
@ -116,7 +117,7 @@ stream instance of account
logger.error e.backtrace logger.error e.backtrace
self.status_in = 'error' self.status_in = 'error'
self.last_log_in = error self.last_log_in = error
save save!
end end
end end
@ -132,7 +133,7 @@ stream all accounts
def self.stream def self.stream
Thread.abort_on_exception = true Thread.abort_on_exception = true
auto_reconnect_after = 25 auto_reconnect_after = 180
last_channels = [] last_channels = []
loop do loop do
@ -140,12 +141,21 @@ stream all accounts
current_channels = [] current_channels = []
channels = Channel.where('active = ? AND area LIKE ?', true, '%::Account') channels = Channel.where('active = ? AND area LIKE ?', true, '%::Account')
channels.each { |channel| channels.each do |channel|
next if channel.options[:adapter] != 'twitter' adapter = channel.options[:adapter]
driver_class = Object.const_get("Channel::Driver::#{adapter.to_classname}")
next if !driver_class.respond_to?(:streamable?)
next if !driver_class.streamable?
channel_id = channel.id.to_s channel_id = channel.id.to_s
if @@channel_stream[channel_id].blank? && @@channel_stream_started_till_at[channel_id] && @@channel_stream_started_till_at[channel_id] > Time.zone.now - 65.seconds
logger.info "skipp channel (#{channel_id}) for streaming, already tried to connect or connection was active within the last minute"
next
end
current_channels.push channel_id current_channels.push channel_id
# exit it channel has changed or connection is older then 25 min. # exit it channel has changed or connection is older then 180 minutes
if @@channel_stream[channel_id] if @@channel_stream[channel_id]
if @@channel_stream[channel_id][:updated_at] != channel.updated_at if @@channel_stream[channel_id][:updated_at] != channel.updated_at
logger.info "channel (#{channel.id}) has changed, stop thread" logger.info "channel (#{channel.id}) has changed, stop thread"
@ -153,12 +163,14 @@ stream all accounts
@@channel_stream[channel_id][:thread].join @@channel_stream[channel_id][:thread].join
@@channel_stream[channel_id][:stream_instance].disconnect @@channel_stream[channel_id][:stream_instance].disconnect
@@channel_stream[channel_id] = false @@channel_stream[channel_id] = false
@@channel_stream_started_till_at[channel_id] = Time.zone.now
elsif @@channel_stream[channel_id][:started_at] && @@channel_stream[channel_id][:started_at] < Time.zone.now - auto_reconnect_after.minutes elsif @@channel_stream[channel_id][:started_at] && @@channel_stream[channel_id][:started_at] < Time.zone.now - auto_reconnect_after.minutes
logger.info "channel (#{channel.id}) reconnect - thread is older then #{auto_reconnect_after} minutes, restart thread" logger.info "channel (#{channel.id}) reconnect - thread is older then #{auto_reconnect_after} minutes, restart thread"
@@channel_stream[channel_id][:thread].exit @@channel_stream[channel_id][:thread].exit
@@channel_stream[channel_id][:thread].join @@channel_stream[channel_id][:thread].join
@@channel_stream[channel_id][:stream_instance].disconnect @@channel_stream[channel_id][:stream_instance].disconnect
@@channel_stream[channel_id] = false @@channel_stream[channel_id] = false
@@channel_stream_started_till_at[channel_id] = Time.zone.now
end end
end end
@ -174,37 +186,44 @@ stream all accounts
sleep @@channel_stream.count sleep @@channel_stream.count
# start threads for each channel # start threads for each channel
@@channel_stream[channel_id][:thread] = Thread.new { @@channel_stream[channel_id][:thread] = Thread.new do
begin begin
logger.info "Started stream channel for '#{channel.id}' (#{channel.area})..." logger.info "Started stream channel for '#{channel.id}' (#{channel.area})..."
channel.status_in = 'ok'
channel.last_log_in = ''
channel.save!
@@channel_stream_started_till_at[channel_id] = Time.zone.now
@@channel_stream[channel_id] ||= {} @@channel_stream[channel_id] ||= {}
@@channel_stream[channel_id][:stream_instance] = channel.stream_instance @@channel_stream[channel_id][:stream_instance] = channel.stream_instance
@@channel_stream[channel_id][:stream_instance].stream @@channel_stream[channel_id][:stream_instance].stream
@@channel_stream[channel_id][:stream_instance].disconnect @@channel_stream[channel_id][:stream_instance].disconnect
@@channel_stream[channel_id] = false @@channel_stream[channel_id] = false
logger.info " ...stopped thread for '#{channel.id}'" @@channel_stream_started_till_at[channel_id] = Time.zone.now
logger.info " ...stopped stream thread for '#{channel.id}'"
rescue => e rescue => e
error = "Can't use channel (#{channel.id}): #{e.inspect}" error = "Can't use stream for channel (#{channel.id}): #{e.inspect}"
logger.error error logger.error error
logger.error e.backtrace logger.error e.backtrace
channel.status_in = 'error' channel.status_in = 'error'
channel.last_log_in = error channel.last_log_in = error
channel.save channel.save!
@@channel_stream[channel_id] = false @@channel_stream[channel_id] = false
end end
} end
} end
# cleanup deleted channels # cleanup deleted channels
last_channels.each { |channel_id| last_channels.each do |channel_id|
next if !@@channel_stream[channel_id.to_s] next if @@channel_stream[channel_id].blank?
next if current_channels.include?(channel_id) next if current_channels.include?(channel_id)
logger.info "channel (#{channel_id}) not longer active, stop thread" logger.info "channel (#{channel_id}) not longer active, stop stream thread"
@@channel_stream[channel_id.to_s][:thread].exit @@channel_stream[channel_id][:thread].exit
@@channel_stream[channel_id.to_s][:thread].join @@channel_stream[channel_id][:thread].join
@@channel_stream[channel_id.to_s][:stream_instance].disconnect @@channel_stream[channel_id][:stream_instance].disconnect
@@channel_stream[channel_id.to_s] = false @@channel_stream[channel_id] = false
} @@channel_stream_started_till_at[channel_id] = Time.zone.now
end
last_channels = current_channels last_channels = current_channels
sleep 20 sleep 20
@ -245,14 +264,14 @@ send via account
result = driver_instance.send(adapter_options, mail_params, notification) result = driver_instance.send(adapter_options, mail_params, notification)
self.status_out = 'ok' self.status_out = 'ok'
self.last_log_out = '' self.last_log_out = ''
save save!
rescue => e rescue => e
error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}" error = "Can't use Channel::Driver::#{adapter.to_classname}: #{e.inspect}"
logger.error error logger.error error
logger.error e.backtrace logger.error e.backtrace
self.status_out = 'error' self.status_out = 'error'
self.last_log_out = error self.last_log_out = error
save save!
raise error raise error
end end
result result

View file

@ -40,24 +40,24 @@ returns
end end
end end
if !access if !access
%w(inbound outbound).each { |key| %w(inbound outbound).each do |key|
if attributes['options'] && attributes['options'][key] && attributes['options'][key]['options'] if attributes['options'] && attributes['options'][key] && attributes['options'][key]['options']
attributes['options'][key]['options'].delete('password') attributes['options'][key]['options'].delete('password')
end end
} end
end end
data[ self.class.to_app_model ][ id ] = attributes data[ self.class.to_app_model ][ id ] = attributes
end end
return data if !self['created_by_id'] && !self['updated_by_id'] return data if !self['created_by_id'] && !self['updated_by_id']
%w(created_by_id updated_by_id).each { |local_user_id| %w(created_by_id updated_by_id).each do |local_user_id|
next if !self[ local_user_id ] next if !self[ local_user_id ]
next if data[ User.to_app_model ] && data[ User.to_app_model ][ self[ local_user_id ] ] next if data[ User.to_app_model ] && data[ User.to_app_model ][ self[ local_user_id ] ]
user = User.lookup(id: self[ local_user_id ]) user = User.lookup(id: self[ local_user_id ])
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
data data
end end

View file

@ -31,10 +31,10 @@ class Channel::Driver::Facebook
def send(options, fb_object_id, article, _notification = false) def send(options, fb_object_id, article, _notification = false)
access_token = nil access_token = nil
options['pages'].each { |page| options['pages'].each do |page|
next if page['id'].to_s != fb_object_id.to_s next if page['id'].to_s != fb_object_id.to_s
access_token = page['access_token'] access_token = page['access_token']
} end
if !access_token if !access_token
raise "No access_token found for fb_object_id: #{fb_object_id}" raise "No access_token found for fb_object_id: #{fb_object_id}"
end end
@ -63,12 +63,26 @@ class Channel::Driver::Facebook
def disconnect def disconnect
end end
=begin
Channel::Driver::Facebook.streamable?
returns
true|false
=end
def self.streamable?
false
end
private private
def get_page(page_id) def get_page(page_id)
@pages.each { |page| @pages.each do |page|
return page if page['id'].to_s == page_id.to_s return page if page['id'].to_s == page_id.to_s
} end
nil nil
end end
@ -79,14 +93,14 @@ class Channel::Driver::Facebook
older_import = 0 older_import = 0
older_import_max = 12 older_import_max = 12
@sync['pages'].each { |page_to_sync_id, page_to_sync_params| @sync['pages'].each do |page_to_sync_id, page_to_sync_params|
page = get_page(page_to_sync_id) page = get_page(page_to_sync_id)
next if !page next if !page
next if page_to_sync_params['group_id'].blank? next if page_to_sync_params['group_id'].blank?
page_client = Facebook.new(page['access_token']) page_client = Facebook.new(page['access_token'])
posts = page_client.client.get_connection('me', 'feed', fields: 'id,from,to,message,created_time,permalink_url,comments{id,from,to,message,created_time}') posts = page_client.client.get_connection('me', 'feed', fields: 'id,from,to,message,created_time,permalink_url,comments{id,from,to,message,created_time}')
posts.each { |post| posts.each do |post|
# ignore older messages # ignore older messages
if (@channel.created_at - 15.days) > Time.zone.parse(post['created_time']) || older_import >= older_import_max if (@channel.created_at - 15.days) > Time.zone.parse(post['created_time']) || older_import >= older_import_max
@ -96,8 +110,8 @@ class Channel::Driver::Facebook
end end
page_client.to_group(post, page_to_sync_params['group_id'], @channel, page) page_client.to_group(post, page_to_sync_params['group_id'], @channel, page)
} end
} end
true true
end end

View file

@ -44,7 +44,7 @@ returns
=end =end
def fetch (options, channel, check_type = '', verify_string = '') def fetch(options, channel, check_type = '', verify_string = '')
ssl = true ssl = true
port = 995 port = 995
if options.key?(:ssl) && options[:ssl] == false if options.key?(:ssl) && options[:ssl] == false
@ -180,6 +180,20 @@ returns
true true
end end
=begin
Channel::Driver::Pop3.streamable?
returns
true|false
=end
def self.streamable?
false
end
def disconnect def disconnect
return if !@pop return if !@pop
@pop.finish @pop.finish

View file

@ -30,6 +30,20 @@ class Channel::Driver::Telegram
message message
end end
=begin
Channel::Driver::Telegram.streamable?
returns
true|false
=end
def self.streamable?
false
end
private private
def check_external_credential(options) def check_external_credential(options)

View file

@ -123,6 +123,20 @@ returns
@rest_client.disconnect if @rest_client @rest_client.disconnect if @rest_client
end end
=begin
Channel::Driver::Twitter.streamable?
returns
true|false
=end
def self.streamable?
true
end
=begin =begin
create stream endpoint form twitter account create stream endpoint form twitter account
@ -183,8 +197,8 @@ returns
=end =end
def stream def stream
sleep_on_unauthorized = 61 sleep_on_unauthorized = 65
2.times { |loop_count| 2.times do |loop_count|
begin begin
stream_start stream_start
rescue Twitter::Error::Unauthorized => e rescue Twitter::Error::Unauthorized => e
@ -196,7 +210,7 @@ returns
raise "Unable to stream, try #{loop_count}, error #{e.inspect}" raise "Unable to stream, try #{loop_count}, error #{e.inspect}"
end end
end end
} end
end end
def stream_start def stream_start
@ -207,9 +221,9 @@ returns
filter = {} filter = {}
if sync['search'] if sync['search']
hashtags = [] hashtags = []
sync['search'].each { |item| sync['search'].each do |item|
hashtags.push item['term'] hashtags.push item['term']
} end
filter[:track] = hashtags.join(',') filter[:track] = hashtags.join(',')
end end
if sync['mentions'] && sync['mentions']['group_id'] != '' if sync['mentions'] && sync['mentions']['group_id'] != ''
@ -242,11 +256,11 @@ returns
if sync['mentions'] && sync['mentions']['group_id'] != '' if sync['mentions'] && sync['mentions']['group_id'] != ''
hit = false hit = false
if tweet.user_mentions if tweet.user_mentions
tweet.user_mentions.each { |user| tweet.user_mentions.each do |user|
if user.id.to_s == @channel.options['user']['id'].to_s if user.id.to_s == @channel.options['user']['id'].to_s
hit = true hit = true
end end
} end
end end
if hit if hit
@stream_client.to_group(tweet, sync['mentions']['group_id'], @channel) @stream_client.to_group(tweet, sync['mentions']['group_id'], @channel)
@ -257,14 +271,14 @@ returns
# check hashtags # check hashtags
if sync['search'] && tweet.hashtags if sync['search'] && tweet.hashtags
hit = false hit = false
sync['search'].each { |item| sync['search'].each do |item|
tweet.hashtags.each { |hashtag| tweet.hashtags.each do |hashtag|
next if item['term'] !~ /^#/ next if item['term'] !~ /^#/
if item['term'].sub(/^#/, '') == hashtag.text if item['term'].sub(/^#/, '') == hashtag.text
hit = item hit = item
end end
} end
} end
if hit if hit
@stream_client.to_group(tweet, hit['group_id'], @channel) @stream_client.to_group(tweet, hit['group_id'], @channel)
next next
@ -275,12 +289,12 @@ returns
if sync['search'] if sync['search']
hit = false hit = false
body = tweet.text body = tweet.text
sync['search'].each { |item| sync['search'].each do |item|
next if item['term'] =~ /^#/ next if item['term'] =~ /^#/
if body =~ /#{item['term']}/ if body =~ /#{item['term']}/
hit = item hit = item
end end
} end
if hit if hit
@stream_client.to_group(tweet, hit['group_id'], @channel) @stream_client.to_group(tweet, hit['group_id'], @channel)
end end
@ -293,14 +307,14 @@ returns
def fetch_search def fetch_search
return if @sync[:search].blank? return if @sync[:search].blank?
@sync[:search].each { |search| @sync[:search].each do |search|
next if search[:term].blank? next if search[:term].blank?
next if search[:group_id].blank? next if search[:group_id].blank?
result_type = search[:type] || 'mixed' result_type = search[:type] || 'mixed'
Rails.logger.debug " - searching for '#{search[:term]}'" Rails.logger.debug " - searching for '#{search[:term]}'"
older_import = 0 older_import = 0
older_import_max = 20 older_import_max = 20
@rest_client.client.search(search[:term], result_type: result_type).collect { |tweet| @rest_client.client.search(search[:term], result_type: result_type).collect do |tweet|
next if !track_retweets? && tweet.retweet? next if !track_retweets? && tweet.retweet?
# ignore older messages # ignore older messages
@ -314,8 +328,8 @@ returns
next if Ticket::Article.find_by(message_id: tweet.id) next if Ticket::Article.find_by(message_id: tweet.id)
break if @rest_client.tweet_limit_reached(tweet) break if @rest_client.tweet_limit_reached(tweet)
@rest_client.to_group(tweet, search[:group_id], @channel) @rest_client.to_group(tweet, search[:group_id], @channel)
} end
} end
end end
def fetch_mentions def fetch_mentions
@ -324,7 +338,7 @@ returns
Rails.logger.debug ' - searching for mentions' Rails.logger.debug ' - searching for mentions'
older_import = 0 older_import = 0
older_import_max = 20 older_import_max = 20
@rest_client.client.mentions_timeline.each { |tweet| @rest_client.client.mentions_timeline.each do |tweet|
next if !track_retweets? && tweet.retweet? next if !track_retweets? && tweet.retweet?
# ignore older messages # ignore older messages
@ -336,7 +350,7 @@ returns
next if Ticket::Article.find_by(message_id: tweet.id) next if Ticket::Article.find_by(message_id: tweet.id)
break if @rest_client.tweet_limit_reached(tweet) break if @rest_client.tweet_limit_reached(tweet)
@rest_client.to_group(tweet, @sync[:mentions][:group_id], @channel) @rest_client.to_group(tweet, @sync[:mentions][:group_id], @channel)
} end
end end
def fetch_direct_messages def fetch_direct_messages
@ -345,7 +359,7 @@ returns
Rails.logger.debug ' - searching for direct_messages' Rails.logger.debug ' - searching for direct_messages'
older_import = 0 older_import = 0
older_import_max = 20 older_import_max = 20
@rest_client.client.direct_messages(full_text: 'true').each { |tweet| @rest_client.client.direct_messages(full_text: 'true').each do |tweet|
# ignore older messages # ignore older messages
if (@channel.created_at - 15.days) > tweet.created_at.dup.utc || older_import >= older_import_max if (@channel.created_at - 15.days) > tweet.created_at.dup.utc || older_import >= older_import_max
@ -356,7 +370,7 @@ returns
next if Ticket::Article.find_by(message_id: tweet.id) next if Ticket::Article.find_by(message_id: tweet.id)
break if @rest_client.direct_message_limit_reached(tweet) break if @rest_client.direct_message_limit_reached(tweet)
@rest_client.to_group(tweet, @sync[:direct_messages][:group_id], @channel) @rest_client.to_group(tweet, @sync[:direct_messages][:group_id], @channel)
} end
end end
def check_external_credential(options) def check_external_credential(options)
@ -376,7 +390,7 @@ returns
def own_tweet_already_imported?(tweet) def own_tweet_already_imported?(tweet)
event_time = Time.zone.now event_time = Time.zone.now
sleep 4 sleep 4
12.times { |loop_count| 12.times do |loop_count|
if Ticket::Article.find_by(message_id: tweet.id) if Ticket::Article.find_by(message_id: tweet.id)
Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}" Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}"
return true return true
@ -387,7 +401,7 @@ returns
sleep_time = 5 if sleep_time > 5 sleep_time = 5 if sleep_time > 5
Rails.logger.debug "Delay importing own tweets - sleep #{sleep_time} (loop #{loop_count})" Rails.logger.debug "Delay importing own tweets - sleep #{sleep_time} (loop #{loop_count})"
sleep sleep_time sleep sleep_time
} end
if Ticket::Article.find_by(message_id: tweet.id) if Ticket::Article.find_by(message_id: tweet.id)
Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}" Rails.logger.debug "Own tweet already imported, skipping tweet #{tweet.id}"

View file

@ -74,7 +74,7 @@ class Channel::EmailParser
mail = Mail.new(msg) mail = Mail.new(msg)
# set all headers # set all headers
mail.header.fields.each { |field| mail.header.fields.each do |field|
# full line, encode, ready for storage # full line, encode, ready for storage
begin begin
@ -89,42 +89,42 @@ class Channel::EmailParser
# if we need to access the lines by objects later again # if we need to access the lines by objects later again
data["raw-#{field.name.downcase}".to_sym] = field data["raw-#{field.name.downcase}".to_sym] = field
} end
# verify content, ignore recipients with non email address # verify content, ignore recipients with non email address
['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each { |field| ['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each do |field|
next if data[field.to_sym].blank? next if data[field.to_sym].blank?
next if data[field.to_sym] =~ /@/ next if data[field.to_sym] =~ /@/
data[field.to_sym] = '' data[field.to_sym] = ''
} end
# get sender with @ / email address # get sender with @ / email address
from = nil from = nil
['from', 'reply-to', 'return-path'].each { |item| ['from', 'reply-to', 'return-path'].each do |item|
next if data[item.to_sym].blank? next if data[item.to_sym].blank?
next if data[item.to_sym] !~ /@/ next if data[item.to_sym] !~ /@/
from = data[item.to_sym] from = data[item.to_sym]
break if from break if from
} end
# in case of no sender with email address - get sender # in case of no sender with email address - get sender
if !from if !from
['from', 'reply-to', 'return-path'].each { |item| ['from', 'reply-to', 'return-path'].each do |item|
next if data[item.to_sym].blank? next if data[item.to_sym].blank?
from = data[item.to_sym] from = data[item.to_sym]
break if from break if from
} end
end end
# set x-any-recipient # set x-any-recipient
data['x-any-recipient'.to_sym] = '' data['x-any-recipient'.to_sym] = ''
['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each { |item| ['to', 'cc', 'delivered-to', 'x-original-to', 'envelope-to'].each do |item|
next if data[item.to_sym].blank? next if data[item.to_sym].blank?
if data['x-any-recipient'.to_sym] != '' if data['x-any-recipient'.to_sym] != ''
data['x-any-recipient'.to_sym] += ', ' data['x-any-recipient'.to_sym] += ', '
end end
data['x-any-recipient'.to_sym] += mail[item.to_sym].to_s data['x-any-recipient'.to_sym] += mail[item.to_sym].to_s
} end
# set extra headers # set extra headers
data = data.merge(Channel::EmailParser.sender_properties(from)) data = data.merge(Channel::EmailParser.sender_properties(from))
@ -197,7 +197,7 @@ class Channel::EmailParser
# get attachments # get attachments
if mail.parts if mail.parts
mail.parts.each { |part| mail.parts.each do |part|
# protect process to work fine with spam emails, see test/fixtures/mail15.box # protect process to work fine with spam emails, see test/fixtures/mail15.box
begin begin
@ -207,7 +207,7 @@ class Channel::EmailParser
attachs = _get_attachment(part, data[:attachments], mail) attachs = _get_attachment(part, data[:attachments], mail)
data[:attachments].concat(attachs) data[:attachments].concat(attachs)
end end
} end
end end
# not multipart email # not multipart email
@ -298,10 +298,10 @@ class Channel::EmailParser
# check if sub parts are available # check if sub parts are available
if !file.parts.empty? if !file.parts.empty?
a = [] a = []
file.parts.each { |p| file.parts.each do |p|
attachment = _get_attachment(p, attachments, mail) attachment = _get_attachment(p, attachments, mail)
a.concat(attachment) a.concat(attachment)
} end
return a return a
end end
@ -313,7 +313,7 @@ class Channel::EmailParser
# get file preferences # get file preferences
headers_store = {} headers_store = {}
file.header.fields.each { |field| file.header.fields.each do |field|
# full line, encode, ready for storage # full line, encode, ready for storage
begin begin
@ -325,7 +325,7 @@ class Channel::EmailParser
rescue => e rescue => e
headers_store[field.name.to_s] = field.raw_value headers_store[field.name.to_s] = field.raw_value
end end
} end
# get filename from content-disposition # get filename from content-disposition
filename = nil filename = nil
@ -364,16 +364,16 @@ class Channel::EmailParser
# generate file name # generate file name
if filename.blank? if filename.blank?
attachment_count = 0 attachment_count = 0
(1..1000).each { |count| (1..1000).each do |count|
filename_exists = false filename_exists = false
filename = 'file-' + count.to_s filename = 'file-' + count.to_s
attachments.each { |attachment| attachments.each do |attachment|
if attachment[:filename] == filename if attachment[:filename] == filename
filename_exists = true filename_exists = true
end end
} end
break if filename_exists == false break if filename_exists == false
} end
end end
# get mime type # get mime type
@ -443,9 +443,9 @@ returns
p 'ERROR: ' + e.inspect # rubocop:disable Rails/Output p 'ERROR: ' + e.inspect # rubocop:disable Rails/Output
Rails.logger.error message Rails.logger.error message
Rails.logger.error e Rails.logger.error e
File.open(filename, 'wb') { |file| File.open(filename, 'wb') do |file|
file.write msg file.write msg
} end
return false if exception == false return false if exception == false
raise e.inspect + e.backtrace.inspect raise e.inspect + e.backtrace.inspect
end end
@ -458,10 +458,10 @@ returns
# run postmaster pre filter # run postmaster pre filter
UserInfo.current_user_id = 1 UserInfo.current_user_id = 1
filters = {} filters = {}
Setting.where(area: 'Postmaster::PreFilter').order(:name).each { |setting| Setting.where(area: 'Postmaster::PreFilter').order(:name).each do |setting|
filters[setting.name] = Kernel.const_get(Setting.get(setting.name)) filters[setting.name] = Kernel.const_get(Setting.get(setting.name))
} end
filters.each { |_prio, backend| filters.each do |_prio, backend|
Rails.logger.debug "run postmaster pre filter #{backend}" Rails.logger.debug "run postmaster pre filter #{backend}"
begin begin
backend.run(channel, mail) backend.run(channel, mail)
@ -470,7 +470,7 @@ returns
Rails.logger.error e.inspect Rails.logger.error e.inspect
raise e raise e
end end
} end
# check ignore header # check ignore header
if mail['x-zammad-ignore'.to_sym] == 'true' || mail['x-zammad-ignore'.to_sym] == true if mail['x-zammad-ignore'.to_sym] == 'true' || mail['x-zammad-ignore'.to_sym] == true
@ -608,10 +608,10 @@ returns
# run postmaster post filter # run postmaster post filter
filters = {} filters = {}
Setting.where(area: 'Postmaster::PostFilter').order(:name).each { |setting| Setting.where(area: 'Postmaster::PostFilter').order(:name).each do |setting|
filters[setting.name] = Kernel.const_get(Setting.get(setting.name)) filters[setting.name] = Kernel.const_get(Setting.get(setting.name))
} end
filters.each { |_prio, backend| filters.each do |_prio, backend|
Rails.logger.debug "run postmaster post filter #{backend}" Rails.logger.debug "run postmaster post filter #{backend}"
begin begin
backend.run(channel, mail, ticket, article, session_user) backend.run(channel, mail, ticket, article, session_user)
@ -619,7 +619,7 @@ returns
Rails.logger.error "can't run postmaster post filter #{backend}" Rails.logger.error "can't run postmaster post filter #{backend}"
Rails.logger.error e.inspect Rails.logger.error e.inspect
end end
} end
# return new objects # return new objects
[ticket, article, session_user, mail] [ticket, article, session_user, mail]
@ -653,14 +653,14 @@ returns
return data if from.blank? return data if from.blank?
begin begin
list = Mail::AddressList.new(from) list = Mail::AddressList.new(from)
list.addresses.each { |address| list.addresses.each do |address|
data[:from_email] = address.address data[:from_email] = address.address
data[:from_local] = address.local data[:from_local] = address.local
data[:from_domain] = address.domain data[:from_domain] = address.domain
data[:from_display_name] = address.display_name || data[:from_display_name] = address.display_name ||
(address.comments && address.comments[0]) (address.comments && address.comments[0])
break if data[:from_email].present? && data[:from_email] =~ /@/ break if data[:from_email].present? && data[:from_email] =~ /@/
} end
rescue => e rescue => e
if from =~ /<>/ && from =~ /<.+?>/ if from =~ /<>/ && from =~ /<.+?>/
data = sender_properties(from.gsub(/<>/, '')) data = sender_properties(from.gsub(/<>/, ''))
@ -694,7 +694,7 @@ returns
def set_attributes_by_x_headers(item_object, header_name, mail, suffix = false) def set_attributes_by_x_headers(item_object, header_name, mail, suffix = false)
# loop all x-zammad-header-* headers # loop all x-zammad-header-* headers
item_object.attributes.each { |key, _value| item_object.attributes.each do |key, _value|
# ignore read only attributes # ignore read only attributes
next if key == 'updated_by_id' next if key == 'updated_by_id'
@ -711,8 +711,9 @@ returns
# only set value on _id if value/reference lookup exists # only set value on _id if value/reference lookup exists
if mail[ header.to_sym ] if mail[ header.to_sym ]
Rails.logger.info "set_attributes_by_x_headers header #{header} found #{mail[header.to_sym]}" Rails.logger.info "set_attributes_by_x_headers header #{header} found #{mail[header.to_sym]}"
item_object.class.reflect_on_all_associations.map { |assoc| item_object.class.reflect_on_all_associations.map do |assoc|
next if assoc.name.to_s != key_short next if assoc.name.to_s != key_short
@ -738,7 +739,7 @@ returns
item_object[key] = assoc_object.id item_object[key] = assoc_object.id
} end
end end
end end
@ -751,7 +752,7 @@ returns
Rails.logger.info "set_attributes_by_x_headers header #{header} found. Assign #{key}=#{mail[header.to_sym]}" Rails.logger.info "set_attributes_by_x_headers header #{header} found. Assign #{key}=#{mail[header.to_sym]}"
item_object[key] = mail[header.to_sym] item_object[key] = mail[header.to_sym]
end end
} end
end end
end end

View file

@ -9,7 +9,7 @@ module Channel::Filter::BounceDeliveryPermanentFailed
return if !mail[:attachments] return if !mail[:attachments]
# remember, do not send notifications to certain recipients again if failed permanent # remember, do not send notifications to certain recipients again if failed permanent
mail[:attachments].each { |attachment| mail[:attachments].each do |attachment|
next if !attachment[:preferences] next if !attachment[:preferences]
next if attachment[:preferences]['Mime-Type'] != 'message/rfc822' next if attachment[:preferences]['Mime-Type'] != 'message/rfc822'
next if !attachment[:data] next if !attachment[:data]
@ -28,19 +28,19 @@ module Channel::Filter::BounceDeliveryPermanentFailed
# get recipient of origin article, if only one - mark this user to not sent notifications anymore # get recipient of origin article, if only one - mark this user to not sent notifications anymore
recipients = [] recipients = []
if article.sender.name == 'System' || article.sender.name == 'Agent' if article.sender.name == 'System' || article.sender.name == 'Agent'
%w(to cc).each { |line| %w(to cc).each do |line|
next if article[line].blank? next if article[line].blank?
recipients = [] recipients = []
begin begin
list = Mail::AddressList.new(article[line]) list = Mail::AddressList.new(article[line])
list.addresses.each { |address| list.addresses.each do |address|
next if address.address.blank? next if address.address.blank?
recipients.push address.address.downcase recipients.push address.address.downcase
} end
rescue rescue
Rails.logger.info "Unable to parse email address in '#{article[line]}'" Rails.logger.info "Unable to parse email address in '#{article[line]}'"
end end
} end
if recipients.count > 1 if recipients.count > 1
recipients = [] recipients = []
end end
@ -56,16 +56,16 @@ module Channel::Filter::BounceDeliveryPermanentFailed
end end
# set user preferences # set user preferences
recipients.each { |recipient| recipients.each do |recipient|
users = User.where(email: recipient) users = User.where(email: recipient)
users.each { |user| users.each do |user|
next if !user next if !user
user.preferences[:mail_delivery_failed] = true user.preferences[:mail_delivery_failed] = true
user.preferences[:mail_delivery_failed_data] = Time.zone.now user.preferences[:mail_delivery_failed_data] = Time.zone.now
user.save! user.save!
} end
} end
} end
true true

View file

@ -9,7 +9,7 @@ module Channel::Filter::BounceFollowUpCheck
return if !mail[:attachments] return if !mail[:attachments]
return if mail[ 'x-zammad-ticket-id'.to_sym ] return if mail[ 'x-zammad-ticket-id'.to_sym ]
mail[:attachments].each { |attachment| mail[:attachments].each do |attachment|
next if !attachment[:preferences] next if !attachment[:preferences]
next if attachment[:preferences]['Mime-Type'] != 'message/rfc822' next if attachment[:preferences]['Mime-Type'] != 'message/rfc822'
next if !attachment[:data] next if !attachment[:data]
@ -25,7 +25,7 @@ module Channel::Filter::BounceFollowUpCheck
mail[ 'x-zammad-is-auto-response'.to_sym ] = true mail[ 'x-zammad-is-auto-response'.to_sym ] = true
return true return true
} end
end end
end end

View file

@ -7,11 +7,11 @@ module Channel::Filter::Database
# process postmaster filter # process postmaster filter
filters = PostmasterFilter.where(active: true, channel: 'email').order(:name, :created_at) filters = PostmasterFilter.where(active: true, channel: 'email').order(:name, :created_at)
filters.each { |filter| filters.each do |filter|
Rails.logger.info " process filter #{filter.name} ..." Rails.logger.info " process filter #{filter.name} ..."
all_matches_ok = true all_matches_ok = true
min_one_rule_exists = false min_one_rule_exists = false
filter[:match].each { |key, meta| filter[:match].each do |key, meta|
begin begin
next if meta.blank? || meta['value'].blank? next if meta.blank? || meta['value'].blank?
value = mail[ key.downcase.to_sym ] value = mail[ key.downcase.to_sym ]
@ -37,17 +37,17 @@ module Channel::Filter::Database
Rails.logger.error "can't use match rule #{match_rule} on #{value}" Rails.logger.error "can't use match rule #{match_rule} on #{value}"
Rails.logger.error e.inspect Rails.logger.error e.inspect
end end
} end
next if !min_one_rule_exists next if !min_one_rule_exists
next if !all_matches_ok next if !all_matches_ok
filter[:perform].each { |key, meta| filter[:perform].each do |key, meta|
next if !Channel::EmailParser.check_attributes_by_x_headers(key, meta['value']) next if !Channel::EmailParser.check_attributes_by_x_headers(key, meta['value'])
Rails.logger.info " perform '#{key.downcase}' = '#{meta.inspect}'" Rails.logger.info " perform '#{key.downcase}' = '#{meta.inspect}'"
mail[ key.downcase.to_sym ] = meta['value'] mail[ key.downcase.to_sym ] = meta['value']
} end
} end
end end

View file

@ -28,14 +28,14 @@ module Channel::Filter::FollowUpCheck
# get ticket# from attachment # get ticket# from attachment
if setting.include?('attachment') && mail[:attachments] if setting.include?('attachment') && mail[:attachments]
mail[:attachments].each { |attachment| mail[:attachments].each do |attachment|
next if !attachment[:data] next if !attachment[:data]
ticket = Ticket::Number.check(attachment[:data]) ticket = Ticket::Number.check(attachment[:data])
next if !ticket next if !ticket
Rails.logger.debug "Follow up for '##{ticket.number}' in attachment." Rails.logger.debug "Follow up for '##{ticket.number}' in attachment."
mail['x-zammad-ticket-id'.to_sym] = ticket.id mail['x-zammad-ticket-id'.to_sym] = ticket.id
return true return true
} end
end end
# get ticket# from references # get ticket# from references
@ -54,14 +54,14 @@ module Channel::Filter::FollowUpCheck
end end
if references != '' if references != ''
message_ids = references.split(/\s+/) message_ids = references.split(/\s+/)
message_ids.each { |message_id| message_ids.each do |message_id|
message_id_md5 = Digest::MD5.hexdigest(message_id) message_id_md5 = Digest::MD5.hexdigest(message_id)
article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first
next if !article next if !article
Rails.logger.debug "Follow up for '##{article.ticket.number}' in references." Rails.logger.debug "Follow up for '##{article.ticket.number}' in references."
mail['x-zammad-ticket-id'.to_sym] = article.ticket_id mail['x-zammad-ticket-id'.to_sym] = article.ticket_id
return true return true
} end
end end
end end
@ -81,7 +81,7 @@ module Channel::Filter::FollowUpCheck
end end
if references != '' if references != ''
message_ids = references.split(/\s+/) message_ids = references.split(/\s+/)
message_ids.each { |message_id| message_ids.each do |message_id|
message_id_md5 = Digest::MD5.hexdigest(message_id) message_id_md5 = Digest::MD5.hexdigest(message_id)
article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first article = Ticket::Article.where(message_id_md5: message_id_md5).order('created_at DESC, id DESC').limit(1).first
next if !article next if !article
@ -100,7 +100,7 @@ module Channel::Filter::FollowUpCheck
Rails.logger.debug "Follow up for '##{article.ticket.number}' in references with same subject as inital article." Rails.logger.debug "Follow up for '##{article.ticket.number}' in references with same subject as inital article."
mail['x-zammad-ticket-id'.to_sym] = article_first.ticket_id mail['x-zammad-ticket-id'.to_sym] = article_first.ticket_id
return true return true
} end
end end
end end

View file

@ -25,7 +25,7 @@ module Channel::Filter::FollowUpMerged
return if links.blank? return if links.blank?
merge_ticket = nil merge_ticket = nil
links.each { |link| links.each do |link|
next if link['link_type'] != 'parent' next if link['link_type'] != 'parent'
next if link['link_object'] != 'Ticket' next if link['link_object'] != 'Ticket'
@ -37,7 +37,7 @@ module Channel::Filter::FollowUpMerged
merge_ticket = check_ticket merge_ticket = check_ticket
break break
} end
merge_ticket merge_ticket
end end
end end

View file

@ -32,7 +32,7 @@ module Channel::Filter::IdentifySender
to = 'raw-to'.to_sym to = 'raw-to'.to_sym
if mail[to] && mail[to].addrs if mail[to] && mail[to].addrs
items = mail[to].addrs items = mail[to].addrs
items.each { |item| items.each do |item|
# skip if recipient is system email # skip if recipient is system email
next if EmailAddress.find_by(email: item.address.downcase) next if EmailAddress.find_by(email: item.address.downcase)
@ -43,7 +43,7 @@ module Channel::Filter::IdentifySender
email: item.address, email: item.address,
) )
break break
} end
end end
rescue => e rescue => e
Rails.logger.error 'ERROR: SenderIsSystemAddress: ' + e.inspect Rails.logger.error 'ERROR: SenderIsSystemAddress: ' + e.inspect
@ -89,12 +89,12 @@ module Channel::Filter::IdentifySender
def self.create_recipients(mail) def self.create_recipients(mail)
max_count = 40 max_count = 40
current_count = 0 current_count = 0
['raw-to', 'raw-cc'].each { |item| ['raw-to', 'raw-cc'].each do |item|
next if !mail[item.to_sym] next if !mail[item.to_sym]
begin begin
next if !mail[item.to_sym].addrs next if !mail[item.to_sym].addrs
items = mail[item.to_sym].addrs items = mail[item.to_sym].addrs
items.each { |address_data| items.each do |address_data|
next if address_data.address.blank? next if address_data.address.blank?
user_create( user_create(
firstname: address_data.display_name, firstname: address_data.display_name,
@ -103,7 +103,7 @@ module Channel::Filter::IdentifySender
) )
current_count += 1 current_count += 1
return false if current_count == max_count return false if current_count == max_count
} end
rescue => e rescue => e
# parse not parseable fields by mail gem like # parse not parseable fields by mail gem like
# - Max Kohl | [example.com] <kohl@example.com> # - Max Kohl | [example.com] <kohl@example.com>
@ -111,7 +111,7 @@ module Channel::Filter::IdentifySender
Rails.logger.error 'ERROR: ' + e.inspect Rails.logger.error 'ERROR: ' + e.inspect
Rails.logger.error "ERROR: try it by my self (#{item}): #{mail[item.to_sym]}" Rails.logger.error "ERROR: try it by my self (#{item}): #{mail[item.to_sym]}"
recipients = mail[item.to_sym].to_s.split(',') recipients = mail[item.to_sym].to_s.split(',')
recipients.each { |recipient| recipients.each do |recipient|
address = nil address = nil
display_name = nil display_name = nil
if recipient =~ /.*<(.+?)>/ if recipient =~ /.*<(.+?)>/
@ -128,9 +128,9 @@ module Channel::Filter::IdentifySender
) )
current_count += 1 current_count += 1
return false if current_count == max_count return false if current_count == max_count
} end
end end
} end
end end
def self.user_create(data) def self.user_create(data)
@ -159,12 +159,12 @@ module Channel::Filter::IdentifySender
role_ids = Role.signup_role_ids role_ids = Role.signup_role_ids
# fillup # fillup
%w(firstname lastname).each { |item| %w(firstname lastname).each do |item|
if data[item.to_sym].nil? if data[item.to_sym].nil?
data[item.to_sym] = '' data[item.to_sym] = ''
end end
data[item.to_sym] = cleanup_name(data[item.to_sym]) data[item.to_sym] = cleanup_name(data[item.to_sym])
} end
data[:password] = '' data[:password] = ''
data[:active] = true data[:active] = true
data[:role_ids] = role_ids data[:role_ids] = role_ids

View file

@ -31,7 +31,7 @@ class Channel::Filter::MonitoringBase
# get mail attibutes like host and state # get mail attibutes like host and state
result = {} result = {}
mail[:body].gsub(%r{(Service|Host|State|Address|Date/Time|Additional\sInfo|Info):(.+?)\n}i) { |_match| mail[:body].gsub(%r{(Service|Host|State|Address|Date/Time|Additional\sInfo|Info):(.+?)\n}i) do |_match|
key = $1 key = $1
if key if key
key = key.downcase key = key.downcase
@ -41,7 +41,7 @@ class Channel::Filter::MonitoringBase
value.strip! value.strip!
end end
result[key] = value result[key] = value
} end
# check min. params # check min. params
return if result['host'].blank? return if result['host'].blank?
@ -68,7 +68,7 @@ class Channel::Filter::MonitoringBase
# follow up detection by meta data # follow up detection by meta data
open_states = Ticket::State.by_category(:open) open_states = Ticket::State.by_category(:open)
ticket_ids = Ticket.where(state: open_states).order(created_at: :desc).limit(5000).pluck(:id) ticket_ids = Ticket.where(state: open_states).order(created_at: :desc).limit(5000).pluck(:id)
ticket_ids.each { |ticket_id| ticket_ids.each do |ticket_id|
ticket = Ticket.find_by(id: ticket_id) ticket = Ticket.find_by(id: ticket_id)
next if !ticket next if !ticket
next if !ticket.preferences next if !ticket.preferences
@ -89,7 +89,7 @@ class Channel::Filter::MonitoringBase
end end
end end
return true return true
} end
# new ticket, set meta data # new ticket, set meta data
if !mail[ 'x-zammad-ticket-id'.to_sym ] if !mail[ 'x-zammad-ticket-id'.to_sym ]
@ -98,9 +98,9 @@ class Channel::Filter::MonitoringBase
end end
preferences = {} preferences = {}
preferences[integration] = result preferences[integration] = result
preferences.each { |key, value| preferences.each do |key, value|
mail[ 'x-zammad-ticket-preferences'.to_sym ][key] = value mail[ 'x-zammad-ticket-preferences'.to_sym ][key] = value
} end
end end
# ignorte states # ignorte states

View file

@ -17,12 +17,12 @@ module Channel::Filter::SenderIsSystemAddress
begin begin
return if !mail[form].addrs return if !mail[form].addrs
items = mail[form].addrs items = mail[form].addrs
items.each { |item| items.each do |item|
next if !EmailAddress.find_by(email: item.address.downcase) next if !EmailAddress.find_by(email: item.address.downcase)
mail['x-zammad-ticket-create-article-sender'.to_sym] = 'Agent' mail['x-zammad-ticket-create-article-sender'.to_sym] = 'Agent'
mail['x-zammad-article-sender'.to_sym] = 'Agent' mail['x-zammad-article-sender'.to_sym] = 'Agent'
return true return true
} end
rescue => e rescue => e
Rails.logger.error 'ERROR: SenderIsSystemAddress: ' + e.inspect Rails.logger.error 'ERROR: SenderIsSystemAddress: ' + e.inspect
end end

View file

@ -7,21 +7,21 @@ module Channel::Filter::Trusted
# check if trust x-headers # check if trust x-headers
if !channel[:trusted] if !channel[:trusted]
mail.each { |key, _value| mail.each do |key, _value|
next if key !~ /^x-zammad/i next if key !~ /^x-zammad/i
mail.delete(key) mail.delete(key)
} end
return return
end end
# verify values # verify values
mail.each { |key, value| mail.each do |key, value|
next if key !~ /^x-zammad/i next if key !~ /^x-zammad/i
# no assoc exists, remove header # no assoc exists, remove header
next if Channel::EmailParser.check_attributes_by_x_headers(key, value) next if Channel::EmailParser.check_attributes_by_x_headers(key, value)
mail.delete(key.to_sym) mail.delete(key.to_sym)
} end
end end
end end

View file

@ -65,21 +65,21 @@ class Chat < ApplicationModel
def self.agent_state(user_id) def self.agent_state(user_id)
return { state: 'chat_disabled' } if !Setting.get('chat') return { state: 'chat_disabled' } if !Setting.get('chat')
assets = {} assets = {}
Chat.where(active: true).each { |chat| Chat.where(active: true).each do |chat|
assets = chat.assets(assets) assets = chat.assets(assets)
} end
active_agent_ids = [] active_agent_ids = []
active_agents.each { |user| active_agents.each do |user|
active_agent_ids.push user.id active_agent_ids.push user.id
assets = user.assets(assets) assets = user.assets(assets)
} end
runningchat_session_list_local = running_chat_session_list runningchat_session_list_local = running_chat_session_list
runningchat_session_list_local.each { |session| runningchat_session_list_local.each do |session|
next if !session['user_id'] next if !session['user_id']
user = User.lookup(id: session['user_id']) user = User.lookup(id: session['user_id'])
next if !user next if !user
assets = user.assets(assets) assets = user.assets(assets)
} end
{ {
waiting_chat_count: waiting_chat_count, waiting_chat_count: waiting_chat_count,
waiting_chat_session_list: waiting_chat_session_list, waiting_chat_session_list: waiting_chat_session_list,
@ -107,9 +107,9 @@ class Chat < ApplicationModel
def self.waiting_chat_session_list def self.waiting_chat_session_list
sessions = [] sessions = []
Chat::Session.where(state: ['waiting']).each { |session| Chat::Session.where(state: ['waiting']).each do |session|
sessions.push session.attributes sessions.push session.attributes
} end
sessions sessions
end end
@ -119,9 +119,9 @@ class Chat < ApplicationModel
def self.running_chat_session_list def self.running_chat_session_list
sessions = [] sessions = []
Chat::Session.where(state: ['running']).each { |session| Chat::Session.where(state: ['running']).each do |session|
sessions.push session.attributes sessions.push session.attributes
} end
sessions sessions
end end
@ -131,9 +131,9 @@ class Chat < ApplicationModel
def self.available_agents(diff = 2.minutes) def self.available_agents(diff = 2.minutes)
agents = {} agents = {}
Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each { |record| Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each do |record|
agents[record.updated_by_id] = record.concurrent agents[record.updated_by_id] = record.concurrent
} end
agents agents
end end
@ -143,19 +143,19 @@ class Chat < ApplicationModel
def self.active_agents(diff = 2.minutes) def self.active_agents(diff = 2.minutes)
users = [] users = []
Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each { |record| Chat::Agent.where(active: true).where('updated_at > ?', Time.zone.now - diff).each do |record|
user = User.lookup(id: record.updated_by_id) user = User.lookup(id: record.updated_by_id)
next if !user next if !user
users.push user users.push user
} end
users users
end end
def self.seads_total(diff = 2.minutes) def self.seads_total(diff = 2.minutes)
total = 0 total = 0
available_agents(diff).each { |_user_id, concurrent| available_agents(diff).each do |_user_id, concurrent|
total += concurrent total += concurrent
} end
total total
end end
@ -178,14 +178,14 @@ optional you can ignore it for dedecated user
def self.broadcast_agent_state_update(ignore_user_id = nil) def self.broadcast_agent_state_update(ignore_user_id = nil)
# send broadcast to agents # send broadcast to agents
Chat::Agent.where('active = ? OR updated_at > ?', true, Time.zone.now - 8.hours).each { |item| Chat::Agent.where('active = ? OR updated_at > ?', true, Time.zone.now - 8.hours).each do |item|
next if item.updated_by_id == ignore_user_id next if item.updated_by_id == ignore_user_id
data = { data = {
event: 'chat_status_agent', event: 'chat_status_agent',
data: Chat.agent_state(item.updated_by_id), data: Chat.agent_state(item.updated_by_id),
} }
Sessions.send_to(item.updated_by_id, data) Sessions.send_to(item.updated_by_id, data)
} end
end end
=begin =begin
@ -200,7 +200,7 @@ broadcast new customer queue position to all waiting customers
# send position update to other waiting sessions # send position update to other waiting sessions
position = 0 position = 0
Chat::Session.where(state: 'waiting').order('created_at ASC').each { |local_chat_session| Chat::Session.where(state: 'waiting').order('created_at ASC').each do |local_chat_session|
position += 1 position += 1
data = { data = {
event: 'chat_session_queue', event: 'chat_session_queue',
@ -211,7 +211,7 @@ broadcast new customer queue position to all waiting customers
}, },
} }
local_chat_session.send_to_recipients(data) local_chat_session.send_to_recipients(data)
} end
end end
=begin =begin
@ -227,10 +227,10 @@ optional you can put the max oldest chat entries
=end =end
def self.cleanup(diff = 3.months) def self.cleanup(diff = 3.months)
Chat::Session.where(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each { |chat_session| Chat::Session.where(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each do |chat_session|
Chat::Message.where(chat_session_id: chat_session.id).delete_all Chat::Message.where(chat_session_id: chat_session.id).delete_all
chat_session.destroy chat_session.destroy
} end
true true
end end
@ -248,7 +248,7 @@ optional you can put the max oldest chat sessions as argument
=end =end
def self.cleanup_close(diff = 5.minutes) def self.cleanup_close(diff = 5.minutes)
Chat::Session.where.not(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each { |chat_session| Chat::Session.where.not(state: 'closed').where('updated_at < ?', Time.zone.now - diff).each do |chat_session|
next if chat_session.recipients_active? next if chat_session.recipients_active?
chat_session.state = 'closed' chat_session.state = 'closed'
chat_session.save chat_session.save
@ -260,7 +260,7 @@ optional you can put the max oldest chat sessions as argument
}, },
} }
chat_session.send_to_recipients(message) chat_session.send_to_recipients(message)
} end
true true
end end

View file

@ -22,29 +22,29 @@ class Chat::Session < ApplicationModel
return true if !preferences return true if !preferences
return true if !preferences[:participants] return true if !preferences[:participants]
count = 0 count = 0
preferences[:participants].each { |client_id| preferences[:participants].each do |client_id|
next if !Sessions.session_exists?(client_id) next if !Sessions.session_exists?(client_id)
count += 1 count += 1
} end
return true if count >= 2 return true if count >= 2
false false
end end
def send_to_recipients(message, ignore_client_id = nil) def send_to_recipients(message, ignore_client_id = nil)
preferences[:participants].each { |local_client_id| preferences[:participants].each do |local_client_id|
next if local_client_id == ignore_client_id next if local_client_id == ignore_client_id
Sessions.send(local_client_id, message) Sessions.send(local_client_id, message)
} end
true true
end end
def position def position
return if state != 'waiting' return if state != 'waiting'
position = 0 position = 0
Chat::Session.where(state: 'waiting').order(created_at: :asc).each { |chat_session| Chat::Session.where(state: 'waiting').order(created_at: :asc).each do |chat_session|
position += 1 position += 1
break if chat_session.id == id break if chat_session.id == id
} end
position position
end end
@ -52,22 +52,22 @@ class Chat::Session < ApplicationModel
chat_session = Chat::Session.find_by(session_id: session_id) chat_session = Chat::Session.find_by(session_id: session_id)
return if !chat_session return if !chat_session
session_attributes = [] session_attributes = []
Chat::Message.where(chat_session_id: chat_session.id).order(created_at: :asc).each { |message| Chat::Message.where(chat_session_id: chat_session.id).order(created_at: :asc).each do |message|
session_attributes.push message.attributes session_attributes.push message.attributes
} end
session_attributes session_attributes
end end
def self.active_chats_by_user_id(user_id) def self.active_chats_by_user_id(user_id)
actice_sessions = [] actice_sessions = []
Chat::Session.where(state: 'running', user_id: user_id).order(created_at: :asc).each { |session| Chat::Session.where(state: 'running', user_id: user_id).order(created_at: :asc).each do |session|
session_attributes = session.attributes session_attributes = session.attributes
session_attributes['messages'] = [] session_attributes['messages'] = []
Chat::Message.where(chat_session_id: session.id).order(created_at: :asc).each { |message| Chat::Message.where(chat_session_id: session.id).order(created_at: :asc).each do |message|
session_attributes['messages'].push message.attributes session_attributes['messages'].push message.attributes
} end
actice_sessions.push session_attributes actice_sessions.push session_attributes
} end
actice_sessions actice_sessions
end end
end end

View file

@ -21,10 +21,10 @@ returns
def generate_uniq_name(name) def generate_uniq_name(name)
return name if !exists?(name: name) return name if !exists?(name: name)
(1..100).each { |counter| (1..100).each do |counter|
name = "#{name}_#{counter}" name = "#{name}_#{counter}"
break if !exists?(name: name) break if !exists?(name: name)
} end
name name
end end
end end

View file

@ -38,11 +38,11 @@ log object update activity stream, if configured - will be executed automaticall
ignored_attributes += %i(created_at updated_at created_by_id updated_by_id) ignored_attributes += %i(created_at updated_at created_by_id updated_by_id)
log = false log = false
saved_changes.each { |key, _value| saved_changes.each do |key, _value|
next if ignored_attributes.include?(key.to_sym) next if ignored_attributes.include?(key.to_sym)
log = true log = true
} end
return true if !log return true if !log
activity_stream_log('update', self['updated_by_id']) activity_stream_log('update', self['updated_by_id'])
true true

View file

@ -41,11 +41,11 @@ log object update history with all updated attributes, if configured - will be e
# new record also triggers update, so ignore new records # new record also triggers update, so ignore new records
changes = saved_changes changes = saved_changes
if history_changes_last_done if history_changes_last_done
history_changes_last_done.each { |key, value| history_changes_last_done.each do |key, value|
if changes.key?(key) && changes[key] == value if changes.key?(key) && changes[key] == value
changes.delete(key) changes.delete(key)
end end
} end
end end
self.history_changes_last_done = changes self.history_changes_last_done = changes
#logger.info 'updated ' + self.changes.inspect #logger.info 'updated ' + self.changes.inspect
@ -55,7 +55,7 @@ log object update history with all updated attributes, if configured - will be e
ignored_attributes = self.class.instance_variable_get(:@history_attributes_ignored) || [] ignored_attributes = self.class.instance_variable_get(:@history_attributes_ignored) || []
ignored_attributes += %i(created_at updated_at created_by_id updated_by_id) ignored_attributes += %i(created_at updated_at created_by_id updated_by_id)
changes.each { |key, value| changes.each do |key, value|
next if ignored_attributes.include?(key.to_sym) next if ignored_attributes.include?(key.to_sym)
@ -104,7 +104,7 @@ log object update history with all updated attributes, if configured - will be e
} }
#logger.info "HIST NEW #{self.class.to_s}.find(#{self.id}) #{data.inspect}" #logger.info "HIST NEW #{self.class.to_s}.find(#{self.id}) #{data.inspect}"
history_log('updated', updated_by_id, data) history_log('updated', updated_by_id, data)
} end
end end
=begin =begin
@ -212,7 +212,7 @@ returns
# get related objects # get related objects
history = History.list(self.class.name, self['id'], nil, true) history = History.list(self.class.name, self['id'], nil, true)
history[:list].each { |item| history[:list].each do |item|
record = Kernel.const_get(item['object']).find(item['o_id']) record = Kernel.const_get(item['object']).find(item['o_id'])
history[:assets] = record.assets(history[:assets]) history[:assets] = record.assets(history[:assets])
@ -221,7 +221,7 @@ returns
record = Kernel.const_get(item['related_object']).find(item['related_o_id']) record = Kernel.const_get(item['related_object']).find(item['related_o_id'])
history[:assets] = record.assets(history[:assets]) history[:assets] = record.assets(history[:assets])
end end
} end
{ {
history: history[:list], history: history[:list],
assets: history[:assets], assets: history[:assets],

View file

@ -84,11 +84,11 @@ returns
def search_index_data def search_index_data
attributes = {} attributes = {}
%w(name note).each { |key| %w(name note).each do |key|
next if !self[key] next if !self[key]
next if self[key].respond_to?('blank?') && self[key].blank? next if self[key].respond_to?('blank?') && self[key].blank?
attributes[key] = self[key] attributes[key] = self[key]
} end
return true if attributes.blank? return true if attributes.blank?
attributes attributes
end end
@ -127,7 +127,7 @@ reload search index with full data
tolerance = 5 tolerance = 5
tolerance_count = 0 tolerance_count = 0
ids = all.order('created_at DESC').pluck(:id) ids = all.order('created_at DESC').pluck(:id)
ids.each { |item_id| ids.each do |item_id|
item = find(item_id) item = find(item_id)
next if item.ignore_search_indexing?(:destroy) next if item.ignore_search_indexing?(:destroy)
begin begin
@ -137,7 +137,7 @@ reload search index with full data
tolerance_count += 1 tolerance_count += 1
raise "Unable to send #{item.class}.find(#{item.id}).search_index_update_backend backend: #{e.inspect}" if tolerance_count == tolerance raise "Unable to send #{item.class}.find(#{item.id}).search_index_update_backend backend: #{e.inspect}" if tolerance_count == tolerance
end end
} end
end end
end end
end end

View file

@ -44,7 +44,7 @@ returns
def self.lookup(caller_id) def self.lookup(caller_id)
result = [] result = []
['known', 'maybe', nil].each { |level| ['known', 'maybe', nil].each do |level|
search_params = { search_params = {
caller_id: caller_id, caller_id: caller_id,
@ -55,11 +55,11 @@ returns
end end
caller_ids = Cti::CallerId.select('MAX(id) as caller_id').where(search_params).group(:user_id).order('caller_id DESC').limit(20).map(&:caller_id) caller_ids = Cti::CallerId.select('MAX(id) as caller_id').where(search_params).group(:user_id).order('caller_id DESC').limit(20).map(&:caller_id)
Cti::CallerId.where(id: caller_ids).order(id: :desc).each { |record| Cti::CallerId.where(id: caller_ids).order(id: :desc).each do |record|
result.push record result.push record
} end
break if result.present? break if result.present?
} end
result result
end end
@ -73,11 +73,11 @@ returns
map = config map = config
level = nil level = nil
model = nil model = nil
map.each { |item| map.each do |item|
next if item[:model] != record.class next if item[:model] != record.class
level = item[:level] level = item[:level]
model = item[:model] model = item[:model]
} end
return if !level || !model return if !level || !model
build_item(record, model, level) build_item(record, model, level)
end end
@ -108,17 +108,17 @@ returns
# get caller ids # get caller ids
caller_ids = [] caller_ids = []
attributes = record.attributes attributes = record.attributes
attributes.each { |_attribute, value| attributes.each do |_attribute, value|
next if value.class != String next if value.class != String
next if value.empty? next if value.empty?
local_caller_ids = Cti::CallerId.extract_numbers(value) local_caller_ids = Cti::CallerId.extract_numbers(value)
next if local_caller_ids.empty? next if local_caller_ids.empty?
caller_ids = caller_ids.concat(local_caller_ids) caller_ids = caller_ids.concat(local_caller_ids)
} end
# store caller ids # store caller ids
Cti::CallerId.where(object: model.to_s, o_id: record.id).destroy_all Cti::CallerId.where(object: model.to_s, o_id: record.id).destroy_all
caller_ids.each { |caller_id| caller_ids.each do |caller_id|
Cti::CallerId.maybe_add( Cti::CallerId.maybe_add(
caller_id: caller_id, caller_id: caller_id,
level: level, level: level,
@ -126,7 +126,7 @@ returns
o_id: record.id, o_id: record.id,
user_id: user_id, user_id: user_id,
) )
} end
true true
end end
@ -139,13 +139,13 @@ returns
def self.rebuild def self.rebuild
transaction do transaction do
delete_all delete_all
config.each { |item| config.each do |item|
level = item[:level] level = item[:level]
model = item[:model] model = item[:model]
item[:model].find_each(batch_size: 500) do |record| item[:model].find_each(batch_size: 500) do |record|
build_item(record, model, level) build_item(record, model, level)
end end
} end
end end
end end
@ -221,7 +221,7 @@ returns
preferences_maybe = {} preferences_maybe = {}
preferences_maybe[direction] = [] preferences_maybe[direction] = []
lookup(extract_numbers(caller_id)).each { |record| lookup(extract_numbers(caller_id)).each do |record|
if record.level == 'known' if record.level == 'known'
preferences_known[direction].push record.attributes preferences_known[direction].push record.attributes
else else
@ -247,7 +247,7 @@ returns
end end
from_comment_maybe += comment from_comment_maybe += comment
end end
} end
return [from_comment_known, preferences_known] if !from_comment_known.empty? return [from_comment_known, preferences_known] if !from_comment_known.empty?
return ["maybe #{from_comment_maybe}", preferences_maybe] if !from_comment_maybe.empty? return ["maybe #{from_comment_maybe}", preferences_maybe] if !from_comment_maybe.empty?
nil nil

View file

@ -247,18 +247,18 @@ returns
# add assets # add assets
assets = {} assets = {}
list.each { |item| list.each do |item|
next if !item.preferences next if !item.preferences
%w(from to).each { |direction| %w(from to).each do |direction|
next if !item.preferences[direction] next if !item.preferences[direction]
item.preferences[direction].each { |caller_id| item.preferences[direction].each do |caller_id|
next if !caller_id['user_id'] next if !caller_id['user_id']
user = User.lookup(id: caller_id['user_id']) user = User.lookup(id: caller_id['user_id'])
next if !user next if !user
assets = user.assets(assets) assets = user.assets(assets)
} end
} end
} end
{ {
list: list, list: list,
@ -344,7 +344,7 @@ Cti::Log.process(
def push_event def push_event
users = User.with_permissions('cti.agent') users = User.with_permissions('cti.agent')
users.each { |user| users.each do |user|
# send notify about event # send notify about event
Sessions.send_to( Sessions.send_to(
@ -354,14 +354,14 @@ Cti::Log.process(
data: self, data: self,
}, },
) )
} end
end end
def push_caller_list def push_caller_list
list = Cti::Log.log list = Cti::Log.log
users = User.with_permissions('cti.agent') users = User.with_permissions('cti.agent')
users.each { |user| users.each do |user|
# send notify on create/update/delete # send notify on create/update/delete
Sessions.send_to( Sessions.send_to(
@ -371,7 +371,7 @@ Cti::Log.process(
data: list, data: list,
}, },
) )
} end
end end
=begin =begin

View file

@ -24,7 +24,7 @@ check and if channel not exists reset configured channels for email addresses
=end =end
def self.channel_cleanup def self.channel_cleanup
EmailAddress.all.each { |email_address| EmailAddress.all.each do |email_address|
# set to active if channel exists # set to active if channel exists
if email_address.channel_id && Channel.find_by(id: email_address.channel_id) if email_address.channel_id && Channel.find_by(id: email_address.channel_id)
@ -37,7 +37,7 @@ check and if channel not exists reset configured channels for email addresses
# set in inactive if channel not longer exists # set in inactive if channel not longer exists
next if !email_address.active next if !email_address.active
email_address.save! email_address.save!
} end
end end
private private
@ -68,9 +68,9 @@ check and if channel not exists reset configured channels for email addresses
# delete group.email_address_id reference if email address get's deleted # delete group.email_address_id reference if email address get's deleted
def delete_group_reference def delete_group_reference
Group.where(email_address_id: id).each { |group| Group.where(email_address_id: id).each do |group|
group.update!(email_address_id: nil) group.update!(email_address_id: nil)
} end
end end
# keep email email address is of inital group filled # keep email email address is of inital group filled

View file

@ -8,7 +8,7 @@ class ExternalSync < ApplicationModel
def changed?(object:, previous_changes: {}, current_changes:) def changed?(object:, previous_changes: {}, current_changes:)
changed = false changed = false
previous_changes ||= {} previous_changes ||= {}
current_changes.each { |attribute, value| current_changes.each do |attribute, value|
next if !object.attributes.key?(attribute.to_s) next if !object.attributes.key?(attribute.to_s)
next if object[attribute] == value next if object[attribute] == value
next if object[attribute].present? && object[attribute] != previous_changes[attribute] next if object[attribute].present? && object[attribute] != previous_changes[attribute]
@ -19,7 +19,7 @@ class ExternalSync < ApplicationModel
rescue => e rescue => e
Rails.logger.error "ERROR: Unable to assign attribute #{attribute} to object #{object.class.name}: #{e.inspect}" Rails.logger.error "ERROR: Unable to assign attribute #{attribute} to object #{object.class.name}: #{e.inspect}"
end end
} end
changed changed
end end
@ -32,7 +32,7 @@ class ExternalSync < ApplicationModel
end end
result = {} result = {}
mapping.each { |remote_key, local_key| mapping.each do |remote_key, local_key|
local_key_sym = local_key.to_sym local_key_sym = local_key.to_sym
@ -40,7 +40,7 @@ class ExternalSync < ApplicationModel
value = extract(remote_key, information_source) value = extract(remote_key, information_source)
next if value.blank? next if value.blank?
result[local_key_sym] = value result[local_key_sym] = value
} end
result result
end end

View file

@ -36,13 +36,13 @@ returns
data = assets_of_selector('condition', data) data = assets_of_selector('condition', data)
data = assets_of_selector('perform', data) data = assets_of_selector('perform', data)
end end
%w(created_by_id updated_by_id).each { |local_user_id| %w(created_by_id updated_by_id).each do |local_user_id|
next if !self[ local_user_id ] next if !self[ local_user_id ]
next if data[ User.to_app_model ][ self[ local_user_id ] ] next if data[ User.to_app_model ][ self[ local_user_id ] ]
user = User.lookup(id: self[ local_user_id ]) user = User.lookup(id: self[ local_user_id ])
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
data data
end end
end end

View file

@ -74,7 +74,7 @@ remove whole karma activity log of an object
def self.latest(user, limit = 12) def self.latest(user, limit = 12)
result = [] result = []
logs = Karma::ActivityLog.where(user_id: user.id).order(id: :desc).limit(limit) logs = Karma::ActivityLog.where(user_id: user.id).order(id: :desc).limit(limit)
logs.each { |log| logs.each do |log|
last = result.last last = result.last
if last && last[:object_id] == log.object_id && last[:o_id] == log.o_id && last[:created_at] == log.created_at if last && last[:object_id] == log.object_id && last[:o_id] == log.o_id && last[:created_at] == log.created_at
comment = { comment = {
@ -97,7 +97,7 @@ remove whole karma activity log of an object
created_at: log.created_at, created_at: log.created_at,
} }
result.push data result.push data
} end
result result
end end

View file

@ -30,14 +30,14 @@ class Karma::User < ApplicationModel
def self.level_by_score(score) def self.level_by_score(score)
level = nil level = nil
karma_levels = Setting.get('karma_levels') karma_levels = Setting.get('karma_levels')
karma_levels.each { |local_level| karma_levels.each do |local_level|
if !level if !level
level = local_level[:name] level = local_level[:name]
end end
next if local_level[:start] && score < local_level[:start] next if local_level[:start] && score < local_level[:start]
next if local_level[:end] && score > local_level[:end] next if local_level[:end] && score > local_level[:end]
level = local_level[:name] level = local_level[:name]
} end
level level
end end

View file

@ -31,25 +31,25 @@ class Link < ApplicationModel
'link_object_source_id = ? AND link_object_source_value = ?', linkobject.id, data[:link_object_value] 'link_object_source_id = ? AND link_object_source_value = ?', linkobject.id, data[:link_object_value]
) )
list.each { |item| list.each do |item|
link = {} link = {}
link['link_type'] = @map[ Link::Type.find( item.link_type_id ).name ] link['link_type'] = @map[ Link::Type.find( item.link_type_id ).name ]
link['link_object'] = Link::Object.find( item.link_object_target_id ).name link['link_object'] = Link::Object.find( item.link_object_target_id ).name
link['link_object_value'] = item.link_object_target_value link['link_object_value'] = item.link_object_target_value
items.push link items.push link
} end
# get links for the other site # get links for the other site
list = Link.where( list = Link.where(
'link_object_target_id = ? AND link_object_target_value = ?', linkobject.id, data[:link_object_value] 'link_object_target_id = ? AND link_object_target_value = ?', linkobject.id, data[:link_object_value]
) )
list.each { |item| list.each do |item|
link = {} link = {}
link['link_type'] = Link::Type.find( item.link_type_id ).name link['link_type'] = Link::Type.find( item.link_type_id ).name
link['link_object'] = Link::Object.find( item.link_object_source_id ).name link['link_object'] = Link::Object.find( item.link_object_source_id ).name
link['link_object_value'] = item.link_object_source_value link['link_object_value'] = item.link_object_source_value
items.push link items.push link
} end
items items
end end

View file

@ -116,14 +116,14 @@ all:
private_class_method def self.to_database(data) private_class_method def self.to_database(data)
ActiveRecord::Base.transaction do ActiveRecord::Base.transaction do
data.each { |locale| data.each do |locale|
exists = Locale.find_by(locale: locale['locale']) exists = Locale.find_by(locale: locale['locale'])
if exists if exists
exists.update!(locale.symbolize_keys!) exists.update!(locale.symbolize_keys!)
else else
Locale.create!(locale.symbolize_keys!) Locale.create!(locale.symbolize_keys!)
end end
} end
end end
end end

View file

@ -29,12 +29,12 @@ list of all attributes
result = ObjectManager::Attribute.all.order('position ASC, name ASC') result = ObjectManager::Attribute.all.order('position ASC, name ASC')
attributes = [] attributes = []
assets = {} assets = {}
result.each { |item| result.each do |item|
attribute = item.attributes attribute = item.attributes
attribute[:object] = ObjectLookup.by_id(item.object_lookup_id) attribute[:object] = ObjectLookup.by_id(item.object_lookup_id)
attribute.delete('object_lookup_id') attribute.delete('object_lookup_id')
attributes.push attribute attributes.push attribute
} end
attributes attributes
end end
@ -279,11 +279,11 @@ possible types
# if data_option has changed, store it for next migration # if data_option has changed, store it for next migration
if !force if !force
[:name, :display, :data_type, :position, :active].each { |key| [:name, :display, :data_type, :position, :active].each do |key|
next if record[key] == data[key] next if record[key] == data[key]
data[:to_config] = true data[:to_config] = true
break break
} end
if record[:data_option] != data[:data_option] if record[:data_option] != data[:data_option]
# do we need a database migration? # do we need a database migration?
@ -298,9 +298,9 @@ possible types
end end
# update attributes # update attributes
data.each { |key, value| data.each do |key, value|
record[key.to_sym] = value record[key.to_sym] = value
} end
# check editable & name # check editable & name
if !force if !force
@ -434,7 +434,7 @@ returns:
to_delete: false, to_delete: false,
).order('position ASC, name ASC') ).order('position ASC, name ASC')
attributes = [] attributes = []
result.each { |item| result.each do |item|
data = { data = {
name: item.name, name: item.name,
display: item.display, display: item.display,
@ -444,32 +444,32 @@ returns:
if item.data_option[:permission] && item.data_option[:permission].any? if item.data_option[:permission] && item.data_option[:permission].any?
next if !user next if !user
hint = false hint = false
item.data_option[:permission].each { |permission| item.data_option[:permission].each do |permission|
next if !user.permissions?(permission) next if !user.permissions?(permission)
hint = true hint = true
break break
} end
next if !hint next if !hint
end end
if item.screens if item.screens
data[:screen] = {} data[:screen] = {}
item.screens.each { |screen, permission_options| item.screens.each do |screen, permission_options|
data[:screen][screen] = {} data[:screen][screen] = {}
permission_options.each { |permission, options| permission_options.each do |permission, options|
if permission == '-all-' if permission == '-all-'
data[:screen][screen] = options data[:screen][screen] = options
elsif user && user.permissions?(permission) elsif user && user.permissions?(permission)
data[:screen][screen] = options data[:screen][screen] = options
end end
} end
} end
end end
if item.data_option if item.data_option
data = data.merge(item.data_option.symbolize_keys) data = data.merge(item.data_option.symbolize_keys)
end end
attributes.push data attributes.push data
} end
attributes attributes
end end
@ -492,9 +492,9 @@ returns:
def self.by_object_as_hash(object, user) def self.by_object_as_hash(object, user)
list = by_object(object, user) list = by_object(object, user)
hash = {} hash = {}
list.each { |item| list.each do |item|
hash[ item[:name] ] = item hash[ item[:name] ] = item
} end
hash hash
end end
@ -512,13 +512,13 @@ returns
def self.discard_changes def self.discard_changes
ObjectManager::Attribute.where('to_create = ?', true).each(&:destroy) ObjectManager::Attribute.where('to_create = ?', true).each(&:destroy)
ObjectManager::Attribute.where('to_delete = ? OR to_config = ?', true, true).each { |attribute| ObjectManager::Attribute.where('to_delete = ? OR to_config = ?', true, true).each do |attribute|
attribute.to_migrate = false attribute.to_migrate = false
attribute.to_delete = false attribute.to_delete = false
attribute.to_config = false attribute.to_config = false
attribute.data_option_new = {} attribute.data_option_new = {}
attribute.save attribute.save
} end
true true
end end
@ -576,7 +576,7 @@ to send no browser reload event, pass false
# check if field already exists # check if field already exists
execute_db_count = 0 execute_db_count = 0
execute_config_count = 0 execute_config_count = 0
migrations.each { |attribute| migrations.each do |attribute|
model = Kernel.const_get(attribute.object_lookup.name) model = Kernel.const_get(attribute.object_lookup.name)
# remove field # remove field
@ -698,7 +698,7 @@ to send no browser reload event, pass false
reset_database_info(model) reset_database_info(model)
execute_db_count += 1 execute_db_count += 1
} end
# sent maintenance message to clients # sent maintenance message to clients
if send_event if send_event
@ -783,10 +783,10 @@ to send no browser reload event, pass false
end end
if data_type == 'integer' if data_type == 'integer'
[:min, :max].each { |item| [:min, :max].each do |item|
raise "Need data_option[#{item.inspect}] param" if !data_option[item] raise "Need data_option[#{item.inspect}] param" if !data_option[item]
raise "Invalid data_option[#{item.inspect}] param #{data_option[item]}" if data_option[item].to_s !~ /^\d+?$/ raise "Invalid data_option[#{item.inspect}] param #{data_option[item]}" if data_option[item].to_s !~ /^\d+?$/
} end
end end
if data_type == 'select' || data_type == 'tree_select' || data_type == 'checkbox' if data_type == 'select' || data_type == 'tree_select' || data_type == 'checkbox'

View file

@ -24,20 +24,20 @@ class Observer::Organization::RefObjectTouch < ActiveRecord::Observer
return true if User.where(organization_id: record.id).count > 100 return true if User.where(organization_id: record.id).count > 100
# touch organizations tickets # touch organizations tickets
Ticket.select('id').where(organization_id: record.id).pluck(:id).each { |ticket_id| Ticket.select('id').where(organization_id: record.id).pluck(:id).each do |ticket_id|
ticket = Ticket.find(ticket_id) ticket = Ticket.find(ticket_id)
ticket.with_lock do ticket.with_lock do
ticket.touch ticket.touch
end end
} end
# touch current members # touch current members
User.select('id').where(organization_id: record.id).pluck(:id).each { |user_id| User.select('id').where(organization_id: record.id).pluck(:id).each do |user_id|
user = User.find(user_id) user = User.find(user_id)
user.with_lock do user.with_lock do
user.touch user.touch
end end
} end
true true
end end
end end

View file

@ -37,11 +37,11 @@ class Observer::Sla::TicketRebuildEscalation < ActiveRecord::Observer
else else
%w(timezone business_hours default ical_url public_holidays) %w(timezone business_hours default ical_url public_holidays)
end end
fields_to_check.each { |item| fields_to_check.each do |item|
next if !record.saved_change_to_attribute(item) next if !record.saved_change_to_attribute(item)
next if record.saved_change_to_attribute(item)[0] == record.saved_change_to_attribute(item)[1] next if record.saved_change_to_attribute(item)[0] == record.saved_change_to_attribute(item)[1]
changed = true changed = true
} end
return true if !changed return true if !changed
_rebuild(record) _rebuild(record)

View file

@ -90,7 +90,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob
# add history record # add history record
recipient_list = '' recipient_list = ''
[:to, :cc].each { |key| [:to, :cc].each do |key|
next if !record[key] next if !record[key]
next if record[key] == '' next if record[key] == ''
@ -99,7 +99,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob
recipient_list += ',' recipient_list += ','
end end
recipient_list += record[key] recipient_list += record[key]
} end
Rails.logger.info "Send email to: '#{recipient_list}' (from #{record.from})" Rails.logger.info "Send email to: '#{recipient_list}' (from #{record.from})"
@ -130,7 +130,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob
if local_record.preferences['delivery_retry'] > 3 if local_record.preferences['delivery_retry'] > 3
recipient_list = '' recipient_list = ''
[:to, :cc].each { |key| [:to, :cc].each do |key|
next if !local_record[key] next if !local_record[key]
next if local_record[key] == '' next if local_record[key] == ''
@ -139,7 +139,7 @@ class Observer::Ticket::Article::CommunicateEmail::BackgroundJob
recipient_list += ',' recipient_list += ','
end end
recipient_list += local_record[key] recipient_list += local_record[key]
} end
# reopen ticket and notify agent # reopen ticket and notify agent
Observer::Transaction.reset Observer::Transaction.reset

View file

@ -30,14 +30,14 @@ class Observer::Ticket::Article::CommunicateTelegram::BackgroundJob
api = TelegramAPI.new(channel.options[:api_token]) api = TelegramAPI.new(channel.options[:api_token])
chat_id = ticket.preferences[:telegram][:chat_id] chat_id = ticket.preferences[:telegram][:chat_id]
result = api.sendMessage(chat_id, article.body) result = api.sendMessage(chat_id, article.body)
article.attachments.each { |file| article.attachments.each do |file|
parts = file.filename.split(/^(.*)(\..+?)$/) parts = file.filename.split(/^(.*)(\..+?)$/)
t = Tempfile.new([parts[1], parts[2]]) t = Tempfile.new([parts[1], parts[2]])
t.binmode t.binmode
t.write(file.content) t.write(file.content)
t.rewind t.rewind
api.sendDocument(chat_id, t.path.to_s) api.sendDocument(chat_id, t.path.to_s)
} end
rescue => e rescue => e
log_error(article, e.message) log_error(article, e.message)
return return

View file

@ -56,13 +56,13 @@ class Observer::Ticket::Article::CommunicateTwitter::BackgroundJob
if tweet.user_mentions if tweet.user_mentions
to = '' to = ''
mention_ids = [] mention_ids = []
tweet.user_mentions.each { |user| tweet.user_mentions.each do |user|
if to != '' if to != ''
to += ' ' to += ' '
end end
to += "@#{user.screen_name}" to += "@#{user.screen_name}"
mention_ids.push user.id mention_ids.push user.id
} end
article.to = to article.to = to
article.preferences['twitter'] = { article.preferences['twitter'] = {
mention_ids: mention_ids, mention_ids: mention_ids,

View file

@ -9,7 +9,7 @@ class Observer::Ticket::OnlineNotificationSeen::BackgroundJob
# set all online notifications to seen # set all online notifications to seen
Transaction.execute do Transaction.execute do
ticket = Ticket.lookup(id: @ticket_id) ticket = Ticket.lookup(id: @ticket_id)
OnlineNotification.list_by_object('Ticket', @ticket_id).each { |notification| OnlineNotification.list_by_object('Ticket', @ticket_id).each do |notification|
next if notification.seen next if notification.seen
seen = ticket.online_notification_seen_state(notification.user_id) seen = ticket.online_notification_seen_state(notification.user_id)
next if !seen next if !seen
@ -17,7 +17,7 @@ class Observer::Ticket::OnlineNotificationSeen::BackgroundJob
notification.seen = true notification.seen = true
notification.updated_by_id = @user_id notification.updated_by_id = @user_id
notification.save! notification.save!
} end
end end
end end
end end

View file

@ -31,26 +31,26 @@ class Observer::Transaction < ActiveRecord::Observer
# get asyn backends # get asyn backends
sync_backends = [] sync_backends = []
Setting.where(area: 'Transaction::Backend::Sync').order(:name).each { |setting| Setting.where(area: 'Transaction::Backend::Sync').order(:name).each do |setting|
backend = Setting.get(setting.name) backend = Setting.get(setting.name)
next if params[:disable] && params[:disable].include?(backend) next if params[:disable] && params[:disable].include?(backend)
sync_backends.push Kernel.const_get(backend) sync_backends.push Kernel.const_get(backend)
} end
# get uniq objects # get uniq objects
list_objects = get_uniq_changes(list) list_objects = get_uniq_changes(list)
list_objects.each { |_object, objects| list_objects.each do |_object, objects|
objects.each { |_id, item| objects.each do |_id, item|
# execute sync backends # execute sync backends
sync_backends.each { |backend| sync_backends.each do |backend|
execute_singel_backend(backend, item, params) execute_singel_backend(backend, item, params)
} end
# execute async backends # execute async backends
Delayed::Job.enqueue(Transaction::BackgroundJob.new(item, params)) Delayed::Job.enqueue(Transaction::BackgroundJob.new(item, params))
} end
} end
end end
def self.execute_singel_backend(backend, item, params) def self.execute_singel_backend(backend, item, params)
@ -115,7 +115,7 @@ class Observer::Transaction < ActiveRecord::Observer
def self.get_uniq_changes(events) def self.get_uniq_changes(events)
list_objects = {} list_objects = {}
events.each { |event| events.each do |event|
# simulate article create as ticket update # simulate article create as ticket update
article = nil article = nil
@ -159,13 +159,13 @@ class Observer::Transaction < ActiveRecord::Observer
if !store[:changes] if !store[:changes]
store[:changes] = event[:changes] store[:changes] = event[:changes]
else else
event[:changes].each { |key, value| event[:changes].each do |key, value|
if !store[:changes][key] if !store[:changes][key]
store[:changes][key] = value store[:changes][key] = value
else else
store[:changes][key][1] = value[1] store[:changes][key][1] = value[1]
end end
} end
end end
end end
@ -173,7 +173,7 @@ class Observer::Transaction < ActiveRecord::Observer
if article if article
store[:article_id] = article.id store[:article_id] = article.id
end end
} end
list_objects list_objects
end end
@ -201,7 +201,7 @@ class Observer::Transaction < ActiveRecord::Observer
# ignore certain attributes # ignore certain attributes
real_changes = {} real_changes = {}
record.changes_to_save.each { |key, value| record.changes_to_save.each do |key, value|
next if key == 'updated_at' next if key == 'updated_at'
next if key == 'first_response_at' next if key == 'first_response_at'
next if key == 'close_at' next if key == 'close_at'
@ -212,7 +212,7 @@ class Observer::Transaction < ActiveRecord::Observer
next if key == 'create_article_type_id' next if key == 'create_article_type_id'
next if key == 'create_article_sender_id' next if key == 'create_article_sender_id'
real_changes[key] = value real_changes[key] = value
} end
# do not send anything if nothing has changed # do not send anything if nothing has changed
return true if real_changes.empty? return true if real_changes.empty?

View file

@ -24,16 +24,16 @@ class Observer::User::Geo < ActiveRecord::Observer
return if !current return if !current
current_location = {} current_location = {}
location.each { |item| location.each do |item|
current_location[item] = current[item] current_location[item] = current[item]
} end
end end
# get full address # get full address
next_location = {} next_location = {}
location.each { |item| location.each do |item|
next_location[item] = record[item] next_location[item] = record[item]
} end
# return if address hasn't changed and geo data is already available # return if address hasn't changed and geo data is already available
return if (current_location == next_location) && record.preferences['lat'] && record.preferences['lng'] return if (current_location == next_location) && record.preferences['lat'] && record.preferences['lng']
@ -46,13 +46,13 @@ class Observer::User::Geo < ActiveRecord::Observer
def geo_update(record) def geo_update(record)
address = '' address = ''
location = %w(address street zip city country) location = %w(address street zip city country)
location.each { |item| location.each do |item|
next if record[item].blank? next if record[item].blank?
if address.present? if address.present?
address += ', ' address += ', '
end end
address += record[item] address += record[item]
} end
# return if no address is given # return if no address is given
return if address.blank? return if address.blank?

View file

@ -46,10 +46,10 @@ class Observer::User::RefObjectTouch < ActiveRecord::Observer
end end
# touch old/current customer # touch old/current customer
member_ids.uniq.each { |user_id| member_ids.uniq.each do |user_id|
next if user_id == record.id next if user_id == record.id
User.find(user_id).touch User.find(user_id).touch
} end
true true
end end
end end

View file

@ -19,12 +19,12 @@ class Observer::User::TicketOrganization < ActiveRecord::Observer
# update last 100 tickets of user # update last 100 tickets of user
tickets = Ticket.where(customer_id: record.id).limit(100) tickets = Ticket.where(customer_id: record.id).limit(100)
tickets.each { |ticket| tickets.each do |ticket|
if ticket.organization_id != record.organization_id if ticket.organization_id != record.organization_id
ticket.organization_id = record.organization_id ticket.organization_id = record.organization_id
ticket.save ticket.save
end end
} end
end end
end end

View file

@ -218,9 +218,9 @@ returns:
def self.all_seen?(object, o_id) def self.all_seen?(object, o_id)
notifications = OnlineNotification.list_by_object(object, o_id) notifications = OnlineNotification.list_by_object(object, o_id)
notifications.each { |onine_notification| notifications.each do |onine_notification|
return false if !onine_notification['seen'] return false if !onine_notification['seen']
} end
true true
end end
@ -240,14 +240,14 @@ returns:
def self.exists?(user, object, o_id, type, created_by_user, seen) def self.exists?(user, object, o_id, type, created_by_user, seen)
# rubocop:enable Metrics/ParameterLists # rubocop:enable Metrics/ParameterLists
notifications = OnlineNotification.list(user, 10) notifications = OnlineNotification.list(user, 10)
notifications.each { |notification| notifications.each do |notification|
next if notification['o_id'] != o_id next if notification['o_id'] != o_id
next if notification['object'] != object next if notification['object'] != object
next if notification['type'] != type next if notification['type'] != type
next if notification['created_by_id'] != created_by_user.id next if notification['created_by_id'] != created_by_user.id
next if notification['seen'] != seen next if notification['seen'] != seen
return true return true
} end
false false
end end
@ -269,7 +269,7 @@ with dedicated times
def self.cleanup(max_age = Time.zone.now - 9.months, max_own_seen = Time.zone.now - 10.minutes, max_auto_seen = Time.zone.now - 8.hours) def self.cleanup(max_age = Time.zone.now - 9.months, max_own_seen = Time.zone.now - 10.minutes, max_auto_seen = Time.zone.now - 8.hours)
OnlineNotification.where('created_at < ?', max_age).delete_all OnlineNotification.where('created_at < ?', max_age).delete_all
OnlineNotification.where('seen = ? AND updated_at < ?', true, max_own_seen).each { |notification| OnlineNotification.where('seen = ? AND updated_at < ?', true, max_own_seen).each do |notification|
# delete own "seen" notificatons after 1 hour # delete own "seen" notificatons after 1 hour
next if notification.user_id == notification.updated_by_id && notification.updated_at > max_own_seen next if notification.user_id == notification.updated_by_id && notification.updated_at > max_own_seen
@ -278,10 +278,10 @@ with dedicated times
next if notification.user_id != notification.updated_by_id && notification.updated_at > max_auto_seen next if notification.user_id != notification.updated_by_id && notification.updated_at > max_auto_seen
notification.delete notification.delete
} end
# notify all agents # notify all agents
User.with_permissions('ticket.agent').each { |user| User.with_permissions('ticket.agent').each do |user|
Sessions.send_to( Sessions.send_to(
user.id, user.id,
{ {
@ -290,7 +290,7 @@ with dedicated times
} }
) )
sleep 2 # slow down client requests sleep 2 # slow down client requests
} end
true true
end end

View file

@ -45,23 +45,23 @@ returns
if local_attributes['member_ids'].count > 100 if local_attributes['member_ids'].count > 100
local_attributes['member_ids'] = local_attributes['member_ids'].sort[0, 100] local_attributes['member_ids'] = local_attributes['member_ids'].sort[0, 100]
end end
local_attributes['member_ids'].each { |local_user_id| local_attributes['member_ids'].each do |local_user_id|
next if data[ app_model_user ][ local_user_id ] next if data[ app_model_user ][ local_user_id ]
user = User.lookup(id: local_user_id) user = User.lookup(id: local_user_id)
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
end end
data[ app_model_organization ][ id ] = local_attributes data[ app_model_organization ][ id ] = local_attributes
end end
%w(created_by_id updated_by_id).each { |local_user_id| %w(created_by_id updated_by_id).each do |local_user_id|
next if !self[ local_user_id ] next if !self[ local_user_id ]
next if data[ app_model_user ][ self[ local_user_id ] ] next if data[ app_model_user ][ self[ local_user_id ] ]
user = User.lookup(id: self[ local_user_id ]) user = User.lookup(id: self[ local_user_id ])
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
data data
end end
end end

View file

@ -60,11 +60,11 @@ returns
if SearchIndexBackend.enabled? if SearchIndexBackend.enabled?
items = SearchIndexBackend.search(query, limit, 'Organization') items = SearchIndexBackend.search(query, limit, 'Organization')
organizations = [] organizations = []
items.each { |item| items.each do |item|
organization = Organization.lookup(id: item[:id]) organization = Organization.lookup(id: item[:id])
next if !organization next if !organization
organizations.push organization organizations.push organization
} end
return organizations return organizations
end end
@ -80,19 +80,19 @@ returns
organizations_by_user = Organization.select('DISTINCT(organizations.id), organizations.name').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where( organizations_by_user = Organization.select('DISTINCT(organizations.id), organizations.name').joins('LEFT OUTER JOIN users ON users.organization_id = organizations.id').where(
'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%" 'users.firstname LIKE ? or users.lastname LIKE ? or users.email LIKE ?', "%#{query}%", "%#{query}%", "%#{query}%"
).order('organizations.name').limit(limit) ).order('organizations.name').limit(limit)
organizations_by_user.each { |organization_by_user| organizations_by_user.each do |organization_by_user|
organization_exists = false organization_exists = false
organizations.each { |organization| organizations.each do |organization|
if organization.id == organization_by_user.id if organization.id == organization_by_user.id
organization_exists = true organization_exists = true
end end
} end
# get model with full data # get model with full data
if !organization_exists if !organization_exists
organizations.push Organization.find(organization_by_user.id) organizations.push Organization.find(organization_by_user.id)
end end
} end
end end
organizations organizations
end end

View file

@ -22,9 +22,9 @@ returns
# add org members for search index data # add org members for search index data
attributes['members'] = [] attributes['members'] = []
users = User.where(organization_id: id) users = User.where(organization_id: id)
users.each { |user| users.each do |user|
attributes['members'].push user.search_index_data attributes['members'].push user.search_index_data
} end
attributes attributes
end end

View file

@ -35,24 +35,24 @@ returns
if !data[ app_model_overview ][ id ] if !data[ app_model_overview ][ id ]
data[ app_model_overview ][ id ] = attributes_with_association_ids data[ app_model_overview ][ id ] = attributes_with_association_ids
if user_ids if user_ids
user_ids.each { |local_user_id| user_ids.each do |local_user_id|
next if data[ app_model_user ][ local_user_id ] next if data[ app_model_user ][ local_user_id ]
user = User.lookup(id: local_user_id) user = User.lookup(id: local_user_id)
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
end end
data = assets_of_selector('condition', data) data = assets_of_selector('condition', data)
end end
%w(created_by_id updated_by_id).each { |local_user_id| %w(created_by_id updated_by_id).each do |local_user_id|
next if !self[ local_user_id ] next if !self[ local_user_id ]
next if data[ app_model_user ][ self[ local_user_id ] ] next if data[ app_model_user ][ self[ local_user_id ] ]
user = User.lookup(id: self[ local_user_id ]) user = User.lookup(id: self[ local_user_id ])
next if !user next if !user
data = user.assets(data) data = user.assets(data)
} end
data data
end end
end end

View file

@ -32,7 +32,7 @@ returns:
# verify installed files # verify installed files
issues = {} issues = {}
package['files'].each { |file| package['files'].each do |file|
if !File.exist?(file['location']) if !File.exist?(file['location'])
logger.error "File #{file['location']} is missing" logger.error "File #{file['location']} is missing"
issues[file['location']] = 'missing' issues[file['location']] = 'missing'
@ -43,7 +43,7 @@ returns:
next if content_package == content_fs next if content_package == content_fs
logger.error "File #{file['location']} is different" logger.error "File #{file['location']} is different"
issues[file['location']] = 'changed' issues[file['location']] = 'changed'
} end
return nil if issues.empty? return nil if issues.empty?
issues issues
end end
@ -65,9 +65,9 @@ install all packages located under auto_install/*.zpm
data.push entry data.push entry
end end
end end
data.each { |file| data.each do |file|
install(file: "#{path}/#{file}") install(file: "#{path}/#{file}")
} end
data data
end end
@ -273,11 +273,11 @@ returns
end end
# write files # write files
package['files'].each { |file| package['files'].each do |file|
permission = file['permission'] || '644' permission = file['permission'] || '644'
content = Base64.decode64(file['content']) content = Base64.decode64(file['content'])
_write_file(file['location'], permission, content) _write_file(file['location'], permission, content)
} end
# update package state # update package state
package_db.state = 'installed' package_db.state = 'installed'
@ -343,11 +343,11 @@ returns
Package::Migration.migrate(package['name'], 'reverse') Package::Migration.migrate(package['name'], 'reverse')
end end
package['files'].each { |file| package['files'].each do |file|
permission = file['permission'] || '644' permission = file['permission'] || '644'
content = Base64.decode64(file['content']) content = Base64.decode64(file['content'])
_delete_file(file['location'], permission, content) _delete_file(file['location'], permission, content)
} end
# delete package # delete package
if !data[:reinstall] if !data[:reinstall]
@ -370,11 +370,11 @@ execute all pending package migrations at once
=end =end
def self.migration_execute def self.migration_execute
Package.all.each { |package| Package.all.each do |package|
json_file = Package._get_bin(package.name, package.version) json_file = Package._get_bin(package.name, package.version)
package = JSON.parse(json_file) package = JSON.parse(json_file)
Package::Migration.migrate(package['name']) Package::Migration.migrate(package['name'])
} end
end end
def self._get_bin(name, version) def self._get_bin(name, version)
@ -435,17 +435,17 @@ execute all pending package migrations at once
# check if directories need to be created # check if directories need to be created
directories = location.split '/' directories = location.split '/'
(0..(directories.length - 2) ).each { |position| (0..(directories.length - 2) ).each do |position|
tmp_path = '' tmp_path = ''
(1..position).each { |count| (1..position).each do |count|
tmp_path = "#{tmp_path}/#{directories[count]}" tmp_path = "#{tmp_path}/#{directories[count]}"
} end
next if tmp_path == '' next if tmp_path == ''
next if File.exist?(tmp_path) next if File.exist?(tmp_path)
Dir.mkdir(tmp_path, 0o755) Dir.mkdir(tmp_path, 0o755)
} end
# install file # install file
begin begin
@ -501,11 +501,11 @@ execute all pending package migrations at once
# get existing migrations # get existing migrations
migrations_existing = [] migrations_existing = []
Dir.foreach(location) { |entry| Dir.foreach(location) do |entry|
next if entry == '.' next if entry == '.'
next if entry == '..' next if entry == '..'
migrations_existing.push entry migrations_existing.push entry
} end
# up # up
migrations_existing = migrations_existing.sort migrations_existing = migrations_existing.sort
@ -515,7 +515,7 @@ execute all pending package migrations at once
migrations_existing = migrations_existing.reverse migrations_existing = migrations_existing.reverse
end end
migrations_existing.each { |migration| migrations_existing.each do |migration|
next if migration !~ /\.rb$/ next if migration !~ /\.rb$/
version = nil version = nil
name = nil name = nil
@ -550,7 +550,7 @@ execute all pending package migrations at once
classname.constantize.up classname.constantize.up
Package::Migration.create(name: package.underscore, version: version) Package::Migration.create(name: package.underscore, version: version)
end end
} end
end end
def self.root def self.root

View file

@ -21,13 +21,13 @@ returns
def self.with_parents(key) def self.with_parents(key)
names = [] names = []
part = '' part = ''
key.split('.').each { |local_part| key.split('.').each do |local_part|
if part != '' if part != ''
part += '.' part += '.'
end end
part += local_part part += local_part
names.push part names.push part
} end
names names
end end

View file

@ -10,7 +10,7 @@ class PostmasterFilter < ApplicationModel
def validate_condition def validate_condition
raise Exceptions::UnprocessableEntity, 'Min. one match rule needed!' if match.blank? raise Exceptions::UnprocessableEntity, 'Min. one match rule needed!' if match.blank?
match.each { |_key, meta| match.each do |_key, meta|
raise Exceptions::UnprocessableEntity, 'operator invalid, ony "contains" and "contains not" is supported' if meta['operator'].blank? || meta['operator'] !~ /^(contains|contains not)$/ raise Exceptions::UnprocessableEntity, 'operator invalid, ony "contains" and "contains not" is supported' if meta['operator'].blank? || meta['operator'] !~ /^(contains|contains not)$/
raise Exceptions::UnprocessableEntity, 'value invalid/empty' if meta['value'].blank? raise Exceptions::UnprocessableEntity, 'value invalid/empty' if meta['value'].blank?
begin begin
@ -22,7 +22,7 @@ class PostmasterFilter < ApplicationModel
rescue => e rescue => e
raise Exceptions::UnprocessableEntity, e.message raise Exceptions::UnprocessableEntity, e.message
end end
} end
true true
end end

View file

@ -57,7 +57,7 @@ class RecentView < ApplicationModel
end end
list = [] list = []
recent_views.each { |item| recent_views.each do |item|
data = item.attributes data = item.attributes
data['object'] = ObjectLookup.by_id(data['recent_view_object_id']) data['object'] = ObjectLookup.by_id(data['recent_view_object_id'])
data.delete('recent_view_object_id') data.delete('recent_view_object_id')
@ -67,7 +67,7 @@ class RecentView < ApplicationModel
# add to result list # add to result list
list.push data list.push data
} end
list list
end end

View file

@ -306,11 +306,11 @@ class Report
] ]
config[:metric][:communication][:backend] = backend config[:metric][:communication][:backend] = backend
config[:metric].each { |metric_key, metric_value| config[:metric].each do |metric_key, metric_value|
metric_value[:backend].each { |metric_backend| metric_value[:backend].each do |metric_backend|
metric_backend[:name] = "#{metric_key}::#{metric_backend[:name]}" metric_backend[:name] = "#{metric_key}::#{metric_backend[:name]}"
} end
} end
config config
end end

Some files were not shown because too many files have changed in this diff Show more