// 推播訊息的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);
        }
Esempio n. 2
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("");
        }
Esempio n. 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);
        }
Esempio n. 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);
            }
        }
        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();
        }
Esempio n. 6
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);
            }
        }
Esempio n. 8
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"));
        }
        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();
        }
Esempio n. 11
0
 public FirebaseService(string ouremail, string pass, IUserManagementService userManagementService)
 {
     Config();
     _messaging            = FirebaseMessaging.GetMessaging(_defaultApp);
     OurEmail              = ouremail;
     Password              = pass;
     UserManagementService = userManagementService;
 }
Esempio n. 12
0
 public FirebaseControl()
 {
     FirebaseApp = FirebaseApp.Create(new AppOptions()
     {
         Credential = GoogleCredential.FromFile("FirebaseCredential.json"),
     });
     Messaging = FirebaseMessaging.GetMessaging(FirebaseApp);
 }
Esempio n. 13
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);
        }
Esempio n. 14
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);
        }
Esempio n. 15
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);
        }
Esempio n. 16
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);
        }
        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);
        }
Esempio n. 18
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);
        }
Esempio n. 19
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)
                {
                    //
                }
            }
        }
Esempio n. 20
0
        public FirebaseMessagingWrapper(string projectId, string credentials)
        {
            var appOptions = new AppOptions
            {
                Credential = GoogleCredential.FromJson(credentials)
            };

            appOptions.ProjectId = projectId;

            app = FirebaseApp.Create(appOptions, Guid.NewGuid().ToString());

            Messaging = FirebaseMessaging.GetMessaging(app);
        }
Esempio n. 21
0
        internal static void AddPushNotificationService(this IServiceCollection services)
        {
            var appFB = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FireBaseCredentials.json"))
            });

            var msgServiceFB = FirebaseMessaging.GetMessaging(appFB);

            services.AddScoped <IPushNotificationService>(cfg => new PushNotificationService {
                messagingFB = msgServiceFB
            });
        }
Esempio n. 22
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
        }
        private FirebaseMessagingClient()
        {
            var path = Directory.GetCurrentDirectory();

            var credential = GoogleCredential.FromFile(Directory.GetCurrentDirectory() + "/serviceAccountKey.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
            //var credential = GoogleCredential.FromFile("serviceAccountKey.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging");
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = credential
            });

            firebaseMessaging = FirebaseMessaging.GetMessaging(app);
        }
Esempio n. 24
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 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));
        }
Esempio n. 26
0
        private static void AddFirebaseMessagingServices(IServiceCollection services,
                                                         string credential)
        {
            var firebaseApp = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(credential).CreateScoped(FirebaseConstants.FirebaseUrl)
            });

            services.AddTransient(sp =>
            {
                var firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);
                return(new FirebaseMessagingService(firebaseMessaging,
                                                    sp.GetRequiredService <ILogger <FirebaseMessagingService> >()));
            });
        }
Esempio n. 27
0
        public async Task SendMessage(string plate)
        {
            var messaging = FirebaseMessaging.GetMessaging(this.app);

            var message = new Message()
            {
                Notification = new Notification
                {
                    Title = "Someone's at the gate",
                    Body  = plate
                },
                Topic = "news"
            };

            await messaging.SendAsync(message);
        }
        public async Task SendSuspiciousAddressesToMobileClient(List <Address> addresses)
        {
            Console.WriteLine("SendSuspiciousAddressesToMobileClient");
            FirebaseMessaging firebaseMessaging = FirebaseMessaging.GetMessaging(FirebaseApp.DefaultInstance);
            var response = await firebaseMessaging.SendAsync(new Message()
            {
                Topic        = "Suspicious",
                Notification = new Notification()
                {
                    Title = "Suspicious",
                    Body  = JsonSerializer.Serialize(addresses)
                }
            });

            Console.WriteLine(response);
        }
Esempio n. 29
0
        /// <summary>
        /// Send notification to topic
        /// </summary>
        /// <param name="input"></param>
        /// <returns>response from the Firebase API</returns>
        public async Task <string> SendNotificationToTopic(SendNotificationToTopicInput input)
        {
            var message = new Message()
            {
                Topic        = input.Topic,
                Notification = new FirebaseAdmin.Messaging.Notification()
                {
                    Body  = input.Body,
                    Title = input.Title
                },
                Data = input.Data
            };

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

            return(await messaging.SendAsync(message));
        }
