// 推播訊息的Json格式範例
        //{
        //    "multicast_id": 7707128547180318330,
        //    "success": 0,
        //    "failure": 1,
        //    "canonical_ids": 0,
        //    "results": [
        //        {
        //            "error": "NotRegistered"
        //        }
        //    ]
        //}

        public void Awake()
        {
            const string credentialFileName = "serviceAccountKey.json";

            // 讀取憑證文件並產生憑證物件
            GoogleCredential googleCredential = null;

            string[] paths = new string[]
            {
                Path.Combine("..", "Config", "Key", credentialFileName),
                Path.Combine("..", "..", "Config", "Key", credentialFileName)
            };
            string path = paths.FirstOrDefault(e => File.Exists(e));

            if (string.IsNullOrEmpty(path))
            {
                Log.Error($"GoogleCredential 's serviceAccountKey.json doesnt exist on the path!");
                return;
            }
            else
            {
                googleCredential = GoogleCredential.FromFile(path);
            }

            // 產生FirebaseApp實體
            firebaseApp = FirebaseApp.Create(new AppOptions()
            {
                Credential = googleCredential,
            });

            // 產生FirebaseMessaging實體
            firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);

            firebaseAuth = FirebaseAuth.GetAuth(firebaseApp);
        }
        public async Task GetMessagingWithClientFactory()
        {
            var handler = new MockMessageHandler()
            {
                Response = new FirebaseMessagingClient.SingleMessageResponse()
                {
                    Name = "test-response",
                },
            };
            var factory = new MockHttpClientFactory(handler);

            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential        = GoogleCredential.FromAccessToken("test-token"),
                HttpClientFactory = factory,
                ProjectId         = "test-project",
            });
            FirebaseMessaging messaging = FirebaseMessaging.GetMessaging(app);

            Assert.NotNull(messaging);
            Assert.Same(messaging, FirebaseMessaging.GetMessaging(app));

            var response = await messaging.SendAsync(new Message()
            {
                Topic = "test-topic"
            });

            Assert.Equal("test-response", response);
            app.Delete();
        }
示例#3
0
        public FirebaseMessaging GetMessaging(App app)
        {
            var messaging = memoryCache.GetOrCreate(app.FirebaseProject, entry =>
            {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);

                var firebaseApp = FirebaseApp.GetInstance(app.Id);

                if (firebaseApp == null)
                {
                    var appOptions = new AppOptions
                    {
                        Credential = GoogleCredential.FromJson(app.FirebaseCredential)
                    };

                    appOptions.ProjectId = app.FirebaseProject;

                    firebaseApp = FirebaseApp.Create(appOptions);
                }

                entry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration
                {
                    EvictionCallback = (key, value, reason, state) =>
                    {
                        firebaseApp.Delete();
                    }
                });

                return(FirebaseMessaging.GetMessaging(firebaseApp));
            });

            return(messaging);
        }
示例#4
0
        private async Task SendPushNotificationMessages(List <string> tokens, string title, string body, Dictionary <string, string> data, CancellationToken cancellationToken)
        {
            int tokenCount = tokens.Count <= 100 ? tokens.Count : 100;

            if (tokenCount == 0)
            {
                return;
            }

            MulticastMessage message = new MulticastMessage
            {
                Tokens       = tokens.Take(tokenCount).ToList(),
                Notification = new Notification
                {
                    Title = title,
                    Body  = body,
                },
                Data = data,
            };

            BatchResponse response = await FirebaseMessaging.GetMessaging(_firebaseApp)
                                     .SendMulticastAsync(message, cancellationToken);

            // TODO: handle response

            if (tokens.Count > 100)
            {
                await SendPushNotificationMessages(tokens.Skip(100).ToList(), title, body, data, cancellationToken);
            }
        }
示例#5
0
        public virtual async Task <string> SendNotification(List <string> clientToken, string title, string body)
        {
            var registrationTokens = clientToken;
            var message            = new MulticastMessage()
            {
                Tokens = registrationTokens,
                Data   = new Dictionary <string, string>()
                {
                    { "title", title },
                    { "body", body },
                },
            };
            var firebaseApp = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(path_to_private_key),
            }, "My_Sexy_App");
            //FirebaseMessaging.GetMessaging(firebaseApp);
            //var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message).ConfigureAwait(true);
            var response = await FirebaseMessaging.GetMessaging(firebaseApp).SendMulticastAsync(message).ConfigureAwait(true);

            var nresp    = response.FailureCount + response.SuccessCount;
            var eachResp = response.Responses;

            return("");
        }
