|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Fcm |
| 4 | + class Client |
| 5 | + # Handle notification delivery methods |
| 6 | + module NotificationDilivery |
| 7 | + BASE_URI = 'https://fcm.googleapis.com' |
| 8 | + END_POINT = '/fcm/send' |
| 9 | + |
| 10 | + def send_notification(registration_ids, options = {}) |
| 11 | + post_body = build_post_body(registration_ids, options) |
| 12 | + res = make_request( |
| 13 | + :post, BASE_URI, END_POINT, post_body, authorization_headers |
| 14 | + ) |
| 15 | + Fcm::Response.build_fcm_response(res, registration_ids) |
| 16 | + end |
| 17 | + |
| 18 | + def send_with_notification_key(notification_key, options = {}) |
| 19 | + body = { to: notification_key }.merge(options) |
| 20 | + res = make_request( |
| 21 | + :post, BASE_URI, END_POINT, body, authorization_headers |
| 22 | + ) |
| 23 | + Fcm::Response.build_fcm_response(res) |
| 24 | + end |
| 25 | + |
| 26 | + def send_to_topic_condition(condition, options = {}) |
| 27 | + return unless validate_condition?(condition) |
| 28 | + |
| 29 | + body = { condition: condition }.merge(options) |
| 30 | + |
| 31 | + res = make_request( |
| 32 | + :post, BASE_URI, END_POINT, body, authorization_headers |
| 33 | + ) |
| 34 | + Fcm::Response.build_fcm_response(res) |
| 35 | + end |
| 36 | + |
| 37 | + def send_to_topic(topic, options = {}) |
| 38 | + return unless topic.gsub(/[a-zA-Z0-9\-_.~%]+/, '').length.zero? |
| 39 | + |
| 40 | + send_with_notification_key("/topics/#{topic}", options) |
| 41 | + end |
| 42 | + |
| 43 | + private |
| 44 | + |
| 45 | + def validate_condition?(condition) |
| 46 | + validate_condition_format?( |
| 47 | + condition |
| 48 | + ) && validate_condition_topics?( |
| 49 | + condition |
| 50 | + ) |
| 51 | + end |
| 52 | + |
| 53 | + def validate_condition_format?(condition) |
| 54 | + bad_characters = condition.gsub( |
| 55 | + /(topics|in|\s|\(|\)|(&&)|!|(\|\|)|'([a-zA-Z0-9\-_.~%]+)')/, |
| 56 | + '' |
| 57 | + ) |
| 58 | + bad_characters.length.zero? |
| 59 | + end |
| 60 | + |
| 61 | + def validate_condition_topics?(condition) |
| 62 | + topics = condition.scan(/(?:^|\S|\s)'([^']*?)'(?:$|\S|\s)/).flatten |
| 63 | + topics.all? { |topic| topic.gsub(/[a-zA-Z0-9\-_.~%]+/, '').length.zero? } |
| 64 | + end |
| 65 | + end |
| 66 | + end |
| 67 | +end |
0 commit comments