docbrown/app/models/consumer_app.rb
Fernando Valverde e602d50d32
Push Notification multi app support (#13304)
* PushNotificationTarget model + /admin/push_notifications (index)

* Admin panel CRUD + request tests

* Migrate Redis backed Rpush model responsibilities into PushNotificationTarget

* Fix failing specs

* Fix conflicts + clean up test by using constant reference

* Removed unused policy

* policy + services + misc feedback

* PushNotificationTarget refactored to AppIntegration

* Review feedback

* Some small cleanup

* Refactor AppIntegration -> ConsumerApp

* Fixing specs

* Trigger Travis

* More naming refactor changes

* Refactor services into queries

* Revert to where(...).first, fix typo and tests

* Apply suggestions from code review

Co-authored-by: rhymes <rhymes@hey.com>

* PR review feedback - create_or_find_by, validations, renaming + more tests

* Fix aria-label text

* Remove unnecessary individual index - composite index will do

Co-authored-by: rhymes <rhymes@hey.com>
2021-04-21 17:13:01 -06:00

61 lines
1.8 KiB
Ruby

class ConsumerApp < ApplicationRecord
resourcify
FOREM_BUNDLE = "com.forem.app".freeze
SUPPORTED_PLATFORMS = [Device::ANDROID, Device::IOS].freeze
FOREM_APP_PLATFORMS = [Device::IOS].freeze
validates :app_bundle, presence: true
validates :platform, presence: true
validates :app_bundle, uniqueness: { scope: :platform }
has_many :devices, dependent: :destroy
# Clear Redis-backed model to ensure it will be recreated with updated values
after_update :clear_rpush_app
def forem_app?
app_bundle == FOREM_BUNDLE && FOREM_APP_PLATFORMS.include?(platform)
end
def creator_app?
!forem_app?
end
# When an error is raised during an attempt to deliver PNs we should catch
# them, mark the app as active=false and the error logged into `last_error`
# If the app is marked as active and credentials are available it's likely
# the ConsumerApp is operational.
def operational?
active && auth_credentials.present?
end
# The Forem apps will get their credentials from an ENV variable, whereas
# custom PN targets will get their credentials from the auth_key stored in
# the DB (configured by the Forem creator).
def auth_credentials
if forem_app?
ApplicationConfig["RPUSH_IOS_PEM"]
else
auth_key
end
end
private
# [@forem/backend] `.where().first` is necessary because we use Redis data storage
# https://github.com/rpush/rpush/wiki/Using-Redis#find_by_name-cannot-be-used-in-rpush-redis
# rubocop:disable Rails/FindBy
def clear_rpush_app
case platform_was
when Device::IOS
Rpush::Apns2::App.where(name: app_bundle_was).first&.destroy
when Device::ANDROID
Rpush::Gcm::App.where(name: app_bundle_was).first&.destroy
end
# This prevents the `destroy` method to return true or false in a callback
true
end
# rubocop:enable Rails/FindBy
end