示例#6
0
        public async Task <ActionResult> SendCustomNotifiation([FromBody] NotificationModel notificationModel)
        {
            try
            {
                Message message = new Message()
                {
                    Notification = new Notification
                    {
                        Title = notificationModel.Title,
                        Body  = notificationModel.Message
                    },
                    Token = notificationModel.Token
                };

                FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;
                string            result    = await messaging.SendAsync(message);

                Console.WriteLine(result);
                return(Ok());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(BadRequest());
            }
        }
        public static void SendAsync(string title, string body, ExecutionContext context)
        {
            var accountSettingsFile = Path.Combine(context.FunctionDirectory, "..\\ai-alerts-firebase-adminsdk.json");
            var appOptions          = new AppOptions()
            {
                Credential = GoogleCredential.FromFile(accountSettingsFile)
            };

            FirebaseApp firebaseApp;

            if (FirebaseApp.DefaultInstance == null)
            {
                firebaseApp = FirebaseApp.Create(appOptions);
            }
            else
            {
                firebaseApp = FirebaseApp.DefaultInstance;
            }

            var firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);

            var message = new Message
            {
                Topic        = "All",
                Notification = new Notification
                {
                    Title = title,
                    Body  = body,
                }
            };

            firebaseMessaging.SendAsync(message);
        }
        public async Task UnsubscribeWithClientFactory()
        {
            var handler = new MockMessageHandler()
            {
                Response = @"{""results"":[{}]}",
            };
            var factory = new MockHttpClientFactory(handler);

            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential        = GoogleCredential.FromAccessToken("test-token"),
                HttpClientFactory = factory,
                ProjectId         = "test-project",
            });
            FirebaseMessaging messaging = FirebaseMessaging.GetMessaging(app);

            Assert.NotNull(messaging);
            Assert.Same(messaging, FirebaseMessaging.GetMessaging(app));

            var response = await messaging.UnsubscribeFromTopicAsync("test-topic", new List <string> {
                "test-token"
            });

            Assert.Equal(0, response.FailureCount);
            Assert.Equal(1, response.SuccessCount);
            app.Delete();
        }
示例#9
0
        public async void Post()
        {
            var app = fireBaseAppProvider.Get();
            var firebaseMessaging = FirebaseMessaging.GetMessaging(app);

            var to = mobileDevicesService.GetAll().ToList();

            logger.LogInformation("Sending to {0} devices", to.Count);

            var message = new MulticastMessage
            {
                Notification = new Notification
                {
                    Title = "Hello from api",
                    Body  = "Test message"
                },
                Android = new AndroidConfig
                {
                    TimeToLive = TimeSpan.FromMinutes(1)
                },
                Tokens = to
            };


            var result = await firebaseMessaging.SendMulticastAsync(message);

            logger.LogInformation("responce: {0}", JsonConvert.SerializeObject(result));
        }
        public async Task <bool> SendAsync(Notification notification, App app, Token token)
        {
            // creating message
            var message = new Message
            {
                Notification = new FirebaseAdmin.Messaging.Notification
                {
                    Title = notification.Title,
                    Body  = notification.Message
                },
                Token = token.TokenString
            };

            // sending message
            try
            {
                var fireBaseApp = FirebaseApp.Create(new AppOptions
                {
                    Credential = GoogleCredential.FromJson(app.Json)
                }, app.Name);
                var response = await FirebaseMessaging.GetMessaging(fireBaseApp).SendAsync(message);

                logger.LogInformation("Message sent to FireBase with result: {}", response);
                logger.LogInformation("FIREBASE_NOTIFICATION_SUCCESS");
                return(true);
            }
            catch (FirebaseException)
            {
                logger.LogError("Message failed with FireBase exception token: {}", token.TokenString);
                logger.LogInformation("FIREBASE_NOTIFICATION_ERROR");
                return(false);
            }
        }