Esempio n. 30
0
        //private async Task<IActionResult> SendNotification(List<ReminderNotificationResponseModel> reminders)
        //{
        //    int count = 0;
        //    bool status = false;
        //    string message;
        //    string serverKey = _configuration["Firebase:Server_Key"];
        //    string senderId = _configuration["Firebase:SenderId"];
        //    string fcmLink = "https://fcm.googleapis.com/fcm/send";


        //    foreach (ReminderNotificationResponseModel reminder in reminders)
        //    {
        //        var notificationData = new NotificationModel()
        //        {
        //            Notification = new NoteModel()
        //            {
        //                Title = reminder.Title,
        //                Body = reminder.Desciption
        //            },
        //            To = reminder.Token
        //        };


        //        //var httpWebRequest = (HttpWebRequest)WebRequest.Create(fcmLink);
        //        //httpWebRequest.ContentType = "application/json";
        //        //httpWebRequest.Headers.Add(string.Format("Authorization: Key={0}", serverKey));
        //        //httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        //        //httpWebRequest.Method = "POST";


        //        //var json = JsonConvert.SerializeObject(notificationData);
        //        //var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

        //        //var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        //        //string jsonMessage = JsonConvert.SerializeObject(notificationData);
        //        //var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, fcmLink);

        //        //request.Headers.TryAddWithoutValidation("Authorization", "key=" + serverKey);
        //        //request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");

        //        //HttpResponseMessage result;

        //        //using(var client = new HttpClient())
        //        //{
        //        //    result = await client.SendAsync(request);
        //        //}

        //        using (var client = new HttpClient())
        //        {

        //            //    client.BaseAddress = new Uri("https://fcm.googleapis.com/");
        //            //    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        //            //    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={serverKey}");
        //            //    client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={senderId}");

        //            //    var json = JsonConvert.SerializeObject(notificationData);
        //            //    var httpContent = new StringContent(json, Encoding.UTF8, "application/json");


        //            var request = new HttpRequestMessage
        //            {
        //                RequestUri = new Uri("https://fcm.googleapis.com/fcm/send"),
        //                Method = System.Net.Http.HttpMethod.Post,
        //                Headers =
        //                {
        //                    { HttpRequestHeader.Authorization.ToString(), "Key="+serverKey },
        //                    { HttpRequestHeader.ContentType.ToString(), "application/json" }
        //                },
        //                Content = new StringContent(JsonConvert.SerializeObject(notificationData))
        //            };

        //            //request.Headers.Add("Content-Type", "application/json");
        //            //request.Headers.TryAddWithoutValidation("Authorization", _configuration["Firebase:Server_Key"]);

        //            HttpResponseMessage httpResponse = await client.SendAsync(request);

        //            if (httpResponse.IsSuccessStatusCode)
        //                count++;
        //        }

        //    }

        //    if (count == reminders.Count)
        //    {
        //        status = true;
        //        message = "Reminder Notification Send Successfully";
        //        return Ok(new { status, message });
        //    }
        //    else
        //    {
        //        message = "Unable to Send Notification";
        //        return Ok(new { status, message });
        //    }

        //}


        /// <summary>
        /// It Notify the user of upcoming note reminder
        /// </summary>
        /// <param name="reminders">contains all data to send notification</param>
        /// <returns></returns>
        private async Task <int> FirebaseNotification(List <ReminderNotificationResponseModel> reminders)
        {
            string result;
            int    count = 0;

            var path = _environment.ContentRootPath;

            path += "\\firebase.json";

            FirebaseApp app;

            try
            {
                app = FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.FromFile(path)
                }, "FundooNotes");
            }
            catch
            {
                app = FirebaseApp.GetInstance("FundooNotes");
            }

            var fcm = FirebaseMessaging.GetMessaging(app);

            foreach (ReminderNotificationResponseModel reminder in reminders)
            {
                Message message = new Message()
                {
                    Notification = new Notification
                    {
                        Title = reminder.Title,
                        Body  = reminder.Desciption
                    },
                    Token = reminder.Token
                };

                result = await fcm.SendAsync(message);

                count++;
            }

            return(count);
        }