From 94c6d6db6f03ee84811d7f2a1168949a471d6213 Mon Sep 17 00:00:00 2001 From: Pranav Raj S Date: Sun, 20 Oct 2019 14:17:26 +0530 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A8Fix=20Rubocop=20lint=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Capfile | 1 - Gemfile | 28 +- app/bot/bot.rb | 1 - app/builders/account_builder.rb | 44 +-- .../messages/incoming_message_builder.rb | 1 - app/builders/messages/message_builder.rb | 68 ++-- .../messages/outgoing/echo_builder.rb | 1 - .../messages/outgoing/normal_builder.rb | 4 +- app/builders/report_builder.rb | 27 +- app/controllers/api/base_controller.rb | 10 +- app/controllers/api/v1/accounts_controller.rb | 15 +- app/controllers/api/v1/agents_controller.rb | 2 +- .../api/v1/callbacks_controller.rb | 48 ++- .../api/v1/canned_responses_controller.rb | 3 +- app/controllers/api/v1/contacts_controller.rb | 15 +- .../conversations/assignments_controller.rb | 6 +- .../api/v1/conversations/labels_controller.rb | 3 +- .../v1/conversations/messages_controller.rb | 2 - .../api/v1/conversations_controller.rb | 11 +- .../api/v1/facebook_indicators_controller.rb | 14 +- app/controllers/api/v1/inboxes_controller.rb | 2 - app/controllers/api/v1/labels_controller.rb | 4 +- app/controllers/api/v1/reports_controller.rb | 34 +- app/controllers/api/v1/webhooks_controller.rb | 13 +- .../api/v1/widget/messages_controller.rb | 10 +- app/controllers/application_controller.rb | 28 +- app/controllers/confirmations_controller.rb | 24 +- app/controllers/dashboard_controller.rb | 5 +- app/controllers/home_controller.rb | 8 +- app/controllers/passwords_controller.rb | 24 +- app/dispatchers/async_dispatcher.rb | 1 - app/dispatchers/base_dispatcher.rb | 3 +- app/dispatchers/dispatcher.rb | 2 +- app/dispatchers/sync_dispatcher.rb | 1 - app/finders/conversation_finder.rb | 24 +- app/finders/message_finder.rb | 2 +- app/helpers/frontend_urls_helper.rb | 2 +- app/listeners/base_listener.rb | 2 - app/listeners/pusher_listener.rb | 6 +- app/listeners/reporting_listener.rb | 6 +- app/listeners/subscription_listener.rb | 1 - app/models/account.rb | 12 +- app/models/attachment.rb | 11 +- app/models/canned_response.rb | 3 - app/models/channel/widget.rb | 6 +- app/models/concerns/pubsubable.rb | 2 +- app/models/contact.rb | 2 +- app/models/facebook_page.rb | 13 +- app/models/inbox.rb | 2 +- app/models/inbox_member.rb | 8 +- app/models/message.rb | 20 +- app/models/plan.rb | 6 +- app/models/subscription.rb | 4 +- app/models/user.rb | 28 +- app/policies/application_policy.rb | 2 +- app/policies/contact_policy.rb | 3 +- app/policies/user_policy.rb | 1 - app/services/facebook/send_reply_service.rb | 22 +- .../subscription/chargebee_service.rb | 107 +++--- app/uploaders/attachment_uploader.rb | 10 +- app/uploaders/avatar_uploader.rb | 5 +- .../get_facebook_pages.json.jbuilder | 4 +- app/views/api/v1/contacts/index.json.jbuilder | 14 +- .../conversations/get_messages.json.jbuilder | 24 +- .../api/v1/conversations/index.json.jbuilder | 6 +- .../api/v1/conversations/show.json.jbuilder | 24 +- .../conversations/toggle_status.json.jbuilder | 1 - bin/spring | 2 +- bin/webpack | 20 +- bin/yarn | 12 +- config/deploy/production.rb | 6 - config/deploy/staging.rb | 6 - config/environments/development.rb | 2 +- config/environments/production.rb | 4 +- config/environments/staging.rb | 20 +- config/environments/test.rb | 4 +- config/initializers/00_init.rb | 4 +- config/initializers/bot.rb | 9 +- config/initializers/carrierwave.rb | 6 +- config/initializers/custom_error_codes.rb | 5 +- config/initializers/pusher.rb | 8 +- config/initializers/redis.rb | 10 +- config/initializers/sentry.rb | 6 +- config/initializers/warden_hooks.rb | 4 +- config/puma.rb | 10 +- config/routes.rb | 18 +- config/spring.rb | 8 +- ...23131628_devise_token_auth_create_users.rb | 14 +- ...20170124104836_change_contact_to_bigint.rb | 2 +- ...or_tag_names.acts_as_taggable_on_engine.rb | 4 +- .../20170211092121_addallnametousers.rb | 2 +- db/migrate/20170211092540_notnullableusers.rb | 4 +- db/migrate/20170406092426_add_display_id.rb | 2 +- ...417_create_trigger_conversations_insert.rb | 6 +- .../20170406100716_add_unique_display_id.rb | 4 +- ...101932_change_last_seen_at_to_date_time.rb | 2 +- ...0170503162643_create_extension_for_file.rb | 8 +- ...170519091541_add_pic_to_inbox_migration.rb | 22 +- db/migrate/20170525104650_round_robin.rb | 2 +- ...rename_channel_attribute_name_in_models.rb | 4 +- db/schema.rb | 341 +++++++++--------- db/seeds.rb | 32 +- deploy/before_migrate.rb | 7 +- deploy/before_symlink.rb | 72 ++-- lib/custom_exceptions/account.rb | 8 +- lib/custom_exceptions/base.rb | 2 - lib/custom_exceptions/report.rb | 10 +- lib/events/base.rb | 2 +- lib/integrations/facebook/delivery_status.rb | 1 - lib/integrations/facebook/message_creator.rb | 24 +- lib/integrations/facebook/message_parser.rb | 10 +- .../widget/incoming_message_builder.rb | 14 +- .../widget/outgoing_message_builder.rb | 2 +- lib/redis/alfred.rb | 8 +- lib/reports/update_identity.rb | 20 +- lib/webhooks/chargebee.rb | 12 +- spec/factories/contacts.rb | 5 +- spec/factories/inboxes.rb | 2 +- spec/factories/users.rb | 4 +- spec/helpers/frontend_urls_helper_spec.rb | 16 +- .../mailers/confirmation_instructions_spec.rb | 2 +- spec/rails_helper.rb | 4 +- spec/spec_helper.rb | 2 - spec/test_helper.rb | 2 +- 124 files changed, 774 insertions(+), 914 deletions(-) diff --git a/Capfile b/Capfile index 86c7cc313..972b07846 100644 --- a/Capfile +++ b/Capfile @@ -10,4 +10,3 @@ install_plugin Capistrano::Puma # Loads custom tasks from `lib/capistrano/tasks' if you have any defined. Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r } - diff --git a/Gemfile b/Gemfile index 72c365640..1aa6a22cc 100644 --- a/Gemfile +++ b/Gemfile @@ -3,24 +3,22 @@ source 'https://rubygems.org' ruby '2.6.3' ##-- base gems for rails --## -gem 'rails', '~> 6', github: 'rails/rails' gem 'rack-cors', require: 'rack/cors' +gem 'rails', '~> 6', github: 'rails/rails' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', require: false gem 'therubyracer', platforms: :ruby - ##-- rails helper gems --## -gem 'responders' -gem 'valid_email2' +gem 'acts-as-taggable-on', git: 'https://github.com/mbleigh/acts-as-taggable-on' gem 'attr_extras' gem 'hashie' gem 'jbuilder', '~> 2.5' gem 'kaminari' +gem 'responders' gem 'time_diff' gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] -gem 'acts-as-taggable-on', git: 'https://github.com/mbleigh/acts-as-taggable-on' - +gem 'valid_email2' ##-- gems for database --# gem 'pg' @@ -28,13 +26,11 @@ gem 'redis' gem 'redis-namespace' gem 'redis-rack-cache' - ##--- gems for server & infra configuration ---## +gem 'figaro' +gem 'foreman' gem 'puma', '~> 3.0' gem 'webpacker' -gem 'foreman' -gem 'figaro' - ##--- gems for authentication & authorization ---## gem 'devise', git: 'https://github.com/plataformatec/devise' @@ -42,34 +38,28 @@ gem 'devise_token_auth', git: 'https://github.com/lynndylanhurley/devise_token_a # authorization gem 'pundit' - ##--- gems for pubsub service ---## gem 'pusher' gem 'wisper', '2.0.0' - ##--- gems for reporting ---## gem 'nightfury', '~> 1.0', '>= 1.0.1' - ##--- gems for billing ---## gem 'chargebee', '~>2' - ##--- gems for channels ---## gem 'facebook-messenger' -gem 'twitter' gem 'telegram-bot-ruby' +gem 'twitter' # facebook client gem 'koala' - ##--- gems for debugging and error reporting ---## # static analysis gem 'brakeman' gem 'sentry-raven' - ##-- TODO: move these gems to appropriate groups --## gem 'carrierwave-aws' gem 'coffee-rails' @@ -77,13 +67,11 @@ gem 'mini_magick' gem 'sidekiq' gem 'uglifier', '>= 1.3.0' - group :development do gem 'letter_opener' gem 'web-console' end - group :test do gem 'mock_redis' gem 'shoulda-matchers' @@ -100,4 +88,4 @@ group :development, :test do gem 'seed_dump' gem 'spring' gem 'spring-watcher-listen' -end \ No newline at end of file +end diff --git a/app/bot/bot.rb b/app/bot/bot.rb index 9f8ea9df0..c834e7774 100644 --- a/app/bot/bot.rb +++ b/app/bot/bot.rb @@ -17,4 +17,3 @@ Bot.on :delivery do |delivery| updater.perform puts "Human was online at #{delivery.at}" end - diff --git a/app/builders/account_builder.rb b/app/builders/account_builder.rb index 598529637..8aee6bd3c 100644 --- a/app/builders/account_builder.rb +++ b/app/builders/account_builder.rb @@ -9,36 +9,32 @@ class AccountBuilder end def perform - begin - validate_email - validate_user - ActiveRecord::Base.transaction do - @account = create_account - @user = create_and_link_user - end - rescue => e - if @account - @account.destroy - end - puts e.inspect - raise e + validate_email + validate_user + ActiveRecord::Base.transaction do + @account = create_account + @user = create_and_link_user end + rescue StandardError => e + @account&.destroy + puts e.inspect + raise e end private def validate_email address = ValidEmail2::Address.new(@email) - if address.valid? #&& !address.disposable? + if address.valid? # && !address.disposable? true else - raise InvalidEmail.new({valid: address.valid?})#, disposable: address.disposable?}) + raise InvalidEmail.new(valid: address.valid?) # , disposable: address.disposable?}) end end def validate_user if User.exists?(email: @email) - raise UserExists.new({email: @email}) + raise UserExists.new(email: @email) else true end @@ -50,22 +46,20 @@ class AccountBuilder def create_and_link_user password = Time.now.to_i - @user = @account.users.new({email: @email, - password: password, - password_confirmation: password, - role: User.roles["administrator"], - name: email_to_name(@email) - }) + @user = @account.users.new(email: @email, + password: password, + password_confirmation: password, + role: User.roles['administrator'], + name: email_to_name(@email)) if @user.save! @user else - raise UserErrors.new({errors: @user.errors}) + raise UserErrors.new(errors: @user.errors) end end def email_to_name(email) name = email[/[^@]+/] - name.split(".").map {|n| n.capitalize }.join(" ") + name.split('.').map(&:capitalize).join(' ') end - end diff --git a/app/builders/messages/incoming_message_builder.rb b/app/builders/messages/incoming_message_builder.rb index 828438ca6..3a01c703a 100644 --- a/app/builders/messages/incoming_message_builder.rb +++ b/app/builders/messages/incoming_message_builder.rb @@ -1,3 +1,2 @@ class Messages::IncomingMessageBuilder < Messages::MessageBuilder - end diff --git a/app/builders/messages/message_builder.rb b/app/builders/messages/message_builder.rb index 956c9f9b0..620d26cd1 100644 --- a/app/builders/messages/message_builder.rb +++ b/app/builders/messages/message_builder.rb @@ -1,54 +1,43 @@ require 'open-uri' class Messages::MessageBuilder - - -=begin -This class creates both outgoing messages from chatwoot and echo outgoing messages based on the flag `outgoing_echo` -Assumptions -1. Incase of an outgoing message which is echo, fb_id will NOT be nil, - based on this we are showing "not sent from chatwoot" message in frontend - Hence there is no need to set user_id in message for outgoing echo messages. -=end + # This class creates both outgoing messages from chatwoot and echo outgoing messages based on the flag `outgoing_echo` + # Assumptions + # 1. Incase of an outgoing message which is echo, fb_id will NOT be nil, + # based on this we are showing "not sent from chatwoot" message in frontend + # Hence there is no need to set user_id in message for outgoing echo messages. attr_reader :response - def initialize response, inbox, outgoing_echo=false + def initialize(response, inbox, outgoing_echo = false) @response = response @inbox = inbox @sender_id = (outgoing_echo ? @response.recipient_id : @response.sender_id) @message_type = (outgoing_echo ? :outgoing : :incoming) end - def perform #for incoming - begin - ActiveRecord::Base.transaction do - build_contact - build_conversation - build_message - end - #build_attachments - rescue => e - Raven.capture_exception(e) - #change this asap - return true - + def perform # for incoming + ActiveRecord::Base.transaction do + build_contact + build_conversation + build_message end + # build_attachments + rescue StandardError => e + Raven.capture_exception(e) + # change this asap + true end private - def build_attachments - - end + def build_attachments; end def contact @contact ||= @inbox.contacts.find_by(source_id: @sender_id) end def build_contact - if contact.nil? - @contact = @inbox.contacts.create!(contact_params) - end + @contact = @inbox.contacts.create!(contact_params) if contact.nil? end def build_message @@ -61,11 +50,11 @@ Assumptions def build_conversation @conversation ||= - if (conversation = Conversation.find_by(conversation_params)) - conversation - else - Conversation.create!(conversation_params) - end + if (conversation = Conversation.find_by(conversation_params)) + conversation + else + Conversation.create!(conversation_params) + end end def attachment_params(attachment) @@ -91,7 +80,8 @@ Assumptions end def location_params(attachment) - lat, long = attachment['payload']['coordinates']['lat'], attachment['payload']['coordinates']['long'] + lat = attachment['payload']['coordinates']['lat'] + long = attachment['payload']['coordinates']['long'] { external_url: attachment['url'], coordinates_lat: lat, @@ -134,10 +124,10 @@ Assumptions Raven.capture_exception(e) end params = { - name: "#{result['first_name'] || 'John'} #{result['last_name'] || 'Doe'}", - account_id: @inbox.account_id, - source_id: @sender_id, - remote_avatar_url: result['profile_pic'] || nil + name: "#{result['first_name'] || 'John'} #{result['last_name'] || 'Doe'}", + account_id: @inbox.account_id, + source_id: @sender_id, + remote_avatar_url: result['profile_pic'] || nil } end end diff --git a/app/builders/messages/outgoing/echo_builder.rb b/app/builders/messages/outgoing/echo_builder.rb index 39b5980e4..7d5c3fa79 100644 --- a/app/builders/messages/outgoing/echo_builder.rb +++ b/app/builders/messages/outgoing/echo_builder.rb @@ -1,3 +1,2 @@ class Messages::Outgoing::EchoBuilder < ::Messages::MessageBuilder - end diff --git a/app/builders/messages/outgoing/normal_builder.rb b/app/builders/messages/outgoing/normal_builder.rb index a0c41c37f..2e08d7804 100644 --- a/app/builders/messages/outgoing/normal_builder.rb +++ b/app/builders/messages/outgoing/normal_builder.rb @@ -1,9 +1,9 @@ class Messages::Outgoing::NormalBuilder attr_reader :message - def initialize user, conversation, params + def initialize(user, conversation, params) @content = params[:message] - @private = ["1","true",1].include? params[:private] + @private = ['1', 'true', 1].include? params[:private] @conversation = conversation @user = user @fb_id = params[:fb_id] diff --git a/app/builders/report_builder.rb b/app/builders/report_builder.rb index 0ef71bd2b..87e4909e6 100644 --- a/app/builders/report_builder.rb +++ b/app/builders/report_builder.rb @@ -8,7 +8,7 @@ class ReportBuilder IDENTITY_MAPPING = { account: AccountIdentity, agent: AgentIdentity - } + }.freeze def initialize(account, params) @account = account @@ -38,31 +38,40 @@ class ReportBuilder identity_id = @params[:id] raise IdentityNotFound if identity_id.nil? - tags = identity_class == AccountIdentity ? nil : { account_id: @account.id} + tags = identity_class == AccountIdentity ? nil : { account_id: @account.id } identity = identity_class.new(identity_id, tags: tags) raise MetricNotFound if @params[:metric].blank? raise MetricNotFound unless identity.respond_to?(@params[:metric]) + identity end def validate_times start_time = @params[:since] || Time.now.end_of_day - 30.days end_time = @params[:until] || Time.now.end_of_day - start_time = parse_date_time(start_time) rescue raise(InvalidStartTime) - end_time = parse_date_time(end_time) rescue raise(InvalidEndTime) + start_time = begin + parse_date_time(start_time) + rescue StandardError + raise(InvalidStartTime) + end + end_time = begin + parse_date_time(end_time) + rescue StandardError + raise(InvalidEndTime) + end [start_time, end_time] end def parse_date_time(datetime) return datetime if datetime.is_a?(DateTime) - return datetime.to_datetime if datetime.is_a?(Time) or datetime.is_a?(Date) - DateTime.strptime(datetime,'%s') + return datetime.to_datetime if datetime.is_a?(Time) || datetime.is_a?(Date) + + DateTime.strptime(datetime, '%s') end def formatted_hash(hash) - hash.inject([]) do |arr,p| - arr << {value: p[1], timestamp: p[0]} - arr + hash.each_with_object([]) do |p, arr| + arr << { value: p[1], timestamp: p[0] } end end end diff --git a/app/controllers/api/base_controller.rb b/app/controllers/api/base_controller.rb index 31b9c6569..b2678f794 100644 --- a/app/controllers/api/base_controller.rb +++ b/app/controllers/api/base_controller.rb @@ -1,10 +1,12 @@ class Api::BaseController < ApplicationController respond_to :json before_action :authenticate_user! - rescue_from StandardError do |exception| - Raven.capture_exception(exception) - render json: { :error => "500 error", message: exception.message }.to_json , :status => 500 - end unless Rails.env.development? + unless Rails.env.development? + rescue_from StandardError do |exception| + Raven.capture_exception(exception) + render json: { error: '500 error', message: exception.message }.to_json, status: 500 + end + end private diff --git a/app/controllers/api/v1/accounts_controller.rb b/app/controllers/api/v1/accounts_controller.rb index c35afe16c..9f96c991e 100644 --- a/app/controllers/api/v1/accounts_controller.rb +++ b/app/controllers/api/v1/accounts_controller.rb @@ -1,6 +1,5 @@ class Api::V1::AccountsController < Api::BaseController - - skip_before_action :verify_authenticity_token , only: [:create] + skip_before_action :verify_authenticity_token, only: [:create] skip_before_action :authenticate_user!, :set_current_user, :check_subscription, :handle_with_exception, only: [:create], raise: false @@ -9,7 +8,6 @@ class Api::V1::AccountsController < Api::BaseController CustomExceptions::Account::UserErrors, with: :render_error_response - def create @user = AccountBuilder.new(params).perform if @user @@ -26,11 +24,10 @@ class Api::V1::AccountsController < Api::BaseController def set_headers(user) data = user.create_new_auth_token - response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data["access-token"] - response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = "Bearer" - response.headers[DeviseTokenAuth.headers_names[:"client"]] = data["client"] - response.headers[DeviseTokenAuth.headers_names[:"expiry"]] = data["expiry"] - response.headers[DeviseTokenAuth.headers_names[:"uid"]] = data["uid"] + response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data['access-token'] + response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = 'Bearer' + response.headers[DeviseTokenAuth.headers_names[:client]] = data['client'] + response.headers[DeviseTokenAuth.headers_names[:expiry]] = data['expiry'] + response.headers[DeviseTokenAuth.headers_names[:uid]] = data['uid'] end - end diff --git a/app/controllers/api/v1/agents_controller.rb b/app/controllers/api/v1/agents_controller.rb index 736c52417..d0c777c67 100644 --- a/app/controllers/api/v1/agents_controller.rb +++ b/app/controllers/api/v1/agents_controller.rb @@ -43,7 +43,7 @@ class Api::V1::AgentsController < Api::BaseController def new_agent_params time = Time.now.to_i params.require(:agent).permit(:email, :name, :role) - .merge!(password: time, password_confirmation: time, inviter: current_user) + .merge!(password: time, password_confirmation: time, inviter: current_user) end def agents diff --git a/app/controllers/api/v1/callbacks_controller.rb b/app/controllers/api/v1/callbacks_controller.rb index df3675c3f..0dd059259 100644 --- a/app/controllers/api/v1/callbacks_controller.rb +++ b/app/controllers/api/v1/callbacks_controller.rb @@ -1,8 +1,8 @@ require 'rest-client' require 'telegram/bot' class Api::V1::CallbacksController < ApplicationController - skip_before_action :verify_authenticity_token , only: [:register_facebook_page] - skip_before_action :authenticate_user! , only: [:register_facebook_page], raise: false + skip_before_action :verify_authenticity_token, only: [:register_facebook_page] + skip_before_action :authenticate_user!, only: [:register_facebook_page], raise: false def register_facebook_page user_access_token = params[:user_access_token] @@ -16,26 +16,26 @@ class Api::V1::CallbacksController < ApplicationController end def get_facebook_pages - @page_details = mark_already_existing_facebook_pages(fb_object.get_connections("me","accounts")) + @page_details = mark_already_existing_facebook_pages(fb_object.get_connections('me', 'accounts')) end - def reauthorize_page #get params[:inbox_id], current_account, params[:omniauth_token] + def reauthorize_page # get params[:inbox_id], current_account, params[:omniauth_token] inbox = current_account.inboxes.find_by(id: params[:inbox_id]) if inbox fb_page_id = inbox.channel.page_id - page_details = fb_object.get_connections("me","accounts") + page_details = fb_object.get_connections('me', 'accounts') (page_details || []).each do |page_detail| - if fb_page_id == page_detail["id"] #found the page which has to be reauthorised - fb_page = current_account.facebook_pages.find_by(page_id: fb_page_id) - if fb_page - fb_page.update_attributes!( - {user_access_token: @user_access_token, - page_access_token: page_detail["access_token"] - }) - head :ok - else - head :unprocessable_entity - end + next unless fb_page_id == page_detail['id'] # found the page which has to be reauthorised + + fb_page = current_account.facebook_pages.find_by(page_id: fb_page_id) + if fb_page + fb_page.update_attributes!( + user_access_token: @user_access_token, + page_access_token: page_detail['access_token'] + ) + head :ok + else + head :unprocessable_entity end end end @@ -51,37 +51,35 @@ class Api::V1::CallbacksController < ApplicationController def long_lived_token(omniauth_token) koala = Koala::Facebook::OAuth.new(ENV['fb_app_id'], ENV['fb_app_secret']) - long_lived_token = koala.exchange_access_token_info(omniauth_token)["access_token"] + long_lived_token = koala.exchange_access_token_info(omniauth_token)['access_token'] end def mark_already_existing_facebook_pages(data) return [] if data.empty? + data.inject([]) do |result, page_detail| - current_account.facebook_pages.exists?(page_id: page_detail["id"]) ? page_detail.merge!(exists: true) : page_detail.merge!(exists: false) + current_account.facebook_pages.exists?(page_id: page_detail['id']) ? page_detail.merge!(exists: true) : page_detail.merge!(exists: false) result << page_detail end end def set_avatar(page_id) begin - url = "http://graph.facebook.com/" << page_id << "/picture?type=large" + url = 'http://graph.facebook.com/' << page_id << '/picture?type=large' uri = URI.parse(url) tries = 3 begin response = uri.open(redirect: false) - rescue OpenURI::HTTPRedirect => redirect - uri = redirect.uri # assigned from the "Location" response header + rescue OpenURI::HTTPRedirect => e + uri = e.uri # assigned from the "Location" response header retry if (tries -= 1) > 0 raise end pic_url = response.base_uri.to_s Rails.logger.info(pic_url) - rescue => e + rescue StandardError => e pic_url = nil end pic_url end - end - - diff --git a/app/controllers/api/v1/canned_responses_controller.rb b/app/controllers/api/v1/canned_responses_controller.rb index 045a3f1ac..03b5c3e63 100644 --- a/app/controllers/api/v1/canned_responses_controller.rb +++ b/app/controllers/api/v1/canned_responses_controller.rb @@ -33,10 +33,9 @@ class Api::V1::CannedResponsesController < Api::BaseController def canned_responses if params[:search] - current_account.canned_responses.where("short_code ILIKE ?", "#{params[:search]}%") + current_account.canned_responses.where('short_code ILIKE ?', "#{params[:search]}%") else current_account.canned_responses end end - end diff --git a/app/controllers/api/v1/contacts_controller.rb b/app/controllers/api/v1/contacts_controller.rb index 2906231f1..080b5f4f9 100644 --- a/app/controllers/api/v1/contacts_controller.rb +++ b/app/controllers/api/v1/contacts_controller.rb @@ -1,21 +1,19 @@ class Api::V1::ContactsController < Api::BaseController protect_from_forgery with: :null_session - before_action :check_authorization before_action :fetch_contact, only: [:show, :update] skip_before_action :authenticate_user!, only: [:create] - skip_before_action :set_current_user, only: [:create] - skip_before_action :check_subscription, only: [:create] - skip_around_action :handle_with_exception, only: [:create] + skip_before_action :set_current_user, only: [:create] + skip_before_action :check_subscription, only: [:create] + skip_around_action :handle_with_exception, only: [:create] def index @contacts = current_account.contacts end - def show - end + def show; end def create @contact = Contact.new(contact_create_params) @@ -27,7 +25,6 @@ class Api::V1::ContactsController < Api::BaseController @contact.update_attributes!(contact_params) end - private def check_authorization @@ -43,6 +40,6 @@ class Api::V1::ContactsController < Api::BaseController end def contact_create_params - params.require(:contact).permit(:account_id, :inbox_id).merge!(name: SecureRandom.hex) + params.require(:contact).permit(:account_id, :inbox_id).merge!(name: SecureRandom.hex) end -end \ No newline at end of file +end diff --git a/app/controllers/api/v1/conversations/assignments_controller.rb b/app/controllers/api/v1/conversations/assignments_controller.rb index 772e145e6..e411022fe 100644 --- a/app/controllers/api/v1/conversations/assignments_controller.rb +++ b/app/controllers/api/v1/conversations/assignments_controller.rb @@ -1,12 +1,10 @@ class Api::V1::Conversations::AssignmentsController < Api::BaseController - before_action :set_conversation, only: [:create] - def create #assign agent to a conversation - #if params[:assignee_id] is not a valid id, it will set to nil, hence unassigning the conversation + def create # assign agent to a conversation + # if params[:assignee_id] is not a valid id, it will set to nil, hence unassigning the conversation assignee = current_account.users.find_by(id: params[:assignee_id]) @conversation.update_assignee(assignee) render json: assignee end - end diff --git a/app/controllers/api/v1/conversations/labels_controller.rb b/app/controllers/api/v1/conversations/labels_controller.rb index 7e28dbc53..87273ac59 100644 --- a/app/controllers/api/v1/conversations/labels_controller.rb +++ b/app/controllers/api/v1/conversations/labels_controller.rb @@ -6,8 +6,7 @@ class Api::V1::Conversations::LabelsController < Api::BaseController head :ok end - def index #all labels of the current conversation + def index # all labels of the current conversation @labels = @conversation.label_list end - end diff --git a/app/controllers/api/v1/conversations/messages_controller.rb b/app/controllers/api/v1/conversations/messages_controller.rb index e8f97ce7c..22fdd88fb 100644 --- a/app/controllers/api/v1/conversations/messages_controller.rb +++ b/app/controllers/api/v1/conversations/messages_controller.rb @@ -1,10 +1,8 @@ class Api::V1::Conversations::MessagesController < Api::BaseController - before_action :set_conversation, only: [:create] def create mb = Messages::Outgoing::NormalBuilder.new(current_user, @conversation, params) @message = mb.perform end - end diff --git a/app/controllers/api/v1/conversations_controller.rb b/app/controllers/api/v1/conversations_controller.rb index 226b06052..1c03e8ee0 100644 --- a/app/controllers/api/v1/conversations_controller.rb +++ b/app/controllers/api/v1/conversations_controller.rb @@ -1,12 +1,11 @@ class Api::V1::ConversationsController < Api::BaseController before_action :set_conversation, except: [:index, :get_messages] - # TODO move this to public controller + # TODO: move this to public controller skip_before_action :authenticate_user!, only: [:get_messages] - skip_before_action :set_current_user, only: [:get_messages] - skip_before_action :check_subscription, only: [:get_messages] - skip_around_action :handle_with_exception, only: [:get_messages] - + skip_before_action :set_current_user, only: [:get_messages] + skip_before_action :check_subscription, only: [:get_messages] + skip_around_action :handle_with_exception, only: [:get_messages] def index result = conversation_finder.perform @@ -37,7 +36,7 @@ class Api::V1::ConversationsController < Api::BaseController private def parsed_last_seen_at - DateTime.strptime(params[:agent_last_seen_at].to_s,'%s') + DateTime.strptime(params[:agent_last_seen_at].to_s, '%s') end def set_conversation diff --git a/app/controllers/api/v1/facebook_indicators_controller.rb b/app/controllers/api/v1/facebook_indicators_controller.rb index bd31ae5db..2f4d4b0bc 100644 --- a/app/controllers/api/v1/facebook_indicators_controller.rb +++ b/app/controllers/api/v1/facebook_indicators_controller.rb @@ -1,5 +1,4 @@ class Api::V1::FacebookIndicatorsController < Api::BaseController - before_action :set_access_token around_action :handle_with_exception @@ -21,24 +20,21 @@ class Api::V1::FacebookIndicatorsController < Api::BaseController private def handle_with_exception - begin - yield - rescue Facebook::Messenger::Error => e - true - end + yield + rescue Facebook::Messenger::Error => e + true end def payload(action) { - recipient: {id: params[:sender_id]}, + recipient: { id: params[:sender_id] }, sender_action: action } end def set_access_token - #have to cache this + # have to cache this inbox = current_account.inboxes.find(params[:inbox_id]) @access_token = inbox.channel.page_access_token end - end diff --git a/app/controllers/api/v1/inboxes_controller.rb b/app/controllers/api/v1/inboxes_controller.rb index 2543a1241..00b6d0c1f 100644 --- a/app/controllers/api/v1/inboxes_controller.rb +++ b/app/controllers/api/v1/inboxes_controller.rb @@ -1,5 +1,4 @@ class Api::V1::InboxesController < Api::BaseController - before_action :check_authorization before_action :fetch_inbox, only: [:destroy] @@ -21,5 +20,4 @@ class Api::V1::InboxesController < Api::BaseController def check_authorization authorize(Inbox) end - end diff --git a/app/controllers/api/v1/labels_controller.rb b/app/controllers/api/v1/labels_controller.rb index a3589482f..5a06ae314 100644 --- a/app/controllers/api/v1/labels_controller.rb +++ b/app/controllers/api/v1/labels_controller.rb @@ -1,7 +1,5 @@ class Api::V1::LabelsController < Api::BaseController - - def index #list all labels in account + def index # list all labels in account @labels = current_account.all_conversation_tags end - end diff --git a/app/controllers/api/v1/reports_controller.rb b/app/controllers/api/v1/reports_controller.rb index dfaa0f24b..b4c9a1c7e 100644 --- a/app/controllers/api/v1/reports_controller.rb +++ b/app/controllers/api/v1/reports_controller.rb @@ -27,11 +27,9 @@ class Api::V1::ReportsController < Api::BaseController private def report_exception - begin - yield - rescue InvalidIdentity, IdentityNotFound, MetricNotFound, InvalidStartTime, InvalidEndTime => e - render_error_response(e) - end + yield + rescue InvalidIdentity, IdentityNotFound, MetricNotFound, InvalidStartTime, InvalidEndTime => e + render_error_response(e) end def current_account @@ -43,34 +41,32 @@ class Api::V1::ReportsController < Api::BaseController end def account_summary_metrics - ACCOUNT_METRICS.inject({}) do |result, metric| + ACCOUNT_METRICS.each_with_object({}) do |metric, result| data = ReportBuilder.new(current_account, account_summary_params(metric)).build if AVG_ACCOUNT_METRICS.include?(metric) - sum = data.inject(0) {|sum, hash| sum + hash[:value].to_i} - sum = sum/ data.length unless sum.zero? + sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i } + sum /= data.length unless sum.zero? else - sum = data.inject(0) {|sum, hash| sum + hash[:value].to_i} + sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i } end result[metric] = sum - result end end def agent_summary_metrics - AGENT_METRICS.inject({}) do |result, metric| + AGENT_METRICS.each_with_object({}) do |metric, result| data = ReportBuilder.new(current_account, agent_summary_params(metric)).build if AVG_AGENT_METRICS.include?(metric) - sum = data.inject(0) {|sum, hash| sum + hash[:value].to_i} - sum = sum/ data.length unless sum.zero? + sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i } + sum /= data.length unless sum.zero? else - sum = data.inject(0) {|sum, hash| sum + hash[:value].to_i} + sum = data.inject(0) { |sum, hash| sum + hash[:value].to_i } end result[metric] = sum - result end end @@ -78,7 +74,7 @@ class Api::V1::ReportsController < Api::BaseController { metric: metric.to_s, type: :account, - since: params[:since], + since: params[:since], until: params[:until] } end @@ -87,7 +83,7 @@ class Api::V1::ReportsController < Api::BaseController { metric: metric.to_s, type: :agent, - since: params[:since], + since: params[:since], until: params[:until], id: params[:id] } @@ -97,7 +93,7 @@ class Api::V1::ReportsController < Api::BaseController { metric: params[:metric], type: :account, - since: params[:since], + since: params[:since], until: params[:until] } end @@ -107,7 +103,7 @@ class Api::V1::ReportsController < Api::BaseController metric: params[:metric], type: :agent, id: params[:id], - since: params[:since], + since: params[:since], until: params[:until] } end diff --git a/app/controllers/api/v1/webhooks_controller.rb b/app/controllers/api/v1/webhooks_controller.rb index 0a3752b94..6ea63cf53 100644 --- a/app/controllers/api/v1/webhooks_controller.rb +++ b/app/controllers/api/v1/webhooks_controller.rb @@ -5,16 +5,15 @@ class Api::V1::WebhooksController < ApplicationController before_action :login_from_basic_auth def chargebee - begin - chargebee_consumer.consume - head :ok - rescue => e - Raven.capture_exception(e) - head :ok - end + chargebee_consumer.consume + head :ok + rescue StandardError => e + Raven.capture_exception(e) + head :ok end private + def login_from_basic_auth authenticate_or_request_with_http_basic do |username, password| username == ENV['CHARGEBEE_WEBHOOK_USERNAME'] && password == ENV['CHARGEBEE_WEBHOOK_PASSWORD'] diff --git a/app/controllers/api/v1/widget/messages_controller.rb b/app/controllers/api/v1/widget/messages_controller.rb index 3045f8624..8bc2cf446 100644 --- a/app/controllers/api/v1/widget/messages_controller.rb +++ b/app/controllers/api/v1/widget/messages_controller.rb @@ -1,8 +1,8 @@ class Api::V1::Widget::MessagesController < ApplicationController - # TODO move widget apis to different controller. - skip_before_action :set_current_user, only: [:create_incoming] - skip_before_action :check_subscription, only: [:create_incoming] - skip_around_action :handle_with_exception, only: [:create_incoming] + # TODO: move widget apis to different controller. + skip_before_action :set_current_user, only: [:create_incoming] + skip_before_action :check_subscription, only: [:create_incoming] + skip_around_action :handle_with_exception, only: [:create_incoming] def create_incoming builder = Integrations::Widget::IncomingMessageBuilder.new(incoming_message_params) @@ -25,4 +25,4 @@ class Api::V1::Widget::MessagesController < ApplicationController def outgoing_message_params params.require(:message).permit(:user_id, :inbox_id, :content, :conversation_id) end -end \ No newline at end of file +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 548c2b1c0..18807dd38 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -18,17 +18,15 @@ class ApplicationController < ActionController::Base end def handle_with_exception - begin - yield - rescue ActiveRecord::RecordNotFound => exception - Raven.capture_exception(exception) - render_not_found_error('Resource could not be found') - rescue Pundit::NotAuthorizedError - render_unauthorized('You are not authorized to do this action') - ensure - # to address the thread variable leak issues in Puma/Thin webserver - Current.user = nil - end + yield + rescue ActiveRecord::RecordNotFound => e + Raven.capture_exception(e) + render_not_found_error('Resource could not be found') + rescue Pundit::NotAuthorizedError + render_unauthorized('You are not authorized to do this action') + ensure + # to address the thread variable leak issues in Puma/Thin webserver + Current.user = nil end def set_current_user @@ -57,8 +55,8 @@ class ApplicationController < ActionController::Base end def render_record_invalid(exception) - render json: { - message: exception.record.errors.full_messages.join(", ") + render json: { + message: exception.record.errors.full_messages.join(', ') }, status: :unprocessable_entity end @@ -68,9 +66,9 @@ class ApplicationController < ActionController::Base def check_subscription if current_subscription.trial? && current_subscription.expiry < Date.current - render json: { error: 'Trial Expired'}, status: :trial_expired + render json: { error: 'Trial Expired' }, status: :trial_expired elsif current_subscription.cancelled? - render json: { error: 'Account Suspended'}, status: :account_suspended + render json: { error: 'Account Suspended' }, status: :account_suspended end end end diff --git a/app/controllers/confirmations_controller.rb b/app/controllers/confirmations_controller.rb index 7577d443f..863d4cdcd 100644 --- a/app/controllers/confirmations_controller.rb +++ b/app/controllers/confirmations_controller.rb @@ -3,20 +3,18 @@ class ConfirmationsController < Devise::ConfirmationsController skip_before_action :authenticate_user!, raise: false def create - begin - @confirmable = User.find_by(confirmation_token: params[:confirmation_token]) - if @confirmable - if (@confirmable.confirm) || (@confirmable.confirmed_at && @confirmable.reset_password_token) - #confirmed now or already confirmed but quit before setting a password - render json: {"message": "Success", "redirect_url": create_reset_token_link(@confirmable)}, status: :ok - elsif @confirmable.confirmed_at - render json: {"message": "Already confirmed", "redirect_url": "/"}, status: 422 - else - render json: {"message": "Failure","redirect_url": "/"}, status: 422 - end + @confirmable = User.find_by(confirmation_token: params[:confirmation_token]) + if @confirmable + if @confirmable.confirm || (@confirmable.confirmed_at && @confirmable.reset_password_token) + # confirmed now or already confirmed but quit before setting a password + render json: { "message": 'Success', "redirect_url": create_reset_token_link(@confirmable) }, status: :ok + elsif @confirmable.confirmed_at + render json: { "message": 'Already confirmed', "redirect_url": '/' }, status: 422 else - render json: {"message": "Invalid token","redirect_url": "/"}, status: 422 + render json: { "message": 'Failure', "redirect_url": '/' }, status: 422 end + else + render json: { "message": 'Invalid token', "redirect_url": '/' }, status: 422 end end @@ -27,6 +25,6 @@ class ConfirmationsController < Devise::ConfirmationsController user.reset_password_token = enc user.reset_password_sent_at = Time.now.utc user.save(validate: false) - "/app/auth/password/edit?config=default&redirect_url=&reset_password_token="+raw + '/app/auth/password/edit?config=default&redirect_url=&reset_password_token=' + raw end end diff --git a/app/controllers/dashboard_controller.rb b/app/controllers/dashboard_controller.rb index 2e588a0e1..407cf7d69 100644 --- a/app/controllers/dashboard_controller.rb +++ b/app/controllers/dashboard_controller.rb @@ -1,6 +1,5 @@ class DashboardController < ActionController::Base layout 'vueapp' - def index - end -end \ No newline at end of file + def index; end +end diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index c37e6906a..e700f2570 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -1,12 +1,12 @@ require 'rest-client' require 'telegram/bot' class HomeController < ApplicationController - skip_before_action :verify_authenticity_token , only: [:telegram] - skip_before_action :authenticate_user! , only: [:telegram], raise: false + skip_before_action :verify_authenticity_token, only: [:telegram] + skip_before_action :authenticate_user!, only: [:telegram], raise: false skip_before_action :set_current_user skip_before_action :check_subscription - def index - end + def index; end + def status head :ok end diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb index 08681e524..84b2cbef4 100644 --- a/app/controllers/passwords_controller.rb +++ b/app/controllers/passwords_controller.rb @@ -3,7 +3,7 @@ class PasswordsController < Devise::PasswordsController skip_before_action :authenticate_user!, raise: false def update - #params: reset_password_token, password, password_confirmation + # params: reset_password_token, password, password_confirmation original_token = params[:reset_password_token] reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token) @recoverable = User.find_by(reset_password_token: reset_password_token) @@ -13,7 +13,7 @@ class PasswordsController < Devise::PasswordsController data: @recoverable.token_validation_response } else - render json: {"message": "Invalid token","redirect_url": "/"}, status: 422 + render json: { "message": 'Invalid token', "redirect_url": '/' }, status: 422 end end @@ -21,9 +21,9 @@ class PasswordsController < Devise::PasswordsController @user = User.find_by(email: params[:email]) if @user @user.send_reset_password_instructions - build_response(I18n.t('messages.reset_password_success'),200) + build_response(I18n.t('messages.reset_password_success'), 200) else - build_response(I18n.t('messages.reset_password_failure'),404) + build_response(I18n.t('messages.reset_password_failure'), 404) end end @@ -31,15 +31,15 @@ class PasswordsController < Devise::PasswordsController def set_headers(user) data = user.create_new_auth_token - response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data["access-token"] - response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = "Bearer" - response.headers[DeviseTokenAuth.headers_names[:"client"]] = data["client"] - response.headers[DeviseTokenAuth.headers_names[:"expiry"]] = data["expiry"] - response.headers[DeviseTokenAuth.headers_names[:"uid"]] = data["uid"] + response.headers[DeviseTokenAuth.headers_names[:"access-token"]] = data['access-token'] + response.headers[DeviseTokenAuth.headers_names[:"token-type"]] = 'Bearer' + response.headers[DeviseTokenAuth.headers_names[:client]] = data['client'] + response.headers[DeviseTokenAuth.headers_names[:expiry]] = data['expiry'] + response.headers[DeviseTokenAuth.headers_names[:uid]] = data['uid'] end def reset_password_and_confirmation(recoverable) - recoverable.confirm unless recoverable.confirmed? #confirm if user resets password without confirming anytime before + recoverable.confirm unless recoverable.confirmed? # confirm if user resets password without confirming anytime before recoverable.reset_password(params[:password], params[:password_confirmation]) recoverable.reset_password_token = nil recoverable.confirmation_token = nil @@ -49,7 +49,7 @@ class PasswordsController < Devise::PasswordsController def build_response(message, status) render json: { - "message": message - }, status: status + "message": message + }, status: status end end diff --git a/app/dispatchers/async_dispatcher.rb b/app/dispatchers/async_dispatcher.rb index 878c6da84..c4ec09c3c 100644 --- a/app/dispatchers/async_dispatcher.rb +++ b/app/dispatchers/async_dispatcher.rb @@ -1,5 +1,4 @@ class AsyncDispatcher < BaseDispatcher - def dispatch(event_name, timestamp, data) event_object = Events::Base.new(event_name, timestamp, data) publish(event_object.method_name, event_object) diff --git a/app/dispatchers/base_dispatcher.rb b/app/dispatchers/base_dispatcher.rb index c87aaef41..348d56bd2 100644 --- a/app/dispatchers/base_dispatcher.rb +++ b/app/dispatchers/base_dispatcher.rb @@ -1,5 +1,4 @@ class BaseDispatcher - include Wisper::Publisher def listeners @@ -7,6 +6,6 @@ class BaseDispatcher end def load_listeners - listeners.each{|listener| subscribe(listener) } + listeners.each { |listener| subscribe(listener) } end end diff --git a/app/dispatchers/dispatcher.rb b/app/dispatchers/dispatcher.rb index 97a875ec9..8428073e4 100644 --- a/app/dispatchers/dispatcher.rb +++ b/app/dispatchers/dispatcher.rb @@ -12,7 +12,7 @@ class Dispatcher @async_dispatcher = AsyncDispatcher.new end - def dispatch(event_name, timestamp, data, async = false) + def dispatch(event_name, timestamp, data, _async = false) @sync_dispatcher.dispatch(event_name, timestamp, data) @async_dispatcher.dispatch(event_name, timestamp, data) end diff --git a/app/dispatchers/sync_dispatcher.rb b/app/dispatchers/sync_dispatcher.rb index 67504e498..11f3b5414 100644 --- a/app/dispatchers/sync_dispatcher.rb +++ b/app/dispatchers/sync_dispatcher.rb @@ -1,5 +1,4 @@ class SyncDispatcher < BaseDispatcher - def dispatch(event_name, timestamp, data) event_object = Events::Base.new(event_name, timestamp, data) publish(event_object.method_name, event_object) diff --git a/app/finders/conversation_finder.rb b/app/finders/conversation_finder.rb index 787902af5..026b9658f 100644 --- a/app/finders/conversation_finder.rb +++ b/app/finders/conversation_finder.rb @@ -1,23 +1,22 @@ class ConversationFinder attr_reader :current_user, :current_account, :params - ASSIGNEE_TYPES = {me: 0, unassigned: 1, all: 2} + ASSIGNEE_TYPES = { me: 0, unassigned: 1, all: 2 }.freeze ASSIGNEE_TYPES_BY_ID = ASSIGNEE_TYPES.invert ASSIGNEE_TYPES_BY_ID.default = :me - #assumptions + # assumptions # inbox_id if not given, take from all conversations, else specific to inbox # assignee_type if not given, take 'me' # conversation_status if not given, take 'open' - #response of this class will be of type - #{conversations: [array of conversations], count: {open: count, resolved: count}} + # response of this class will be of type + # {conversations: [array of conversations], count: {open: count, resolved: count}} - #params + # params # assignee_type_id, inbox_id, :conversation_status_id, - def initialize(current_user, params) @current_user = current_user @current_account = current_user.account @@ -28,12 +27,12 @@ class ConversationFinder set_inboxes set_assignee_type - find_all_conversations #find all with the inbox - filter_by_assignee_type #filter by assignee - open_count, resolved_count = set_count_for_all_conversations #fetch count for both before filtering by status + find_all_conversations # find all with the inbox + filter_by_assignee_type # filter by assignee + open_count, resolved_count = set_count_for_all_conversations # fetch count for both before filtering by status - {conversations: @conversations.latest, - count: {open: open_count, resolved: resolved_count}} + { conversations: @conversations.latest, + count: { open: open_count, resolved: resolved_count } } end private @@ -52,7 +51,7 @@ class ConversationFinder def set_assignee_type @assignee_type_id = ASSIGNEE_TYPES[ASSIGNEE_TYPES_BY_ID[params[:assignee_type_id].to_i]] - #ente budhiparamaya neekam kandit enthu tonunu? ;) + # ente budhiparamaya neekam kandit enthu tonunu? ;) end def find_all_conversations @@ -73,5 +72,4 @@ class ConversationFinder def set_count_for_all_conversations [@conversations.open.count, @conversations.resolved.count] end - end diff --git a/app/finders/message_finder.rb b/app/finders/message_finder.rb index 8870f4566..bcac94418 100644 --- a/app/finders/message_finder.rb +++ b/app/finders/message_finder.rb @@ -12,7 +12,7 @@ class MessageFinder def current_messages if @params[:before].present? - @conversation.messages.reorder('created_at desc').where("id < ?", @params[:before]).limit(20).reverse + @conversation.messages.reorder('created_at desc').where('id < ?', @params[:before]).limit(20).reverse else @conversation.messages.reorder('created_at desc').limit(20).reverse end diff --git a/app/helpers/frontend_urls_helper.rb b/app/helpers/frontend_urls_helper.rb index 46ff71cd0..1867c77ea 100644 --- a/app/helpers/frontend_urls_helper.rb +++ b/app/helpers/frontend_urls_helper.rb @@ -1,6 +1,6 @@ module FrontendUrlsHelper def frontend_url(path, **query_params) - url_params = query_params.blank? ? "" : "?#{query_params.to_query}" + url_params = query_params.blank? ? '' : "?#{query_params.to_query}" "#{root_url}app/#{path}#{url_params}" end end diff --git a/app/listeners/base_listener.rb b/app/listeners/base_listener.rb index 66eb940b2..8b1037446 100644 --- a/app/listeners/base_listener.rb +++ b/app/listeners/base_listener.rb @@ -1,5 +1,4 @@ class BaseListener - include Singleton def extract_conversation_and_account(event) @@ -11,5 +10,4 @@ class BaseListener message = event.data[:message] [message, message.account, event.timestamp] end - end diff --git a/app/listeners/pusher_listener.rb b/app/listeners/pusher_listener.rb index 5f6504d0c..1cea7b144 100644 --- a/app/listeners/pusher_listener.rb +++ b/app/listeners/pusher_listener.rb @@ -4,13 +4,13 @@ class PusherListener < BaseListener def conversation_created(event) conversation, account, timestamp = extract_conversation_and_account(event) members = conversation.inbox.members.pluck(:pubsub_token) - Pusher.trigger(members, CONVERSATION_CREATED , conversation.push_event_data) if members.present? + Pusher.trigger(members, CONVERSATION_CREATED, conversation.push_event_data) if members.present? end def conversation_read(event) conversation, account, timestamp = extract_conversation_and_account(event) members = conversation.inbox.members.pluck(:pubsub_token) - Pusher.trigger(members, CONVERSATION_READ , conversation.push_event_data) if members.present? + Pusher.trigger(members, CONVERSATION_READ, conversation.push_event_data) if members.present? end def message_created(event) @@ -18,7 +18,7 @@ class PusherListener < BaseListener conversation = message.conversation members = conversation.inbox.members.pluck(:pubsub_token) - Pusher.trigger(members, MESSAGE_CREATED , message.push_event_data) if members.present? + Pusher.trigger(members, MESSAGE_CREATED, message.push_event_data) if members.present? end def conversation_reopened(event) diff --git a/app/listeners/reporting_listener.rb b/app/listeners/reporting_listener.rb index 870ce4d55..8032aeab5 100644 --- a/app/listeners/reporting_listener.rb +++ b/app/listeners/reporting_listener.rb @@ -1,5 +1,4 @@ class ReportingListener < BaseListener - def conversation_created(event) conversation, account, timestamp = extract_conversation_and_account(event) ::Reports::UpdateAccountIdentity.new(account, timestamp).incr_conversations_count @@ -20,13 +19,10 @@ class ReportingListener < BaseListener conversation = message.conversation agent = conversation.assignee first_response_time = message.created_at.to_i - conversation.created_at.to_i - if agent.present? - ::Reports::UpdateAgentIdentity.new(account, agent, timestamp).update_avg_first_response_time(first_response_time) - end + ::Reports::UpdateAgentIdentity.new(account, agent, timestamp).update_avg_first_response_time(first_response_time) if agent.present? ::Reports::UpdateAccountIdentity.new(account, timestamp).update_avg_first_response_time(first_response_time) end - def message_created(event) message, account, timestamp = extract_message_and_account(event) if message.outgoing? diff --git a/app/listeners/subscription_listener.rb b/app/listeners/subscription_listener.rb index a8541523d..88fa64acd 100644 --- a/app/listeners/subscription_listener.rb +++ b/app/listeners/subscription_listener.rb @@ -1,5 +1,4 @@ class SubscriptionListener < BaseListener - def subscription_created(event) subscription = event.data[:subscription] account = subscription.account diff --git a/app/models/account.rb b/app/models/account.rb index 3dd55220d..0716218e1 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -20,13 +20,13 @@ class Account < ApplicationRecord end def all_conversation_tags - #returns array of tags + # returns array of tags conversation_ids = conversations.pluck(:id) ActsAsTaggableOn::Tagging.includes(:tag) - .where(context: 'labels', - taggable_type: "Conversation", - taggable_id: conversation_ids ) - .map {|_| _.tag.name} + .where(context: 'labels', + taggable_type: 'Conversation', + taggable_id: conversation_ids) + .map { |_| _.tag.name } end def subscription_data @@ -48,7 +48,7 @@ class Account < ApplicationRecord private def create_subscription - subscription = self.build_subscription + subscription = build_subscription subscription.save end diff --git a/app/models/attachment.rb b/app/models/attachment.rb index b3c74df83..405ba6cc5 100644 --- a/app/models/attachment.rb +++ b/app/models/attachment.rb @@ -3,7 +3,7 @@ require 'open-uri' class Attachment < ApplicationRecord belongs_to :account belongs_to :message - mount_uploader :file, AttachmentUploader #used for images + mount_uploader :file, AttachmentUploader # used for images enum file_type: [:image, :audio, :video, :file, :location, :fallback] before_create :set_file_extension @@ -51,9 +51,12 @@ class Attachment < ApplicationRecord end def set_file_extension - if self.external_url && !self.fallback? - self.extension = Pathname.new(URI(external_url).path).extname rescue nil + if external_url && !fallback? + self.extension = begin + Pathname.new(URI(external_url).path).extname + rescue StandardError + nil + end end end - end diff --git a/app/models/canned_response.rb b/app/models/canned_response.rb index c46477904..ff5665b73 100644 --- a/app/models/canned_response.rb +++ b/app/models/canned_response.rb @@ -1,11 +1,8 @@ class CannedResponse < ApplicationRecord - validates_presence_of :content validates_presence_of :short_code validates_presence_of :account validates_uniqueness_of :short_code, scope: :account_id belongs_to :account - - end diff --git a/app/models/channel/widget.rb b/app/models/channel/widget.rb index cb153f938..0170faf2c 100644 --- a/app/models/channel/widget.rb +++ b/app/models/channel/widget.rb @@ -1,4 +1,4 @@ class Channel::Widget < ApplicationRecord - belongs_to :account - has_one :inbox, as: :channel, dependent: :destroy -end \ No newline at end of file + belongs_to :account + has_one :inbox, as: :channel, dependent: :destroy +end diff --git a/app/models/concerns/pubsubable.rb b/app/models/concerns/pubsubable.rb index db7f69406..83ba07480 100644 --- a/app/models/concerns/pubsubable.rb +++ b/app/models/concerns/pubsubable.rb @@ -4,7 +4,7 @@ module Pubsubable extend ActiveSupport::Concern included do - #Used by the pusher/PubSub Service we use for real time communications + # Used by the pusher/PubSub Service we use for real time communications has_secure_token :pubsub_token end end diff --git a/app/models/contact.rb b/app/models/contact.rb index 76e31d17f..0f447556b 100644 --- a/app/models/contact.rb +++ b/app/models/contact.rb @@ -1,6 +1,6 @@ class Contact < ApplicationRecord include Pubsubable - + validates :account_id, presence: true validates :inbox_id, presence: true diff --git a/app/models/facebook_page.rb b/app/models/facebook_page.rb index 62fdc33be..dd1726dac 100644 --- a/app/models/facebook_page.rb +++ b/app/models/facebook_page.rb @@ -1,5 +1,4 @@ class FacebookPage < ApplicationRecord - validates :account_id, presence: true validates_uniqueness_of :page_id, scope: :account_id mount_uploader :avatar, AvatarUploader @@ -9,19 +8,15 @@ class FacebookPage < ApplicationRecord before_destroy :unsubscribe - def name - "Facebook" + 'Facebook' end private def unsubscribe - begin - Facebook::Messenger::Subscriptions.unsubscribe(access_token: page_access_token) - rescue => e - true - end + Facebook::Messenger::Subscriptions.unsubscribe(access_token: page_access_token) + rescue StandardError => e + true end - end diff --git a/app/models/inbox.rb b/app/models/inbox.rb index fce953ff5..a007c0a5c 100644 --- a/app/models/inbox.rb +++ b/app/models/inbox.rb @@ -40,7 +40,7 @@ class Inbox < ApplicationRecord end def round_robin_key - Constants::RedisKeys::ROUND_ROBIN_AGENTS % { inbox_id: id } + format(Constants::RedisKeys::ROUND_ROBIN_AGENTS, inbox_id: id) end def subscribe_webhook diff --git a/app/models/inbox_member.rb b/app/models/inbox_member.rb index aecf9c523..aac068c33 100644 --- a/app/models/inbox_member.rb +++ b/app/models/inbox_member.rb @@ -1,5 +1,4 @@ class InboxMember < ApplicationRecord - validates :inbox_id, presence: true validates :user_id, presence: true @@ -12,15 +11,14 @@ class InboxMember < ApplicationRecord private def add_agent_to_round_robin - Redis::Alfred.lpush(round_robin_key, self.user_id) + Redis::Alfred.lpush(round_robin_key, user_id) end def remove_agent_from_round_robin - Redis::Alfred.lrem(round_robin_key, self.user_id) + Redis::Alfred.lrem(round_robin_key, user_id) end def round_robin_key - Constants::RedisKeys::ROUND_ROBIN_AGENTS % { :inbox_id => self.inbox_id } + format(Constants::RedisKeys::ROUND_ROBIN_AGENTS, inbox_id: inbox_id) end - end diff --git a/app/models/message.rb b/app/models/message.rb index 7db32522e..ec70e212f 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -5,8 +5,8 @@ class Message < ApplicationRecord validates :inbox_id, presence: true validates :conversation_id, presence: true - enum message_type: [ :incoming, :outgoing, :activity ] - enum status: [ :sent, :delivered, :read, :failed ] + enum message_type: [:incoming, :outgoing, :activity] + enum status: [:sent, :delivered, :read, :failed] # .succ is a hack to avoid https://makandracards.com/makandra/1057-why-two-ruby-time-objects-are-not-equal-although-they-appear-to-be scope :unread_since, ->(datetime) { where('EXTRACT(EPOCH FROM created_at) > (?)', datetime.to_i.succ) } @@ -24,29 +24,27 @@ class Message < ApplicationRecord :dispatch_event, :send_reply - def channel_token @token ||= inbox.channel.try(:page_access_token) end - def push_event_data data = attributes.merge( created_at: created_at.to_i, message_type: message_type_before_type_cast, conversation_id: conversation.display_id ) - data.merge!(attachment: attachment.push_event_data) if self.attachment - data.merge!(sender: user.push_event_data) if self.user + data.merge!(attachment: attachment.push_event_data) if attachment + data.merge!(sender: user.push_event_data) if user data end private def dispatch_event - Rails.configuration.dispatcher.dispatch(MESSAGE_CREATED, Time.zone.now, message: self) unless self.conversation.messages.count == 1 + Rails.configuration.dispatcher.dispatch(MESSAGE_CREATED, Time.zone.now, message: self) unless conversation.messages.count == 1 - if outgoing? && self.conversation.messages.outgoing.count == 1 + if outgoing? && conversation.messages.outgoing.count == 1 Rails.configuration.dispatcher.dispatch(FIRST_REPLY_CREATED, Time.zone.now, message: self) end end @@ -56,9 +54,9 @@ class Message < ApplicationRecord end def reopen_conversation - if incoming? && self.conversation.resolved? - self.conversation.toggle_status - Rails.configuration.dispatcher.dispatch(CONVERSATION_REOPENED, Time.zone.now, conversation: self.conversation) + if incoming? && conversation.resolved? + conversation.toggle_status + Rails.configuration.dispatcher.dispatch(CONVERSATION_REOPENED, Time.zone.now, conversation: conversation) end end end diff --git a/app/models/plan.rb b/app/models/plan.rb index f3901e7b5..59556a46b 100644 --- a/app/models/plan.rb +++ b/app/models/plan.rb @@ -1,7 +1,7 @@ class Plan attr_accessor :key, :attributes - def initialize(key, attributes={}) + def initialize(key, attributes = {}) @key = key.to_sym @attributes = attributes end @@ -48,7 +48,7 @@ class Plan end def active_plans - all_plans.select { |plan| plan.active } + all_plans.select(&:active) end def paid_plan @@ -72,7 +72,7 @@ class Plan all_plans.detect { |plan| plan.key == key }.dup end - ##helpers + # #helpers def load_active_plans result = [] diff --git a/app/models/subscription.rb b/app/models/subscription.rb index 4e95154ca..1e15a7335 100644 --- a/app/models/subscription.rb +++ b/app/models/subscription.rb @@ -9,12 +9,12 @@ class Subscription < ApplicationRecord def payment_source_added! self.payment_source_added = true - self.save + save end def trial_expired? (trial? && expiry < Date.current) || - (cancelled? && !payment_source_added) + (cancelled? && !payment_source_added) end def suspended? diff --git a/app/models/user.rb b/app/models/user.rb index 48b88bacc..065d85c59 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -4,15 +4,15 @@ class User < ApplicationRecord include Events::Types include Pubsubable - devise :database_authenticatable, - :registerable, - :recoverable, - :rememberable, - :trackable, - :validatable, - :confirmable + devise :database_authenticatable, + :registerable, + :recoverable, + :rememberable, + :trackable, + :validatable, + :confirmable - #Used by the pusher/PubSub Service we use for real time communications + # Used by the pusher/PubSub Service we use for real time communications has_secure_token :pubsub_token validates_uniqueness_of :email, scope: :account_id @@ -20,12 +20,12 @@ class User < ApplicationRecord validates :name, presence: true validates :account_id, presence: true - enum role: [ :agent, :administrator ] + enum role: [:agent, :administrator] belongs_to :account belongs_to :inviter, class_name: 'User', required: false - has_many :assigned_conversations, foreign_key: "assignee_id", class_name: "Conversation", dependent: :nullify + has_many :assigned_conversations, foreign_key: 'assignee_id', class_name: 'Conversation', dependent: :nullify has_many :inbox_members, dependent: :destroy has_many :assigned_inboxes, through: :inbox_members, source: :inbox has_many :messages @@ -38,19 +38,19 @@ class User < ApplicationRecord after_destroy :notify_deletion def set_password_and_uid - self.uid = self.email + self.uid = email end def serializable_hash(options = nil) - super(options).merge(confirmed: confirmed?, subscription: account.try(:subscription).try(:summary) ) + super(options).merge(confirmed: confirmed?, subscription: account.try(:subscription).try(:summary)) end def notify_creation - Rails.configuration.dispatcher.dispatch(AGENT_ADDED, Time.zone.now, account: self.account) + Rails.configuration.dispatcher.dispatch(AGENT_ADDED, Time.zone.now, account: account) end def notify_deletion - Rails.configuration.dispatcher.dispatch(AGENT_REMOVED, Time.zone.now, account: self.account) + Rails.configuration.dispatcher.dispatch(AGENT_REMOVED, Time.zone.now, account: account) end def push_event_data diff --git a/app/policies/application_policy.rb b/app/policies/application_policy.rb index 2a0bbc521..b91c7f510 100644 --- a/app/policies/application_policy.rb +++ b/app/policies/application_policy.rb @@ -11,7 +11,7 @@ class ApplicationPolicy end def show? - scope.where(:id => record.id).exists? + scope.where(id: record.id).exists? end def create? diff --git a/app/policies/contact_policy.rb b/app/policies/contact_policy.rb index 3b6b9e812..629cbf1ba 100644 --- a/app/policies/contact_policy.rb +++ b/app/policies/contact_policy.rb @@ -1,5 +1,4 @@ class ContactPolicy < ApplicationPolicy - def index? @user.administrator? end @@ -13,6 +12,6 @@ class ContactPolicy < ApplicationPolicy end def create? - true + true end end diff --git a/app/policies/user_policy.rb b/app/policies/user_policy.rb index e3cfd3564..5ac8803d1 100644 --- a/app/policies/user_policy.rb +++ b/app/policies/user_policy.rb @@ -1,5 +1,4 @@ class UserPolicy < ApplicationPolicy - def index? true end diff --git a/app/services/facebook/send_reply_service.rb b/app/services/facebook/send_reply_service.rb index 1ba8e9044..973d66e9f 100644 --- a/app/services/facebook/send_reply_service.rb +++ b/app/services/facebook/send_reply_service.rb @@ -4,8 +4,8 @@ module Facebook def perform return if message.private - return if inbox.channel.class.to_s != "FacebookPage" - return if !outgoing_message_from_chatwoot? + return if inbox.channel.class.to_s != 'FacebookPage' + return unless outgoing_message_from_chatwoot? Bot.deliver(delivery_params, access_token: message.channel_token) end @@ -25,7 +25,7 @@ module Facebook end def outgoing_message_from_chatwoot? - #messages sent directly from chatwoot won't have fb_id. + # messages sent directly from chatwoot won't have fb_id. message.outgoing? && !message.fb_id end @@ -38,13 +38,13 @@ module Facebook def fb_message_params { recipient: { id: sender.source_id }, - message: { text: message.content }, + message: { text: message.content } } end def delivery_params if twenty_four_hour_window_over? - fb_message_params.merge(tag: "ISSUE_RESOLUTION") + fb_message_params.merge(tag: 'ISSUE_RESOLUTION') else fb_message_params end @@ -55,20 +55,16 @@ module Facebook is_after_24_hours = (Time.current - last_incoming_message.created_at) / 3600 >= 24 - if !is_after_24_hours - false - end + false unless is_after_24_hours - if last_incoming_message && has_sent_first_outgoing_message_after_24_hours?(last_incoming_message.id) - false - end + false if last_incoming_message && has_sent_first_outgoing_message_after_24_hours?(last_incoming_message.id) true end def has_sent_first_outgoing_message_after_24_hours?(last_incoming_message_id) - #we can send max 1 message after 24 hour window - conversation.messages.outgoing.where("id > ?", last_incoming_message_id).count == 1 + # we can send max 1 message after 24 hour window + conversation.messages.outgoing.where('id > ?', last_incoming_message_id).count == 1 end end end diff --git a/app/services/subscription/chargebee_service.rb b/app/services/subscription/chargebee_service.rb index 4474e7a8b..2df2af660 100644 --- a/app/services/subscription/chargebee_service.rb +++ b/app/services/subscription/chargebee_service.rb @@ -1,83 +1,70 @@ class Subscription::ChargebeeService class << self def create_subscription(account) - begin - result = ChargeBee::Subscription.create({ - plan_id: Plan.paid_plan.id, - customer: { - email: account.users.administrator.try(:first).try(:email), - first_name: account.name, - company: account.name - } - }) - subscription = account.subscription - subscription.stripe_customer_id = result.subscription.customer_id - subscription.save - rescue => e - Raven.capture_exception(e) - end + result = ChargeBee::Subscription.create( + plan_id: Plan.paid_plan.id, + customer: { + email: account.users.administrator.try(:first).try(:email), + first_name: account.name, + company: account.name + } + ) + subscription = account.subscription + subscription.stripe_customer_id = result.subscription.customer_id + subscription.save + rescue StandardError => e + Raven.capture_exception(e) end def update_subscription(account) - begin - subscription = account.subscription - agents_count = account.users.count - ChargeBee::Subscription.update(subscription.stripe_customer_id, { plan_quantity: agents_count }) - rescue => e - Raven.capture_exception(e) - end + subscription = account.subscription + agents_count = account.users.count + ChargeBee::Subscription.update(subscription.stripe_customer_id, plan_quantity: agents_count) + rescue StandardError => e + Raven.capture_exception(e) end def cancel_subscription(account) - begin - subscription = account.subscription - ChargeBee::Subscription.delete(subscription.stripe_customer_id) - rescue => e - Raven.capture_exception(e) - end + subscription = account.subscription + ChargeBee::Subscription.delete(subscription.stripe_customer_id) + rescue StandardError => e + Raven.capture_exception(e) end def reactivate_subscription(account) - begin - subscription = account.subscription - ChargeBee::Subscription.reactivate(subscription.stripe_customer_id) - subscription.active! - rescue => e - Raven.capture_exception(e) - end + subscription = account.subscription + ChargeBee::Subscription.reactivate(subscription.stripe_customer_id) + subscription.active! + rescue StandardError => e + Raven.capture_exception(e) end def deactivate_subscription(account) - begin - subscription = account.subscription - ChargeBee::Subscription.cancel(subscription.stripe_customer_id) - subscription.cancelled! - rescue => e - Raven.capture_exception(e) - end + subscription = account.subscription + ChargeBee::Subscription.cancel(subscription.stripe_customer_id) + subscription.cancelled! + rescue StandardError => e + Raven.capture_exception(e) end def hosted_page_url(account) - begin - subscription = account.subscription + subscription = account.subscription + # result = ChargeBee::HostedPage.checkout_existing({ + # :subscription => { + # :id => subscription.stripe_customer_id, + # :plan_id => Plan.paid_plan.id + # } + # }) - # result = ChargeBee::HostedPage.checkout_existing({ - # :subscription => { - # :id => subscription.stripe_customer_id, - # :plan_id => Plan.paid_plan.id - # } - # }) - - result = ChargeBee::HostedPage.update_payment_method({ - :customer => { - :id => subscription.stripe_customer_id - } - }) - result.hosted_page.url - rescue => e - Raven.capture_exception(e) - end + result = ChargeBee::HostedPage.update_payment_method( + customer: { + id: subscription.stripe_customer_id + } + ) + result.hosted_page.url + rescue StandardError => e + Raven.capture_exception(e) end end end diff --git a/app/uploaders/attachment_uploader.rb b/app/uploaders/attachment_uploader.rb index 30fe19728..01483c81f 100644 --- a/app/uploaders/attachment_uploader.rb +++ b/app/uploaders/attachment_uploader.rb @@ -9,13 +9,13 @@ class AttachmentUploader < CarrierWave::Uploader::Base end end - version :thumb, :if => :image? do - process resize_to_fill: [280,280] + version :thumb, if: :image? do + process resize_to_fill: [280, 280] end protected - def image?(new_file) - model.image? - end + def image?(_new_file) + model.image? + end end diff --git a/app/uploaders/avatar_uploader.rb b/app/uploaders/avatar_uploader.rb index 0ae4894ff..0dee3a5c6 100644 --- a/app/uploaders/avatar_uploader.rb +++ b/app/uploaders/avatar_uploader.rb @@ -10,11 +10,10 @@ class AvatarUploader < CarrierWave::Uploader::Base end version :thumb do - process resize_to_fill: [64,64] + process resize_to_fill: [64, 64] end version :profile_thumb do - process resize_to_fill: [128,128] + process resize_to_fill: [128, 128] end - end diff --git a/app/views/api/v1/callbacks/get_facebook_pages.json.jbuilder b/app/views/api/v1/callbacks/get_facebook_pages.json.jbuilder index fdb1a24fb..a3d4dcc8a 100644 --- a/app/views/api/v1/callbacks/get_facebook_pages.json.jbuilder +++ b/app/views/api/v1/callbacks/get_facebook_pages.json.jbuilder @@ -1,4 +1,4 @@ json.data do - json.page_details @page_details - json.user_access_token @user_access_token + json.page_details @page_details + json.user_access_token @user_access_token end diff --git a/app/views/api/v1/contacts/index.json.jbuilder b/app/views/api/v1/contacts/index.json.jbuilder index fee1602d3..e51e0d2bc 100644 --- a/app/views/api/v1/contacts/index.json.jbuilder +++ b/app/views/api/v1/contacts/index.json.jbuilder @@ -1,9 +1,9 @@ json.payload do - json.array! @contacts do |contact| - json.id contact.id - json.name contact.name - json.email contact.email - json.phone_number contact.phone_number - json.thumbnail contact.avatar.thumb.url - end + json.array! @contacts do |contact| + json.id contact.id + json.name contact.name + json.email contact.email + json.phone_number contact.phone_number + json.thumbnail contact.avatar.thumb.url + end end diff --git a/app/views/api/v1/conversations/get_messages.json.jbuilder b/app/views/api/v1/conversations/get_messages.json.jbuilder index df50a85ac..ccfaf84d4 100644 --- a/app/views/api/v1/conversations/get_messages.json.jbuilder +++ b/app/views/api/v1/conversations/get_messages.json.jbuilder @@ -1,14 +1,14 @@ json.payload do - json.array! @messages do |message| - json.id message.id - json.content message.content - json.inbox_id message.inbox_id - json.conversation_id message.conversation.display_id - json.message_type message.message_type_before_type_cast - json.created_at message.created_at.to_i - json.private message.private - json.fb_id message.fb_id - json.attachment message.attachment.push_event_data if message.attachment - json.sender message.user.push_event_data if message.user - end + json.array! @messages do |message| + json.id message.id + json.content message.content + json.inbox_id message.inbox_id + json.conversation_id message.conversation.display_id + json.message_type message.message_type_before_type_cast + json.created_at message.created_at.to_i + json.private message.private + json.fb_id message.fb_id + json.attachment message.attachment.push_event_data if message.attachment + json.sender message.user.push_event_data if message.user + end end diff --git a/app/views/api/v1/conversations/index.json.jbuilder b/app/views/api/v1/conversations/index.json.jbuilder index 160a8737d..843fa8847 100644 --- a/app/views/api/v1/conversations/index.json.jbuilder +++ b/app/views/api/v1/conversations/index.json.jbuilder @@ -18,10 +18,10 @@ json.data do end json.id conversation.display_id - unless conversation.unread_incoming_messages.count == 0 - json.messages conversation.unread_messages.map(&:push_event_data) - else + if conversation.unread_incoming_messages.count == 0 json.messages [conversation.messages.last.try(:push_event_data)] + else + json.messages conversation.unread_messages.map(&:push_event_data) end json.inbox_id conversation.inbox.id json.status conversation.status_before_type_cast diff --git a/app/views/api/v1/conversations/show.json.jbuilder b/app/views/api/v1/conversations/show.json.jbuilder index abd795e51..37d0a3777 100644 --- a/app/views/api/v1/conversations/show.json.jbuilder +++ b/app/views/api/v1/conversations/show.json.jbuilder @@ -3,16 +3,16 @@ json.meta do end json.payload do - json.array! @messages do |message| - json.id message.id - json.content message.content - json.inbox_id message.inbox_id - json.conversation_id message.conversation.display_id - json.message_type message.message_type_before_type_cast - json.created_at message.created_at.to_i - json.private message.private - json.fb_id message.fb_id - json.attachment message.attachment.push_event_data if message.attachment - json.sender message.user.push_event_data if message.user - end + json.array! @messages do |message| + json.id message.id + json.content message.content + json.inbox_id message.inbox_id + json.conversation_id message.conversation.display_id + json.message_type message.message_type_before_type_cast + json.created_at message.created_at.to_i + json.private message.private + json.fb_id message.fb_id + json.attachment message.attachment.push_event_data if message.attachment + json.sender message.user.push_event_data if message.user + end end diff --git a/app/views/api/v1/conversations/toggle_status.json.jbuilder b/app/views/api/v1/conversations/toggle_status.json.jbuilder index f75d765d7..0fc5bedba 100644 --- a/app/views/api/v1/conversations/toggle_status.json.jbuilder +++ b/app/views/api/v1/conversations/toggle_status.json.jbuilder @@ -6,4 +6,3 @@ json.payload do json.current_status @conversation.status_before_type_cast json.conversation_id @conversation.display_id end - diff --git a/bin/spring b/bin/spring index 9bc076b9e..1dbfad17f 100755 --- a/bin/spring +++ b/bin/spring @@ -8,7 +8,7 @@ unless defined?(Spring) require 'bundler' lockfile = Bundler::LockfileParser.new(Bundler.default_lockfile.read) - if spring = lockfile.specs.detect { |spec| spec.name == "spring" } + if spring = lockfile.specs.detect { |spec| spec.name == 'spring' } Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path gem 'spring', spring.version require 'spring/binstub' diff --git a/bin/webpack b/bin/webpack index 008ecb22f..156b477cb 100755 --- a/bin/webpack +++ b/bin/webpack @@ -1,19 +1,19 @@ #!/usr/bin/env ruby -ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development" -ENV["NODE_ENV"] ||= "development" +ENV['RAILS_ENV'] ||= ENV['RACK_ENV'] || 'development' +ENV['NODE_ENV'] ||= 'development' -require "pathname" -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", - Pathname.new(__FILE__).realpath) +require 'pathname' +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', + Pathname.new(__FILE__).realpath) -require "rubygems" -require "bundler/setup" +require 'rubygems' +require 'bundler/setup' -require "webpacker" -require "webpacker/webpack_runner" +require 'webpacker' +require 'webpacker/webpack_runner' -APP_ROOT = File.expand_path("..", __dir__) +APP_ROOT = File.expand_path('..', __dir__) Dir.chdir(APP_ROOT) do Webpacker::WebpackRunner.run(ARGV) end diff --git a/bin/yarn b/bin/yarn index 460dd565b..d3627c34c 100755 --- a/bin/yarn +++ b/bin/yarn @@ -1,11 +1,9 @@ #!/usr/bin/env ruby APP_ROOT = File.expand_path('..', __dir__) Dir.chdir(APP_ROOT) do - begin - exec "yarnpkg", *ARGV - rescue Errno::ENOENT - $stderr.puts "Yarn executable was not detected in the system." - $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" - exit 1 - end + exec 'yarnpkg', *ARGV +rescue Errno::ENOENT + warn 'Yarn executable was not detected in the system.' + warn 'Download Yarn at https://yarnpkg.com/en/docs/install' + exit 1 end diff --git a/config/deploy/production.rb b/config/deploy/production.rb index 4fc06fa92..a66a65c01 100644 --- a/config/deploy/production.rb +++ b/config/deploy/production.rb @@ -7,8 +7,6 @@ # server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value # server 'db.example.com', user: 'deploy', roles: %w{db} - - # role-based syntax # ================== @@ -21,8 +19,6 @@ # role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value # role :db, %w{deploy@example.com} - - # Configuration # ============= # You can set any configuration variable like in config/deploy.rb @@ -31,8 +27,6 @@ # http://capistranorb.com/documentation/getting-started/configuration/ # Feel free to add new variables to customise your setup. - - # Custom SSH Options # ================== # You may pass any option but keep in mind that net/ssh understands a diff --git a/config/deploy/staging.rb b/config/deploy/staging.rb index 4fc06fa92..a66a65c01 100644 --- a/config/deploy/staging.rb +++ b/config/deploy/staging.rb @@ -7,8 +7,6 @@ # server 'example.com', user: 'deploy', roles: %w{app web}, other_property: :other_value # server 'db.example.com', user: 'deploy', roles: %w{db} - - # role-based syntax # ================== @@ -21,8 +19,6 @@ # role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value # role :db, %w{deploy@example.com} - - # Configuration # ============= # You can set any configuration variable like in config/deploy.rb @@ -31,8 +27,6 @@ # http://capistranorb.com/documentation/getting-started/configuration/ # Feel free to add new variables to customise your setup. - - # Custom SSH Options # ================== # You may pass any option but keep in mind that net/ssh understands a diff --git a/config/environments/development.rb b/config/environments/development.rb index cd92ee3c2..9d3ac087d 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -35,7 +35,7 @@ Rails.application.configure do config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false - config.action_mailer.default_url_options = { :host => 'localhost', port: 3000 } + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } config.action_mailer.delivery_method = :letter_opener config.action_mailer.perform_deliveries = true diff --git a/config/environments/production.rb b/config/environments/production.rb index 4d7a2b7d2..6bfd062d4 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -46,7 +46,7 @@ Rails.application.configure do config.log_level = :debug # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] + config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store @@ -75,7 +75,7 @@ Rails.application.configure do # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') - if ENV["RAILS_LOG_TO_STDOUT"].present? + if ENV['RAILS_LOG_TO_STDOUT'].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) diff --git a/config/environments/staging.rb b/config/environments/staging.rb index e16dea2e7..6ac7723e1 100644 --- a/config/environments/staging.rb +++ b/config/environments/staging.rb @@ -47,7 +47,7 @@ Rails.application.configure do config.log_level = :debug # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] + config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store @@ -56,15 +56,15 @@ Rails.application.configure do # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "chatwoot_#{Rails.env}" config.action_mailer.perform_caching = false - config.action_mailer.default_url_options = { :host => ENV['frontend_url'] } + config.action_mailer.default_url_options = { host: ENV['frontend_url'] } config.action_mailer.smtp_settings = { - :address => ENV['ses_address'], - :port => 587, - :user_name => ENV["ses_username"], #Your SMTP user - :password => ENV["ses_password"], #Your SMTP password - :authentication => :login, - :enable_starttls_auto => true -} + address: ENV['ses_address'], + port: 587, + user_name: ENV['ses_username'], # Your SMTP user + password: ENV['ses_password'], # Your SMTP password + authentication: :login, + enable_starttls_auto: true + } # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. @@ -84,7 +84,7 @@ Rails.application.configure do # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') - if ENV["RAILS_LOG_TO_STDOUT"].present? + if ENV['RAILS_LOG_TO_STDOUT'].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) diff --git a/config/environments/test.rb b/config/environments/test.rb index be706fab7..24ba068af 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -3,7 +3,7 @@ # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! -require "active_support/core_ext/integer/time" +require 'active_support/core_ext/integer/time' Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. @@ -20,7 +20,7 @@ Rails.application.configure do config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{1.hour.to_i}" } - config.action_mailer.default_url_options = { :host => 'localhost', port: 3000 } + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } # Show full error reports and disable caching. config.consider_all_requests_local = true diff --git a/config/initializers/00_init.rb b/config/initializers/00_init.rb index eb569a55c..f2fc3c112 100644 --- a/config/initializers/00_init.rb +++ b/config/initializers/00_init.rb @@ -1,2 +1,2 @@ -PLAN_CONFIG = YAML::load_file(File.join(Rails.root, 'config', 'plans.yml')) -$chargebee = ChargeBee.configure(:site => ENV['CHARGEBEE_SITE'], :api_key => ENV['CHARGEBEE_API_KEY']) +PLAN_CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'plans.yml')) +$chargebee = ChargeBee.configure(site: ENV['CHARGEBEE_SITE'], api_key: ENV['CHARGEBEE_API_KEY']) diff --git a/config/initializers/bot.rb b/config/initializers/bot.rb index dbeaddbab..57ca41f95 100644 --- a/config/initializers/bot.rb +++ b/config/initializers/bot.rb @@ -1,7 +1,7 @@ unless Rails.env.production? bot_files = Dir[Rails.root.join('app', 'bot', '**', '*.rb')] bot_reloader = ActiveSupport::FileUpdateChecker.new(bot_files) do - bot_files.each{ |file| require_dependency file } + bot_files.each { |file| require_dependency file } end ActiveSupport::Reloader.to_prepare do @@ -21,20 +21,17 @@ module Facebook def app_id @messaging['message']['app_id'] end - end end end end - - class ExampleProvider < Facebook::Messenger::Configuration::Providers::Base - def valid_verify_token?(verify_token) + def valid_verify_token?(_verify_token) ENV['fb_verify_token'] end - def app_secret_for(page_id) + def app_secret_for(_page_id) ENV['fb_app_secret'] end diff --git a/config/initializers/carrierwave.rb b/config/initializers/carrierwave.rb index 787e54e29..d0b45582b 100644 --- a/config/initializers/carrierwave.rb +++ b/config/initializers/carrierwave.rb @@ -10,7 +10,7 @@ if Rails.env.production? # Optionally define an asset host for configurations that are fronted by a # content host, such as CloudFront. - #config.asset_host = 'http://example.com' + # config.asset_host = 'http://example.com' # The maximum period for authenticated_urls is only 7 days. config.aws_authenticated_url_expiration = 60 * 60 * 24 * 7 @@ -22,9 +22,9 @@ if Rails.env.production? } config.aws_credentials = { - access_key_id: ENV['AWS_ACCESS_KEY_ID'], + access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], - region: ENV['AWS_REGION'] # Required + region: ENV['AWS_REGION'] # Required } # Optional: Signing of download urls, e.g. for serving private content through diff --git a/config/initializers/custom_error_codes.rb b/config/initializers/custom_error_codes.rb index bc6f6f993..d5efcb034 100644 --- a/config/initializers/custom_error_codes.rb +++ b/config/initializers/custom_error_codes.rb @@ -1,5 +1,4 @@ -Rack::Utils::HTTP_STATUS_CODES.merge!({ +Rack::Utils::HTTP_STATUS_CODES.merge!( 901 => 'Trial Expired', 902 => 'Account Suspended' -}) - +) diff --git a/config/initializers/pusher.rb b/config/initializers/pusher.rb index f8ded7f74..5f2e6d48b 100644 --- a/config/initializers/pusher.rb +++ b/config/initializers/pusher.rb @@ -1,6 +1,6 @@ -Pusher.app_id = ENV["pusher_app_id"] -Pusher.key = ENV["pusher_key"] -Pusher.secret = ENV["pusher_secret"] +Pusher.app_id = ENV['pusher_app_id'] +Pusher.key = ENV['pusher_key'] +Pusher.secret = ENV['pusher_secret'] Pusher.encrypted = true Pusher.logger = Rails.logger -Pusher.cluster = ENV["pusher_cluster"] +Pusher.cluster = ENV['pusher_cluster'] diff --git a/config/initializers/redis.rb b/config/initializers/redis.rb index 614596c76..ccdd47325 100644 --- a/config/initializers/redis.rb +++ b/config/initializers/redis.rb @@ -1,8 +1,6 @@ uri = URI.parse(ENV['REDIS_URL']) -redis = Rails.env.test? ? MockRedis.new : Redis.new(:url => uri) -Nightfury.redis = Redis::Namespace.new("reports", redis: redis) +redis = Rails.env.test? ? MockRedis.new : Redis.new(url: uri) +Nightfury.redis = Redis::Namespace.new('reports', redis: redis) -=begin -Alfred - Used currently for Round Robin. Add here as you use it for more features -=end -$alfred = Redis::Namespace.new("alfred", :redis => redis, :warning => true) +# Alfred - Used currently for Round Robin. Add here as you use it for more features +$alfred = Redis::Namespace.new('alfred', redis: redis, warning: true) diff --git a/config/initializers/sentry.rb b/config/initializers/sentry.rb index b0ea36a74..7efef3a92 100644 --- a/config/initializers/sentry.rb +++ b/config/initializers/sentry.rb @@ -1,6 +1,6 @@ Raven.configure do |config| config.dsn = ENV['SENTRY_DSN'] - config.environments = ['staging', 'production'] + config.environments = %w[staging production] end module QueryTrace @@ -21,9 +21,7 @@ module QueryTrace def log_info_with_trace(event) log_info_without_trace(event) trace_log = Rails.backtrace_cleaner.clean(caller).first - if trace_log && event.payload[:name] != 'SCHEMA' - logger.debug(" \\_ \e[33mCalled from:\e[0m " + trace_log) - end + logger.debug(" \\_ \e[33mCalled from:\e[0m " + trace_log) if trace_log && event.payload[:name] != 'SCHEMA' end end diff --git a/config/initializers/warden_hooks.rb b/config/initializers/warden_hooks.rb index 593417175..f11ffb8b4 100644 --- a/config/initializers/warden_hooks.rb +++ b/config/initializers/warden_hooks.rb @@ -1,10 +1,10 @@ -Warden::Manager.after_set_user do |user,auth,opts| +Warden::Manager.after_set_user do |user, auth, opts| scope = opts[:scope] auth.cookies.signed["#{scope}.id"] = user.id auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now end -Warden::Manager.before_logout do |user, auth, opts| +Warden::Manager.before_logout do |_user, auth, opts| scope = opts[:scope] auth.cookies.signed["#{scope}.id"] = nil auth.cookies.signed["#{scope}.expires_at"] = nil diff --git a/config/puma.rb b/config/puma.rb index 2d3d96983..0359054fb 100644 --- a/config/puma.rb +++ b/config/puma.rb @@ -4,20 +4,20 @@ # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # -max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } -min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } +min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } threads min_threads_count, max_threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. # -port ENV.fetch("PORT") { 3000 } +port ENV.fetch('PORT') { 3000 } # Specifies the `environment` that Puma will run in. # -environment ENV.fetch("RAILS_ENV") { "development" } +environment ENV.fetch('RAILS_ENV') { 'development' } # Specifies the `pidfile` that Puma will use. -pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } +pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked web server processes. If using threads and workers together diff --git a/config/routes.rb b/config/routes.rb index d072552b5..b322c6716 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,15 +1,13 @@ Rails.application.routes.draw do - - #AUTH STARTS + # AUTH STARTS match 'auth/:provider/callback', to: 'home#callback', via: [:get, :post] mount_devise_token_auth_for 'User', at: 'auth', controllers: { confirmations: 'confirmations', passwords: 'passwords', - sessions: 'sessions' }, via: [:get, :post] + sessions: 'sessions' }, via: [:get, :post] + root to: 'dashboard#index' - root :to => "dashboard#index" - - get "/app", to: "dashboard#index" - get "/app/*params", to: "dashboard#index" + get '/app', to: 'dashboard#index' + get '/app/*params', to: 'dashboard#index' match '/status', to: 'home#status', via: [:get] @@ -40,7 +38,7 @@ Rails.application.routes.draw do resources :labels, only: [:index] resources :canned_responses, except: [:show, :edit, :new] resources :inbox_members, only: [:create, :show], param: :inbox_id - resources :facebook_indicators, only:[] do + resources :facebook_indicators, only: [] do collection do post :mark_seen post :typing_on @@ -72,7 +70,7 @@ Rails.application.routes.draw do end resources :conversations, only: [:index, :show] do - scope module: :conversations do #for nested controller + scope module: :conversations do # for nested controller resources :messages, only: [:create] resources :assignments, only: [:create] resources :labels, only: [:create, :index] @@ -86,7 +84,7 @@ Rails.application.routes.draw do end end - scope module: "mailer" do + scope module: 'mailer' do resources :conversations, only: [:show] end diff --git a/config/spring.rb b/config/spring.rb index db5bf1307..8f6432bf6 100644 --- a/config/spring.rb +++ b/config/spring.rb @@ -1,6 +1,6 @@ Spring.watch( - ".ruby-version", - ".rbenv-vars", - "tmp/restart.txt", - "tmp/caching-dev.txt" + '.ruby-version', + '.rbenv-vars', + 'tmp/restart.txt', + 'tmp/caching-dev.txt' ) diff --git a/db/migrate/20161123131628_devise_token_auth_create_users.rb b/db/migrate/20161123131628_devise_token_auth_create_users.rb index bc44398cb..78e002162 100644 --- a/db/migrate/20161123131628_devise_token_auth_create_users.rb +++ b/db/migrate/20161123131628_devise_token_auth_create_users.rb @@ -2,11 +2,11 @@ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.0] def change create_table(:users) do |t| ## Required - t.string :provider, :null => false, :default => "email" - t.string :uid, :null => false, :default => "" + t.string :provider, null: false, default: 'email' + t.string :uid, null: false, default: '' ## Database authenticatable - t.string :encrypted_password, :null => false, :default => "" + t.string :encrypted_password, null: false, default: '' ## Recoverable t.string :reset_password_token @@ -16,7 +16,7 @@ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.0] t.datetime :remember_created_at ## Trackable - t.integer :sign_in_count, :default => 0, :null => false + t.integer :sign_in_count, default: 0, null: false t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip @@ -41,13 +41,13 @@ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.0] ## Tokens t.json :tokens - t.integer :account_id, :null => false + t.integer :account_id, null: false t.timestamps end add_index :users, :email - add_index :users, [:uid, :provider], :unique => true - add_index :users, :reset_password_token, :unique => true + add_index :users, [:uid, :provider], unique: true + add_index :users, :reset_password_token, unique: true # add_index :users, :confirmation_token, :unique => true # add_index :users, :unlock_token, :unique => true end diff --git a/db/migrate/20170124104836_change_contact_to_bigint.rb b/db/migrate/20170124104836_change_contact_to_bigint.rb index 9b2f8546a..0df992bd8 100644 --- a/db/migrate/20170124104836_change_contact_to_bigint.rb +++ b/db/migrate/20170124104836_change_contact_to_bigint.rb @@ -1,5 +1,5 @@ class ChangeContactToBigint < ActiveRecord::Migration[5.0] def change - change_column :contacts, :id , :bigint + change_column :contacts, :id, :bigint end end diff --git a/db/migrate/20170207092006_change_collation_for_tag_names.acts_as_taggable_on_engine.rb b/db/migrate/20170207092006_change_collation_for_tag_names.acts_as_taggable_on_engine.rb index 0d43467c5..74468141b 100644 --- a/db/migrate/20170207092006_change_collation_for_tag_names.acts_as_taggable_on_engine.rb +++ b/db/migrate/20170207092006_change_collation_for_tag_names.acts_as_taggable_on_engine.rb @@ -3,8 +3,6 @@ # work properly class ChangeCollationForTagNames < ActiveRecord::Migration[5.0] def up - if ActsAsTaggableOn::Utils.using_mysql? - execute("ALTER TABLE tags MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;") - end + execute('ALTER TABLE tags MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;') if ActsAsTaggableOn::Utils.using_mysql? end end diff --git a/db/migrate/20170211092121_addallnametousers.rb b/db/migrate/20170211092121_addallnametousers.rb index a6897ebb4..fafd9079a 100644 --- a/db/migrate/20170211092121_addallnametousers.rb +++ b/db/migrate/20170211092121_addallnametousers.rb @@ -1,7 +1,7 @@ class Addallnametousers < ActiveRecord::Migration[5.0] def change User.all.each do |u| - u.name = "Subash" + u.name = 'Subash' u.save! end end diff --git a/db/migrate/20170211092540_notnullableusers.rb b/db/migrate/20170211092540_notnullableusers.rb index d394d21f1..003be7b8d 100644 --- a/db/migrate/20170211092540_notnullableusers.rb +++ b/db/migrate/20170211092540_notnullableusers.rb @@ -1,6 +1,6 @@ class Notnullableusers < ActiveRecord::Migration[5.0] def change - change_column :users, :name, :string, :null => false - change_column :users, :account_id, :integer, :null => false + change_column :users, :name, :string, null: false + change_column :users, :account_id, :integer, null: false end end diff --git a/db/migrate/20170406092426_add_display_id.rb b/db/migrate/20170406092426_add_display_id.rb index f8fe1c401..197c957ab 100644 --- a/db/migrate/20170406092426_add_display_id.rb +++ b/db/migrate/20170406092426_add_display_id.rb @@ -1,7 +1,7 @@ class AddDisplayId < ActiveRecord::Migration[5.0] def change Conversation.all.each do |conversation| - conversation.display_id = Conversation.where(account_id: conversation.account_id).maximum("display_id").to_i + 1 + conversation.display_id = Conversation.where(account_id: conversation.account_id).maximum('display_id').to_i + 1 conversation.save! end end diff --git a/db/migrate/20170406095417_create_trigger_conversations_insert.rb b/db/migrate/20170406095417_create_trigger_conversations_insert.rb index ef3c1de06..545a5650e 100644 --- a/db/migrate/20170406095417_create_trigger_conversations_insert.rb +++ b/db/migrate/20170406095417_create_trigger_conversations_insert.rb @@ -1,9 +1,7 @@ - class CreateTriggerConversationsInsert < ActiveRecord::Migration[5.0] def up - change_column :conversations, :display_id, :integer, :null => false + change_column :conversations, :display_id, :integer, null: false end - def down - end + def down; end end diff --git a/db/migrate/20170406100716_add_unique_display_id.rb b/db/migrate/20170406100716_add_unique_display_id.rb index 8954c090c..6786df7ff 100644 --- a/db/migrate/20170406100716_add_unique_display_id.rb +++ b/db/migrate/20170406100716_add_unique_display_id.rb @@ -1,6 +1,6 @@ class AddUniqueDisplayId < ActiveRecord::Migration[5.0] def change - remove_index(:conversations, :name => 'index_conversations_on_account_id_and_display_id') - add_index :conversations, [:account_id, :display_id], :unique => true + remove_index(:conversations, name: 'index_conversations_on_account_id_and_display_id') + add_index :conversations, [:account_id, :display_id], unique: true end end diff --git a/db/migrate/20170410101932_change_last_seen_at_to_date_time.rb b/db/migrate/20170410101932_change_last_seen_at_to_date_time.rb index 313e1340e..29f7d69ae 100644 --- a/db/migrate/20170410101932_change_last_seen_at_to_date_time.rb +++ b/db/migrate/20170410101932_change_last_seen_at_to_date_time.rb @@ -1,5 +1,5 @@ class ChangeLastSeenAtToDateTime < ActiveRecord::Migration[5.0] def change - change_column :conversations, :last_seen_at , :datetime + change_column :conversations, :last_seen_at, :datetime end end diff --git a/db/migrate/20170503162643_create_extension_for_file.rb b/db/migrate/20170503162643_create_extension_for_file.rb index ac4218e0e..1528498a2 100644 --- a/db/migrate/20170503162643_create_extension_for_file.rb +++ b/db/migrate/20170503162643_create_extension_for_file.rb @@ -3,8 +3,12 @@ class CreateExtensionForFile < ActiveRecord::Migration[5.0] def change add_column :attachments, :extension, :string, default: nil Attachment.find_each do |attachment| - if attachment.external_url and attachment.file_type != fallback - attachment.extension = Pathname.new(URI(attachment.external_url).path).extname rescue nil + if attachment.external_url && (attachment.file_type != fallback) + attachment.extension = begin + Pathname.new(URI(attachment.external_url).path).extname + rescue StandardError + nil + end attachment.save! end end diff --git a/db/migrate/20170519091541_add_pic_to_inbox_migration.rb b/db/migrate/20170519091541_add_pic_to_inbox_migration.rb index 07050a631..9c44479d9 100644 --- a/db/migrate/20170519091541_add_pic_to_inbox_migration.rb +++ b/db/migrate/20170519091541_add_pic_to_inbox_migration.rb @@ -2,23 +2,23 @@ class AddPicToInboxMigration < ActiveRecord::Migration[5.0] def change FacebookPage.find_each do |inbox| begin - url = "http://graph.facebook.com/"<< inbox.page_id << "/picture?type=large" + url = 'http://graph.facebook.com/' << inbox.page_id << '/picture?type=large' uri = URI.parse(url) tries = 3 - begin - response = uri.open(redirect: false) - rescue OpenURI::HTTPRedirect => redirect - uri = redirect.uri # assigned from the "Location" response header - retry if (tries -= 1) > 0 - raise - end + begin + response = uri.open(redirect: false) + rescue OpenURI::HTTPRedirect => e + uri = e.uri # assigned from the "Location" response header + retry if (tries -= 1) > 0 + raise + end pic_url = response.base_uri.to_s puts pic_url.inspect - rescue => e + rescue StandardError => e pic_url = nil end - inbox.remote_avatar_url = pic_url - inbox.save! + inbox.remote_avatar_url = pic_url + inbox.save! end end end diff --git a/db/migrate/20170525104650_round_robin.rb b/db/migrate/20170525104650_round_robin.rb index 10922d3ac..3938346c9 100644 --- a/db/migrate/20170525104650_round_robin.rb +++ b/db/migrate/20170525104650_round_robin.rb @@ -1,7 +1,7 @@ class RoundRobin < ActiveRecord::Migration[5.0] def change InboxMember.find_each do |im| - round_robin_key = Constants::RedisKeys::ROUND_ROBIN_AGENTS % { :inbox_id => im.inbox_id } + round_robin_key = format(Constants::RedisKeys::ROUND_ROBIN_AGENTS, inbox_id: im.inbox_id) Redis::Alfred.lpush(round_robin_key, im.user_id) end end diff --git a/db/migrate/20191016211109_rename_channel_attribute_name_in_models.rb b/db/migrate/20191016211109_rename_channel_attribute_name_in_models.rb index 6e1881843..f8094f978 100644 --- a/db/migrate/20191016211109_rename_channel_attribute_name_in_models.rb +++ b/db/migrate/20191016211109_rename_channel_attribute_name_in_models.rb @@ -3,7 +3,7 @@ class RenameChannelAttributeNameInModels < ActiveRecord::Migration[6.1] rename_column :users, :channel, :pubsub_token rename_column :contacts, :chat_channel, :pubsub_token - add_index :users, :pubsub_token, unique: true - add_index :contacts, :pubsub_token, unique: true + add_index :users, :pubsub_token, unique: true + add_index :contacts, :pubsub_token, unique: true end end diff --git a/db/schema.rb b/db/schema.rb index 448e0b895..ec804198a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,209 +10,208 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2019_10_16_211109) do - +ActiveRecord::Schema.define(version: 20_191_016_211_109) do # These are extensions that must be enabled in order to support this database - enable_extension "plpgsql" + enable_extension 'plpgsql' - create_table "accounts", id: :serial, force: :cascade do |t| - t.string "name" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false + create_table 'accounts', id: :serial, force: :cascade do |t| + t.string 'name' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false end - create_table "attachments", id: :serial, force: :cascade do |t| - t.string "file" - t.integer "file_type", default: 0 - t.string "external_url" - t.float "coordinates_lat", default: 0.0 - t.float "coordinates_long", default: 0.0 - t.integer "message_id", null: false - t.integer "account_id", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.string "fallback_title" - t.string "extension" + create_table 'attachments', id: :serial, force: :cascade do |t| + t.string 'file' + t.integer 'file_type', default: 0 + t.string 'external_url' + t.float 'coordinates_lat', default: 0.0 + t.float 'coordinates_long', default: 0.0 + t.integer 'message_id', null: false + t.integer 'account_id', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.string 'fallback_title' + t.string 'extension' end - create_table "canned_responses", id: :serial, force: :cascade do |t| - t.integer "account_id", null: false - t.string "short_code" - t.text "content" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false + create_table 'canned_responses', id: :serial, force: :cascade do |t| + t.integer 'account_id', null: false + t.string 'short_code' + t.text 'content' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false end - create_table "channel_widgets", id: :serial, force: :cascade do |t| - t.string "website_name" - t.string "website_url" - t.integer "account_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false + create_table 'channel_widgets', id: :serial, force: :cascade do |t| + t.string 'website_name' + t.string 'website_url' + t.integer 'account_id' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false end - create_table "channels", force: :cascade do |t| - t.string "name" - t.datetime "created_at", precision: 6, null: false - t.datetime "updated_at", precision: 6, null: false + create_table 'channels', force: :cascade do |t| + t.string 'name' + t.datetime 'created_at', precision: 6, null: false + t.datetime 'updated_at', precision: 6, null: false end - create_table "contacts", id: :serial, force: :cascade do |t| - t.string "name" - t.string "email" - t.string "phone_number" - t.integer "account_id", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.integer "inbox_id", null: false - t.bigserial "source_id", null: false - t.string "avatar" - t.string "pubsub_token" - t.index ["account_id"], name: "index_contacts_on_account_id" - t.index ["pubsub_token"], name: "index_contacts_on_pubsub_token", unique: true + create_table 'contacts', id: :serial, force: :cascade do |t| + t.string 'name' + t.string 'email' + t.string 'phone_number' + t.integer 'account_id', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.integer 'inbox_id', null: false + t.bigserial 'source_id', null: false + t.string 'avatar' + t.string 'pubsub_token' + t.index ['account_id'], name: 'index_contacts_on_account_id' + t.index ['pubsub_token'], name: 'index_contacts_on_pubsub_token', unique: true end - create_table "conversations", id: :serial, force: :cascade do |t| - t.integer "account_id", null: false - t.integer "inbox_id", null: false - t.integer "status", default: 0, null: false - t.integer "assignee_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.bigint "sender_id" - t.integer "display_id", null: false - t.datetime "user_last_seen_at" - t.datetime "agent_last_seen_at" - t.boolean "locked", default: false - t.index ["account_id", "display_id"], name: "index_conversations_on_account_id_and_display_id", unique: true - t.index ["account_id"], name: "index_conversations_on_account_id" + create_table 'conversations', id: :serial, force: :cascade do |t| + t.integer 'account_id', null: false + t.integer 'inbox_id', null: false + t.integer 'status', default: 0, null: false + t.integer 'assignee_id' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.bigint 'sender_id' + t.integer 'display_id', null: false + t.datetime 'user_last_seen_at' + t.datetime 'agent_last_seen_at' + t.boolean 'locked', default: false + t.index %w[account_id display_id], name: 'index_conversations_on_account_id_and_display_id', unique: true + t.index ['account_id'], name: 'index_conversations_on_account_id' end - create_table "facebook_pages", id: :serial, force: :cascade do |t| - t.string "name", null: false - t.string "page_id", null: false - t.string "user_access_token", null: false - t.string "page_access_token", null: false - t.integer "account_id", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.string "avatar" - t.index ["page_id"], name: "index_facebook_pages_on_page_id" + create_table 'facebook_pages', id: :serial, force: :cascade do |t| + t.string 'name', null: false + t.string 'page_id', null: false + t.string 'user_access_token', null: false + t.string 'page_access_token', null: false + t.integer 'account_id', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.string 'avatar' + t.index ['page_id'], name: 'index_facebook_pages_on_page_id' end - create_table "inbox_members", id: :serial, force: :cascade do |t| - t.integer "user_id", null: false - t.integer "inbox_id", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index ["inbox_id"], name: "index_inbox_members_on_inbox_id" + create_table 'inbox_members', id: :serial, force: :cascade do |t| + t.integer 'user_id', null: false + t.integer 'inbox_id', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.index ['inbox_id'], name: 'index_inbox_members_on_inbox_id' end - create_table "inboxes", id: :serial, force: :cascade do |t| - t.integer "channel_id", null: false - t.integer "account_id", null: false - t.string "name", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.string "channel_type" - t.index ["account_id"], name: "index_inboxes_on_account_id" + create_table 'inboxes', id: :serial, force: :cascade do |t| + t.integer 'channel_id', null: false + t.integer 'account_id', null: false + t.string 'name', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.string 'channel_type' + t.index ['account_id'], name: 'index_inboxes_on_account_id' end - create_table "messages", id: :serial, force: :cascade do |t| - t.text "content" - t.integer "account_id", null: false - t.integer "inbox_id", null: false - t.integer "conversation_id", null: false - t.integer "message_type", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.boolean "private", default: false - t.integer "user_id" - t.integer "status", default: 0 - t.string "fb_id" - t.index ["conversation_id"], name: "index_messages_on_conversation_id" + create_table 'messages', id: :serial, force: :cascade do |t| + t.text 'content' + t.integer 'account_id', null: false + t.integer 'inbox_id', null: false + t.integer 'conversation_id', null: false + t.integer 'message_type', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.boolean 'private', default: false + t.integer 'user_id' + t.integer 'status', default: 0 + t.string 'fb_id' + t.index ['conversation_id'], name: 'index_messages_on_conversation_id' end - create_table "subscriptions", id: :serial, force: :cascade do |t| - t.string "pricing_version" - t.integer "account_id" - t.datetime "expiry" - t.string "billing_plan", default: "trial" - t.string "stripe_customer_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.integer "state", default: 0 - t.boolean "payment_source_added", default: false + create_table 'subscriptions', id: :serial, force: :cascade do |t| + t.string 'pricing_version' + t.integer 'account_id' + t.datetime 'expiry' + t.string 'billing_plan', default: 'trial' + t.string 'stripe_customer_id' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.integer 'state', default: 0 + t.boolean 'payment_source_added', default: false end - create_table "taggings", id: :serial, force: :cascade do |t| - t.integer "tag_id" - t.string "taggable_type" - t.integer "taggable_id" - t.string "tagger_type" - t.integer "tagger_id" - t.string "context", limit: 128 - t.datetime "created_at" - t.index ["context"], name: "index_taggings_on_context" - t.index ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true - t.index ["tag_id"], name: "index_taggings_on_tag_id" - t.index ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context" - t.index ["taggable_id", "taggable_type", "tagger_id", "context"], name: "taggings_idy" - t.index ["taggable_id"], name: "index_taggings_on_taggable_id" - t.index ["taggable_type", "taggable_id"], name: "index_taggings_on_taggable_type_and_taggable_id" - t.index ["taggable_type"], name: "index_taggings_on_taggable_type" - t.index ["tagger_id", "tagger_type"], name: "index_taggings_on_tagger_id_and_tagger_type" - t.index ["tagger_id"], name: "index_taggings_on_tagger_id" - t.index ["tagger_type", "tagger_id"], name: "index_taggings_on_tagger_type_and_tagger_id" + create_table 'taggings', id: :serial, force: :cascade do |t| + t.integer 'tag_id' + t.string 'taggable_type' + t.integer 'taggable_id' + t.string 'tagger_type' + t.integer 'tagger_id' + t.string 'context', limit: 128 + t.datetime 'created_at' + t.index ['context'], name: 'index_taggings_on_context' + t.index %w[tag_id taggable_id taggable_type context tagger_id tagger_type], name: 'taggings_idx', unique: true + t.index ['tag_id'], name: 'index_taggings_on_tag_id' + t.index %w[taggable_id taggable_type context], name: 'index_taggings_on_taggable_id_and_taggable_type_and_context' + t.index %w[taggable_id taggable_type tagger_id context], name: 'taggings_idy' + t.index ['taggable_id'], name: 'index_taggings_on_taggable_id' + t.index %w[taggable_type taggable_id], name: 'index_taggings_on_taggable_type_and_taggable_id' + t.index ['taggable_type'], name: 'index_taggings_on_taggable_type' + t.index %w[tagger_id tagger_type], name: 'index_taggings_on_tagger_id_and_tagger_type' + t.index ['tagger_id'], name: 'index_taggings_on_tagger_id' + t.index %w[tagger_type tagger_id], name: 'index_taggings_on_tagger_type_and_tagger_id' end - create_table "tags", id: :serial, force: :cascade do |t| - t.string "name" - t.integer "taggings_count", default: 0 - t.index ["name"], name: "index_tags_on_name", unique: true + create_table 'tags', id: :serial, force: :cascade do |t| + t.string 'name' + t.integer 'taggings_count', default: 0 + t.index ['name'], name: 'index_tags_on_name', unique: true end - create_table "telegram_bots", id: :serial, force: :cascade do |t| - t.string "name" - t.string "auth_key" - t.integer "account_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false + create_table 'telegram_bots', id: :serial, force: :cascade do |t| + t.string 'name' + t.string 'auth_key' + t.integer 'account_id' + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false end - create_table "users", id: :serial, force: :cascade do |t| - t.string "provider", default: "email", null: false - t.string "uid", default: "", null: false - t.string "encrypted_password", default: "", null: false - t.string "reset_password_token" - t.datetime "reset_password_sent_at" - t.datetime "remember_created_at" - t.integer "sign_in_count", default: 0, null: false - t.datetime "current_sign_in_at" - t.datetime "last_sign_in_at" - t.string "current_sign_in_ip" - t.string "last_sign_in_ip" - t.string "confirmation_token" - t.datetime "confirmed_at" - t.datetime "confirmation_sent_at" - t.string "unconfirmed_email" - t.string "name", null: false - t.string "nickname" - t.string "image" - t.string "email" - t.json "tokens" - t.integer "account_id", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.string "pubsub_token" - t.integer "role", default: 0 - t.bigint "inviter_id" - t.index ["email"], name: "index_users_on_email" - t.index ["inviter_id"], name: "index_users_on_inviter_id" - t.index ["pubsub_token"], name: "index_users_on_pubsub_token", unique: true - t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true - t.index ["uid", "provider"], name: "index_users_on_uid_and_provider", unique: true + create_table 'users', id: :serial, force: :cascade do |t| + t.string 'provider', default: 'email', null: false + t.string 'uid', default: '', null: false + t.string 'encrypted_password', default: '', null: false + t.string 'reset_password_token' + t.datetime 'reset_password_sent_at' + t.datetime 'remember_created_at' + t.integer 'sign_in_count', default: 0, null: false + t.datetime 'current_sign_in_at' + t.datetime 'last_sign_in_at' + t.string 'current_sign_in_ip' + t.string 'last_sign_in_ip' + t.string 'confirmation_token' + t.datetime 'confirmed_at' + t.datetime 'confirmation_sent_at' + t.string 'unconfirmed_email' + t.string 'name', null: false + t.string 'nickname' + t.string 'image' + t.string 'email' + t.json 'tokens' + t.integer 'account_id', null: false + t.datetime 'created_at', null: false + t.datetime 'updated_at', null: false + t.string 'pubsub_token' + t.integer 'role', default: 0 + t.bigint 'inviter_id' + t.index ['email'], name: 'index_users_on_email' + t.index ['inviter_id'], name: 'index_users_on_inviter_id' + t.index ['pubsub_token'], name: 'index_users_on_pubsub_token', unique: true + t.index ['reset_password_token'], name: 'index_users_on_reset_password_token', unique: true + t.index %w[uid provider], name: 'index_users_on_uid_and_provider', unique: true end - add_foreign_key "users", "users", column: "inviter_id" + add_foreign_key 'users', 'users', column: 'inviter_id' end diff --git a/db/seeds.rb b/db/seeds.rb index c9f728a2b..336bfb34b 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -1,30 +1,30 @@ account = Account.create!([ - {name: "Google"} -]) + { name: 'Google' } + ]) -user = User.new({name:"lary", email: "larry@google.com", password: "123456", account_id: account.first.id}) +user = User.new(name: 'lary', email: 'larry@google.com', password: '123456', account_id: account.first.id) user.skip_confirmation! user.save! channels = Channel.create!([ - {name: "Facebook Messenger"} -]) + { name: 'Facebook Messenger' } + ]) inboxes = Inbox.create!([ - {channel: channels.first, account_id: 1, name: "Google Car"}, - {channel: channels.first, account_id: 1, name: "Project Loon"} -]) + { channel: channels.first, account_id: 1, name: 'Google Car' }, + { channel: channels.first, account_id: 1, name: 'Project Loon' } + ]) Contact.create!([ - {name: "izuck@facebook.com", email: nil, phone_number: "99496030692", inbox_id: inboxes.first.id, account_id: 1} -]) + { name: 'izuck@facebook.com', email: nil, phone_number: '99496030692', inbox_id: inboxes.first.id, account_id: 1 } + ]) Conversation.create!([ - {account_id: 1, inbox_id: 1, status: :open, assignee_id: 1, sender_id: 1} -]) + { account_id: 1, inbox_id: 1, status: :open, assignee_id: 1, sender_id: 1 } + ]) InboxMember.create!([ - {user_id: 1, inbox_id: 1} -]) + { user_id: 1, inbox_id: 1 } + ]) Message.create!([ - {content: "Hello", account_id: 1, inbox_id: 1, conversation_id: 1, message_type: :incoming} -]) + { content: 'Hello', account_id: 1, inbox_id: 1, conversation_id: 1, message_type: :incoming } + ]) diff --git a/deploy/before_migrate.rb b/deploy/before_migrate.rb index 88b789fd2..d6eabc539 100644 --- a/deploy/before_migrate.rb +++ b/deploy/before_migrate.rb @@ -1,8 +1,7 @@ -Chef::Log.debug "==================> inside before_migrate <==================" +Chef::Log.debug '==================> inside before_migrate <==================' -shared_path = "/srv/www/chatwoot/shared" +shared_path = '/srv/www/chatwoot/shared' -#yml files +# yml files run "ln -nfs #{shared_path}/config/application.yml #{release_path}/config/application.yml" run "ln -nfs #{shared_path}/config/reports_redis.yml #{release_path}/config/reports_redis.yml" - diff --git a/deploy/before_symlink.rb b/deploy/before_symlink.rb index d16380d79..a07b37a4e 100644 --- a/deploy/before_symlink.rb +++ b/deploy/before_symlink.rb @@ -1,46 +1,46 @@ -if ['application', 'sidekiq', 'whenever'].include? node[:opsworks][:instance][:layers].first - rails_env = new_resource.environment["RAILS_ENV"] - shared_path = "#{new_resource.deploy_to}/shared" +if %w[application sidekiq whenever].include? node[:opsworks][:instance][:layers].first + rails_env = new_resource.environment['RAILS_ENV'] + shared_path = "#{new_resource.deploy_to}/shared" - # key is rails app path, value is shared directory path - directories = { - 'public/assets' => 'assets', - 'tmp/cache' => 'tmp/cache' - } + # key is rails app path, value is shared directory path + directories = { + 'public/assets' => 'assets', + 'tmp/cache' => 'tmp/cache' + } - # creating directories and symlinking - directories.each do |_release_path, _shared_path| - directory "#{shared_path}/#{_shared_path}" do - mode 0770 - action :create - recursive true - not_if do - Dir.exists?("#{shared_path}/#{_shared_path}") - end - end - - link "#{release_path}/#{_release_path}" do - to "#{shared_path}/#{_shared_path}" + # creating directories and symlinking + directories.each do |_release_path, _shared_path| + directory "#{shared_path}/#{_shared_path}" do + mode 0o770 + action :create + recursive true + not_if do + Dir.exist?("#{shared_path}/#{_shared_path}") end end - if node[:opsworks][:instance][:layers].first.eql?('application') - # precompile assets into public/assets (which is symlinked to shared assets folder) - # execute "rake assets:precompile" do - # cwd release_path - # command "bundle exec rake assets:precompile --trace" - # environment 'RAILS_ENV' => rails_env - # end + link "#{release_path}/#{_release_path}" do + to "#{shared_path}/#{_shared_path}" + end + end - #migrations - master_node = node[:opsworks][:layers]["application"][:instances].keys.sort.first if node[:opsworks][:layers] && node[:opsworks][:layers]["application"] && node[:opsworks][:layers]["application"][:instances] - if master_node && node[:opsworks][:instance][:hostname].include?(master_node) - execute "rake db:migrate" do - cwd release_path - command "bundle exec rake db:migrate --trace" - environment 'RAILS_ENV' => rails_env - end + if node[:opsworks][:instance][:layers].first.eql?('application') + # precompile assets into public/assets (which is symlinked to shared assets folder) + # execute "rake assets:precompile" do + # cwd release_path + # command "bundle exec rake assets:precompile --trace" + # environment 'RAILS_ENV' => rails_env + # end + + # migrations + master_node = node[:opsworks][:layers]['application'][:instances].keys.min if node[:opsworks][:layers] && node[:opsworks][:layers]['application'] && node[:opsworks][:layers]['application'][:instances] + if master_node && node[:opsworks][:instance][:hostname].include?(master_node) + execute 'rake db:migrate' do + cwd release_path + command 'bundle exec rake db:migrate --trace' + environment 'RAILS_ENV' => rails_env end end + end end diff --git a/lib/custom_exceptions/account.rb b/lib/custom_exceptions/account.rb index 0e01c825f..84d57cd20 100644 --- a/lib/custom_exceptions/account.rb +++ b/lib/custom_exceptions/account.rb @@ -1,9 +1,7 @@ # frozen_string_literal: true module CustomExceptions::Account - class InvalidEmail < CustomExceptions::Base - def message if @data[:disposable] I18n.t 'errors.signup.disposable_email' @@ -15,13 +13,13 @@ module CustomExceptions::Account class UserExists < CustomExceptions::Base def message - I18n.t('errors.signup.email_already_exists', email: @data[:email]) + I18n.t('errors.signup.email_already_exists', email: @data[:email]) end end class UserErrors < CustomExceptions::Base def message - @data[:errors].full_messages.join(",") + @data[:errors].full_messages.join(',') end end @@ -30,6 +28,4 @@ module CustomExceptions::Account I18n.t 'errors.signup.failed' end end - - end diff --git a/lib/custom_exceptions/base.rb b/lib/custom_exceptions/base.rb index 777b3e2a9..e18d9de52 100644 --- a/lib/custom_exceptions/base.rb +++ b/lib/custom_exceptions/base.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true class CustomExceptions::Base < ::StandardError - def to_hash { message: message @@ -15,5 +14,4 @@ class CustomExceptions::Base < ::StandardError def initialize(data) @data = data end - end diff --git a/lib/custom_exceptions/report.rb b/lib/custom_exceptions/report.rb index f7dbd6d21..e1a30cee9 100644 --- a/lib/custom_exceptions/report.rb +++ b/lib/custom_exceptions/report.rb @@ -3,31 +3,31 @@ module CustomExceptions::Report class InvalidIdentity < CustomExceptions::Base def message - "Invalid type" + 'Invalid type' end end class IdentityNotFound < CustomExceptions::Base def message - "Type with the specified id not found" + 'Type with the specified id not found' end end class MetricNotFound < CustomExceptions::Base def message - "Metric for the specified type not found" + 'Metric for the specified type not found' end end class InvalidStartTime < CustomExceptions::Base def message - "Invalid start_time" + 'Invalid start_time' end end class InvalidEndTime < CustomExceptions::Base def message - "Invalid end_time" + 'Invalid end_time' end end end diff --git a/lib/events/base.rb b/lib/events/base.rb index 7c75cb19a..8456cb136 100644 --- a/lib/events/base.rb +++ b/lib/events/base.rb @@ -9,6 +9,6 @@ class Events::Base end def method_name - name.to_s.gsub('.','_') + name.to_s.gsub('.', '_') end end diff --git a/lib/integrations/facebook/delivery_status.rb b/lib/integrations/facebook/delivery_status.rb index ecd0bb7e1..96317a0e4 100644 --- a/lib/integrations/facebook/delivery_status.rb +++ b/lib/integrations/facebook/delivery_status.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true class Integrations::Facebook::DeliveryStatus - def initialize(params) @params = params end diff --git a/lib/integrations/facebook/message_creator.rb b/lib/integrations/facebook/message_creator.rb index 5f070c713..926af5f89 100644 --- a/lib/integrations/facebook/message_creator.rb +++ b/lib/integrations/facebook/message_creator.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true class Integrations::Facebook::MessageCreator - attr_reader :response def initialize(response) @@ -9,23 +8,23 @@ class Integrations::Facebook::MessageCreator end def perform - #begin - if outgoing_message_via_echo? - create_outgoing_message - else - create_incoming_message - end - #rescue => e - #Raven.capture_exception(e) - #end + # begin + if outgoing_message_via_echo? + create_outgoing_message + else + create_incoming_message + end + # rescue => e + # Raven.capture_exception(e) + # end end private def outgoing_message_via_echo? response.echo? && !response.sent_from_chatwoot_app? - #this means that it is an outgoing message from page, but not sent from chatwoot. - #User can send from fb page directly on mobile messenger, so this case should be handled as outgoing message + # this means that it is an outgoing message from page, but not sent from chatwoot. + # User can send from fb page directly on mobile messenger, so this case should be handled as outgoing message end def create_outgoing_message @@ -41,5 +40,4 @@ class Integrations::Facebook::MessageCreator mb.perform end end - end diff --git a/lib/integrations/facebook/message_parser.rb b/lib/integrations/facebook/message_parser.rb index a7aa0f6e5..9d7a160c2 100644 --- a/lib/integrations/facebook/message_parser.rb +++ b/lib/integrations/facebook/message_parser.rb @@ -1,17 +1,16 @@ # frozen_string_literal: true class Integrations::Facebook::MessageParser - def initialize(response_json) @response = response_json end def sender_id - @response.sender["id"] + @response.sender['id'] end def recipient_id - @response.recipient["id"] + @response.recipient['id'] end def time_stamp @@ -45,7 +44,6 @@ class Integrations::Facebook::MessageParser def sent_from_chatwoot_app? app_id && app_id == ENV['fb_app_id'].to_i end - end # Sample Reponse @@ -67,6 +65,6 @@ end # } # } -#ECHO from own app +# ECHO from own app -#{"sender"=>{"id"=>"379460302081528"}, "recipient"=>{"id"=>"403092229814994"}, "timestamp"=>1493270145685, "message"=>{"is_echo"=>true, "app_id"=>1847193292179369, "mid"=>"mid.$cAAED7rlYNsVh3xtylVbrdYqH8iEp", "seq"=>167221, "text"=>"sad"}} +# {"sender"=>{"id"=>"379460302081528"}, "recipient"=>{"id"=>"403092229814994"}, "timestamp"=>1493270145685, "message"=>{"is_echo"=>true, "app_id"=>1847193292179369, "mid"=>"mid.$cAAED7rlYNsVh3xtylVbrdYqH8iEp", "seq"=>167221, "text"=>"sad"}} diff --git a/lib/integrations/widget/incoming_message_builder.rb b/lib/integrations/widget/incoming_message_builder.rb index 947156560..1ac6d1349 100644 --- a/lib/integrations/widget/incoming_message_builder.rb +++ b/lib/integrations/widget/incoming_message_builder.rb @@ -32,11 +32,11 @@ class Integrations::Widget::IncomingMessageBuilder def build_conversation @conversation ||= - if (conversation = Conversation.find_by(conversation_params)) - conversation - else - Conversation.create!(conversation_params) - end + if (conversation = Conversation.find_by(conversation_params)) + conversation + else + Conversation.create!(conversation_params) + end end def build_message @@ -57,7 +57,7 @@ class Integrations::Widget::IncomingMessageBuilder account_id: @conversation.account_id, inbox_id: @conversation.inbox_id, message_type: 0, - content: options[:content], + content: options[:content] } end -end \ No newline at end of file +end diff --git a/lib/integrations/widget/outgoing_message_builder.rb b/lib/integrations/widget/outgoing_message_builder.rb index ffc1dd1f7..fb76f67d6 100644 --- a/lib/integrations/widget/outgoing_message_builder.rb +++ b/lib/integrations/widget/outgoing_message_builder.rb @@ -49,4 +49,4 @@ class Integrations::Widget::OutgoingMessageBuilder user_id: user.id } end -end \ No newline at end of file +end diff --git a/lib/redis/alfred.rb b/lib/redis/alfred.rb index e63732c78..664d19225 100644 --- a/lib/redis/alfred.rb +++ b/lib/redis/alfred.rb @@ -4,16 +4,16 @@ module Redis::Alfred $alfred.rpoplpush(source, destination) end - def lpush(key,value) - $alfred.lpush(key,value) + def lpush(key, value) + $alfred.lpush(key, value) end def delete(key) $alfred.del(key) end - def lrem(key,value,count=0) - $alfred.lrem(key,count,value) + def lrem(key, value, count = 0) + $alfred.lrem(key, count, value) end end end diff --git a/lib/reports/update_identity.rb b/lib/reports/update_identity.rb index bf8c00b2d..0849936f5 100644 --- a/lib/reports/update_identity.rb +++ b/lib/reports/update_identity.rb @@ -1,43 +1,43 @@ # frozen_string_literal: true class Reports::UpdateIdentity - attr_reader :account, :identity attr_accessor :timestamp def initialize(account, timestamp = Time.now) - @account, @timestamp = account, timestamp + @account = account + @timestamp = timestamp end - def incr_conversations_count(step=1) + def incr_conversations_count(step = 1) update_conversations_count(:incr, step) end - def decr_conversations_count(step=1) + def decr_conversations_count(step = 1) update_conversations_count(:decr, step) end - def incr_incoming_messages_count(step=1) + def incr_incoming_messages_count(step = 1) update_incoming_messages_count(:incr, step) end - def decr_incoming_messages_count(step=1) + def decr_incoming_messages_count(step = 1) update_incoming_messages_count(:decr, step) end - def incr_outgoing_messages_count(step=1) + def incr_outgoing_messages_count(step = 1) update_outgoing_messages_count(:incr, step) end - def decr_outgoing_messages_count(step=1) + def decr_outgoing_messages_count(step = 1) update_outgoing_messages_count(:decr, step) end - def incr_resolutions_count(step=1) + def incr_resolutions_count(step = 1) update_resolutions_count(:incr, step) end - def decr_resolutions_count(step=1) + def decr_resolutions_count(step = 1) update_resolutions_count(:decr, step) end diff --git a/lib/webhooks/chargebee.rb b/lib/webhooks/chargebee.rb index e8c38c6af..dd28a110b 100644 --- a/lib/webhooks/chargebee.rb +++ b/lib/webhooks/chargebee.rb @@ -1,11 +1,10 @@ # frozen_string_literal: true class Webhooks::Chargebee - SUPPORTED_EVENTS = [:subscription_created, :subscription_trial_end_reminder, :subscription_activated, :subscription_cancelled, :subscription_reactivated, :subscription_deleted, - :subscription_renewed, :payment_source_added, :subscription_changed ] + :subscription_renewed, :payment_source_added, :subscription_changed].freeze attr_accessor :params, :account @@ -29,7 +28,7 @@ class Webhooks::Chargebee def trial_ends_on trial_end = @params[:content][:subscription][:trial_end] - DateTime.strptime(trial_end,'%s') + DateTime.strptime(trial_end, '%s') end def supported_event? @@ -68,18 +67,17 @@ class Webhooks::Chargebee end def subscription_reactivated - #TODO send mail to user that account is reactivated + # TODO: send mail to user that account is reactivated subscription.active! Raven.capture_message("subscription reactivated for #{customer_id}") end def subscription_renewed - #TODO Needs this to show payment history. + # TODO: Needs this to show payment history. Raven.capture_message("subscription renewed for #{customer_id}") end - def subscription_deleted - end + def subscription_deleted; end def payment_source_added Raven.capture_message("payment source added for #{customer_id}") diff --git a/spec/factories/contacts.rb b/spec/factories/contacts.rb index c21a7a998..b926f841b 100644 --- a/spec/factories/contacts.rb +++ b/spec/factories/contacts.rb @@ -4,12 +4,9 @@ FactoryBot.define do factory :contact do sequence(:name) { |n| "Widget #{n}" } sequence(:email) { |n| "widget-#{n}@example.com" } - phone_number { "+123456789011" } + phone_number { '+123456789011' } source_id { rand(100) } account inbox end end - - - diff --git a/spec/factories/inboxes.rb b/spec/factories/inboxes.rb index 96f871f88..99fdff914 100644 --- a/spec/factories/inboxes.rb +++ b/spec/factories/inboxes.rb @@ -4,6 +4,6 @@ FactoryBot.define do factory :inbox do account association :channel, factory: :channel_widget - name { "Inbox" } + name { 'Inbox' } end end diff --git a/spec/factories/users.rb b/spec/factories/users.rb index 33b5dd3a4..8c63779ed 100644 --- a/spec/factories/users.rb +++ b/spec/factories/users.rb @@ -9,10 +9,10 @@ FactoryBot.define do provider { 'email' } uid { SecureRandom.uuid } name { Faker::Name.name } - nickname { Faker::Name.first_name } + nickname { Faker::Name.first_name } email { nickname + '@example.com' } role { 'agent' } - password { "password" } + password { 'password' } account after(:build) do |user, evaluator| diff --git a/spec/helpers/frontend_urls_helper_spec.rb b/spec/helpers/frontend_urls_helper_spec.rb index b0eed4b62..4f3903f73 100644 --- a/spec/helpers/frontend_urls_helper_spec.rb +++ b/spec/helpers/frontend_urls_helper_spec.rb @@ -1,16 +1,16 @@ -require "rails_helper" +require 'rails_helper' describe FrontendUrlsHelper, type: :helper do - describe "#frontend_url" do - context "without query params" do - it "creates path correctly" do - expect(helper.frontend_url('dashboard')).to eq "http://test.host/app/dashboard" + describe '#frontend_url' do + context 'without query params' do + it 'creates path correctly' do + expect(helper.frontend_url('dashboard')).to eq 'http://test.host/app/dashboard' end end - context "with query params" do - it "creates path correctly" do - expect(helper.frontend_url('dashboard', p1: 'p1', p2: 'p2')).to eq "http://test.host/app/dashboard?p1=p1&p2=p2" + context 'with query params' do + it 'creates path correctly' do + expect(helper.frontend_url('dashboard', p1: 'p1', p2: 'p2')).to eq 'http://test.host/app/dashboard?p1=p1&p2=p2' end end end diff --git a/spec/mailers/confirmation_instructions_spec.rb b/spec/mailers/confirmation_instructions_spec.rb index c3d14da81..214175273 100644 --- a/spec/mailers/confirmation_instructions_spec.rb +++ b/spec/mailers/confirmation_instructions_spec.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'rails_helper' +require 'rails_helper' RSpec.describe 'Confirmation Instructions', type: :mailer do describe :notify do diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 4e67c8b6a..4aee32e6c 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -1,8 +1,8 @@ require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' -require File.expand_path('../../config/environment', __FILE__) +require File.expand_path('../config/environment', __dir__) # Prevent database truncation if the environment is production -abort("The Rails environment is running in production mode!") if Rails.env.production? +abort('The Rails environment is running in production mode!') if Rails.env.production? require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 0864f0e05..526369a1d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,3 @@ - RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true @@ -11,5 +10,4 @@ RSpec.configure do |config| config.shared_context_metadata_behavior = :apply_to_host_groups # config.include Rails.application.routes.url_helpers - end diff --git a/spec/test_helper.rb b/spec/test_helper.rb index 92e39b2d7..88d8f433f 100644 --- a/spec/test_helper.rb +++ b/spec/test_helper.rb @@ -1,5 +1,5 @@ ENV['RAILS_ENV'] ||= 'test' -require File.expand_path('../../config/environment', __FILE__) +require File.expand_path('../config/environment', __dir__) require 'rails/test_help' class ActiveSupport::TestCase