示例#11
0
        // 新版接口
        public async Task <IActionResult> V1()
        {
            var deviceId    = "fQVPgfq8TZKrltAwHSB-WI:APA91bFWh5E5PKp_8fdjlkkeE7K6xjoA9CH9Dll-nJBvPwnKDcsNnH2Py5Gf5T7SMna4X0D35_tA8a32ytB29nApEei4Kx78pIsk7md6xfBh-_JffilmRZQSR179e2pc8pbZs4T78ocp";
            var firebaseApp = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("seekit24-69d2d-firebase-adminsdk-2mq43-30c9335ed4.json"),
            }, Guid.NewGuid().ToString());

            var messaging = FirebaseMessaging.GetMessaging(firebaseApp);

            var msg = new Message
            {
                Token   = deviceId,
                Android = new AndroidConfig
                {
                    Priority = Priority.High,
                },
                Notification = new Notification
                {
                    Title = "通知",
                    Body  = "安卓测试消息 🆚",
                },
                Data = new Dictionary <string, string> {
                    { "sss", "asdf" },
                    { "sss2", "asdf2" }
                }
            };
            await messaging.SendAsync(msg);

            return(Content("tui wan"));
        }
示例#12
0
 public FirebaseService(string ouremail, string pass, IUserManagementService userManagementService)
 {
     Config();
     _messaging            = FirebaseMessaging.GetMessaging(_defaultApp);
     OurEmail              = ouremail;
     Password              = pass;
     UserManagementService = userManagementService;
 }
 public PushNotificationSender(ILogger <PushNotificationSender> logger,
                               FirebaseMessaging firebaseMessaging,
                               MulticastMessageFactory messageFactory)
 {
     _logger            = logger;
     _firebaseMessaging = firebaseMessaging;
     _messageFactory    = messageFactory;
 }
示例#14
0
 public FirebaseControl()
 {
     FirebaseApp = FirebaseApp.Create(new AppOptions()
     {
         Credential = GoogleCredential.FromFile("FirebaseCredential.json"),
     });
     Messaging = FirebaseMessaging.GetMessaging(FirebaseApp);
 }
示例#15
0
        public static Android.Gms.Tasks.Task SubscribeToTopic(this FirebaseMessaging fb, string platform, YawsNotification.Topic topic)
        {
#if DEBUG
            var fbTopic = $"Debug-{platform}-{topic}";
#else
            var fbTopic = $"{platform}-{topic}";
#endif
            return(fb.SubscribeToTopic(fbTopic));
        }
示例#16
0
        public FirebaseCloudMessageService(IOptions <FirebaseCredential> firebaseCredential)
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromJson(JsonSerializer.Serialize(firebaseCredential.Value))
            });

            _firebaseService = FirebaseMessaging.DefaultInstance;
        }
示例#17
0
        public Notification()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(Path).CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });

            messaging = FirebaseMessaging.GetMessaging(app);
        }
示例#18
0
        public MobileMessagingService()
        {
            FirebaseApp app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("cheeseit-firebase-adminsdk.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging"),
            });

            messaging = FirebaseMessaging.GetMessaging(app);
        }
示例#19
0
 public void SubscribeTopic(string topic, Action <Task> task = null)
 {
     if (!m_IsInit)
     {
         return;
     }
     FirebaseMessaging.SubscribeAsync(topic).ContinueWith(task);
     Log.i("Register topic Success");
 }
示例#20
0
        /*
         * Refer this
         * https://firebase.google.com/docs/admin/setup/#windows
         */
        public PushController(UserContext userContext, IDtsBusinessAccess dtsBusinessAccess)
        {
            this.userContext = userContext;

            app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(ConfigSettings.Instance.FileSettings.GoogleFirebaseFile).CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });
            messaging = FirebaseMessaging.GetMessaging(app);
        }
示例#21
0
        public MobileMessagingClient()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("fir-app-659c6-firebase-adminsdk-sjxdp-6e5e08c5d4.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });

            messaging = FirebaseMessaging.GetMessaging(app);
            messaging = FirebaseMessaging.GetMessaging(app);
        }
示例#22
0
 public override void OnTokenRefresh()
 {
     if (FirebaseInstanceId.Instance.Token != null)
     {
         var refreshedToken = FirebaseInstanceId.Instance.Token;
         Android.Util.Log.Debug("TAG", "Refreshed token: " + refreshedToken);
         FirebaseMessaging fcm = FirebaseMessaging.Instance;
         fcm.SubscribeToTopic("Aditya");
     }
 }
        public MobileMessagingClient()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential
                             .FromFile("../Versus.Messaging/Credentials/serviceAccountKey.json")
                             .CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });

            _messaging = FirebaseMessaging.GetMessaging(app);
        }
示例#24
0
    // Use this for initialization
    void Start()
    {
        //PlayerSettings.statusBarHidden = false;
        Screen.fullScreen = false;

        if (!PlayerPrefs.HasKey("isPush"))
        {
            FirebaseMessaging.Subscribe("Notification");
            PlayerPrefs.SetInt("isPush", 1);
        }
    }
示例#25
0
        /// <summary>
        /// Sends notification to a person
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SendNotificationToPersonAsync(SendNotificationToPersonInput input)
        {
            var validationResults = new List <ValidationResult>();

            Person person = null;

            if (input.PersonId == Guid.Empty)
            {
                validationResults.Add(new ValidationResult($"'{nameof(input.PersonId)}' is mandatory"));
            }
            else
            {
                person = await _personRepository.GetAll().Where(p => p.Id == input.PersonId).FirstOrDefaultAsync();

                if (person == null)
                {
                    validationResults.Add(new ValidationResult("Person not found"));
                }
            }

            if (validationResults.Any())
            {
                throw new AbpValidationException("Failed to send message", validationResults);
            }

            var app       = _firebaseApplicationProvider.GetApplication();
            var messaging = FirebaseMessaging.GetMessaging(app);

            var devices = await _deviceRepository.GetAll().Where(d => d.Person == person).ToListAsync();

            foreach (var device in devices)
            {
                try
                {
                    var message = new Message()
                    {
                        Token        = device.DeviceRegistrationId,
                        Notification = new FirebaseAdmin.Messaging.Notification()
                        {
                            Body  = input.Body,
                            Title = input.Title
                        },
                        Data = input.Data
                    };

                    await messaging.SendAsync(message);
                }
                catch (FirebaseMessagingException e)
                {
                    //
                }
            }
        }
示例#26
0
        public PushNotification(FirebaseConfiguration firebaseConfiguration, FirebaseMessaging firebaseMessaging)
        {
            _firebaseConfiguration = firebaseConfiguration;

            FirebaseApp app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("cashflow-firebase-adminsdk.json")
                             .CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });

            _firebaseMessaging = FirebaseMessaging.GetMessaging(app);
        }
示例#27
0
        public async Task <String> SendNotification(string token, string title, string body)
        {
            FirebaseMessaging messaging;
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(AppDomain.CurrentDomain.BaseDirectory + "/Json/niovarjobsnotifications-firebase-adminsdk.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });

            messaging = FirebaseMessaging.GetMessaging(app);
            return(await messaging.SendAsync(CreateNotification(title, body, token)));

            //do something with result
        }
示例#28
0
        public FirebaseService(IOptions <Configuration.FcmOptions> options)
        {
            string path = options.Value.ServiceAccountFilePath;

            if (!string.IsNullOrWhiteSpace(path))
            {
                FirebaseApp app = FirebaseApp.Create(new AppOptions
                {
                    Credential = GoogleCredential.FromFile(path)
                });
                messaging = FirebaseMessaging.GetMessaging(app);
            }
        }
        public void GetDefaultMessaging()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = MockCredential
            });
            FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;

            Assert.NotNull(messaging);
            Assert.Same(messaging, FirebaseMessaging.DefaultInstance);
            app.Delete();
            Assert.Null(FirebaseMessaging.DefaultInstance);
        }
        public void GetMessaging()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = MockCredential
            }, "MyApp");
            FirebaseMessaging messaging = FirebaseMessaging.GetMessaging(app);

            Assert.NotNull(messaging);
            Assert.Same(messaging, FirebaseMessaging.GetMessaging(app));
            app.Delete();
            Assert.Throws <InvalidOperationException>(() => FirebaseMessaging.GetMessaging(app));
        }