Esempio n. 1
0
        void send(GcmNotification msg, string senderAuthToken, string senderID, string applicationID)
        {
            var result = new GcmMessageTransportResponse();

            result.Message = msg;

            var postData = msg.GetJson();

            var webReq = (HttpWebRequest)WebRequest.Create(GCM_SEND_URL);

            //webReq.ContentLength = postData.Length;
            webReq.Method      = "POST";
            webReq.ContentType = "application/json";
            //webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8   can be used for plaintext bodies
            webReq.UserAgent = "PushSharp (version: 1.0)";
            webReq.Headers.Add("Authorization: key=" + senderAuthToken);

            webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters()
            {
                WebRequest      = webReq,
                WebResponse     = null,
                Message         = msg,
                SenderAuthToken = senderAuthToken,
                SenderId        = senderID,
                ApplicationId   = applicationID
            });
        }
Esempio n. 2
0
        public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback)
        {
            var msg = notification as GcmNotification;

            var result = new GcmMessageTransportResponse();

            result.Message = msg;

            //var postData = msg.GetJson();

            var webReq = (HttpWebRequest)WebRequest.Create(gcmSettings.GcmUrl);

            //webReq.ContentLength = postData.Length;
            webReq.Method      = "POST";
            webReq.ContentType = "application/json";
            //webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8   can be used for plaintext bodies
            webReq.UserAgent = "PushSharp (version: " + assemblyVerison.ToString() + ")";
            webReq.Headers.Add("Authorization: key=" + gcmSettings.SenderAuthToken);

            webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters()
            {
                Callback        = callback,
                WebRequest      = webReq,
                WebResponse     = null,
                Message         = msg,
                SenderAuthToken = gcmSettings.SenderAuthToken,
                SenderId        = gcmSettings.SenderID,
                ApplicationId   = gcmSettings.ApplicationIdPackageName
            });
        }
Esempio n. 3
0
		public void SendNotification(INotification notification, SendNotificationCallbackDelegate callback)
		{
            Interlocked.Increment(ref waitCounter);

			var msg = notification as GcmNotification;

			var result = new GcmMessageTransportResponse();
			result.Message = msg;
						
			//var postData = msg.GetJson();

			var webReq = (HttpWebRequest)WebRequest.Create(gcmSettings.GcmUrl);
			//webReq.ContentLength = postData.Length;
			webReq.Method = "POST";
			webReq.ContentType = "application/json";
			//webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8   can be used for plaintext bodies
			webReq.UserAgent = "PushSharp (version: " + assemblyVerison.ToString () + ")";
			webReq.Headers.Add("Authorization: key=" + gcmSettings.SenderAuthToken);

			webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters()
			{
				Callback = callback,
				WebRequest = webReq,
				WebResponse = null,
				Message = msg,
				SenderAuthToken = gcmSettings.SenderAuthToken,
				SenderId = gcmSettings.SenderID,
				ApplicationId = gcmSettings.ApplicationIdPackageName
			});
		}
Esempio n. 4
0
        void processResponseError(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse();

            result.ResponseCode = GcmMessageTransportResponseCode.Error;

            if (asyncParam.WebResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                //401 bad auth token
                result.ResponseCode = GcmMessageTransportResponseCode.InvalidAuthToken;
                throw new GcmAuthenticationErrorTransportException(result);
            }
            else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                result.ResponseCode = GcmMessageTransportResponseCode.BadRequest;
                throw new GcmBadRequestTransportException(result);
            }
            else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.InternalServerError)
            {
                result.ResponseCode = GcmMessageTransportResponseCode.InternalServiceError;
                throw new GcmMessageTransportException("Internal Service Error", result);
            }
            else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                //First try grabbing the retry-after header and parsing it.
                TimeSpan retryAfter = new TimeSpan(0, 0, 120);

                var wrRetryAfter = asyncParam.WebResponse.GetResponseHeader("Retry-After");

                if (!string.IsNullOrEmpty(wrRetryAfter))
                {
                    DateTime wrRetryAfterDate = DateTime.UtcNow;

                    if (DateTime.TryParse(wrRetryAfter, out wrRetryAfterDate))
                    {
                        retryAfter = wrRetryAfterDate - DateTime.UtcNow;
                    }
                    else
                    {
                        int wrRetryAfterSeconds = 120;
                        if (int.TryParse(wrRetryAfter, out wrRetryAfterSeconds))
                        {
                            retryAfter = new TimeSpan(0, 0, wrRetryAfterSeconds);
                        }
                    }
                }

                //503 exponential backoff, get retry-after header
                result.ResponseCode = GcmMessageTransportResponseCode.ServiceUnavailable;

                throw new GcmServiceUnavailableTransportException(retryAfter, result);
            }

            asyncParam.WebResponse.Close();

            throw new GcmMessageTransportException("Unknown Transport Error", result);
        }
Esempio n. 5
0
		public static GcmNotification ForSingleResult(GcmMessageTransportResponse response, int resultIndex)
		{
			var result = new GcmNotification();
			result.Tag = response.Message.Tag;
			result.RegistrationIds.Add(response.Message.RegistrationIds[resultIndex]);
			result.CollapseKey = response.Message.CollapseKey;
			result.JsonData = response.Message.JsonData;
			result.DelayWhileIdle = response.Message.DelayWhileIdle;
			return result;
		}
        void processResponseError(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse();
            result.ResponseCode = GcmMessageTransportResponseCode.Error;

            if (asyncParam == null || asyncParam.WebResponse == null)
                throw new GcmMessageTransportException("Unknown Transport Error", result);

            if (asyncParam.WebResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                //401 bad auth token
                result.ResponseCode = GcmMessageTransportResponseCode.InvalidAuthToken;
                throw new GcmAuthenticationErrorTransportException(result);
            }
            else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                result.ResponseCode = GcmMessageTransportResponseCode.BadRequest;
                throw new GcmBadRequestTransportException(result);
            }
            else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.InternalServerError)
            {
                result.ResponseCode = GcmMessageTransportResponseCode.InternalServiceError;
                throw new GcmMessageTransportException("Internal Service Error", result);
            }
            else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                //First try grabbing the retry-after header and parsing it.
                TimeSpan retryAfter = new TimeSpan(0, 0, 120);

                var wrRetryAfter = asyncParam.WebResponse.GetResponseHeader("Retry-After");

                if (!string.IsNullOrEmpty(wrRetryAfter))
                {
                    DateTime wrRetryAfterDate = DateTime.UtcNow;

                    if (DateTime.TryParse(wrRetryAfter, out wrRetryAfterDate))
                        retryAfter = wrRetryAfterDate - DateTime.UtcNow;
                    else
                    {
                        int wrRetryAfterSeconds = 120;
                        if (int.TryParse(wrRetryAfter, out wrRetryAfterSeconds))
                            retryAfter = new TimeSpan(0, 0, wrRetryAfterSeconds);
                    }
                }

                //503 exponential backoff, get retry-after header
                result.ResponseCode = GcmMessageTransportResponseCode.ServiceUnavailable;

                throw new GcmServiceUnavailableTransportException(retryAfter, result);
            }

            asyncParam.WebResponse.Close();

            throw new GcmMessageTransportException("Unknown Transport Error", result);
        }
Esempio n. 7
0
        public static GcmNotification ForSingleResult(GcmMessageTransportResponse response, int resultIndex)
        {
            var result = new GcmNotification();

            result.Tag = response.Message.Tag;
            result.RegistrationIds.Add(response.Message.RegistrationIds[resultIndex]);
            result.CollapseKey    = response.Message.CollapseKey;
            result.JsonData       = response.Message.JsonData;
            result.DelayWhileIdle = response.Message.DelayWhileIdle;
            return(result);
        }
Esempio n. 8
0
        void transport_MessageResponseReceived(GcmMessageTransportResponse response)
        {
            int index = 0;

            //Loop through every result in the response
            // We will raise events for each individual result so that the consumer of the library
            // can deal with individual registrationid's for the notification
            foreach (var r in response.Results)
            {
                var singleResultNotification = GcmNotification.ForSingleResult(response, index);

                if (r.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                {
                    //It worked! Raise success
                    this.Events.RaiseNotificationSent(singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.CanonicalRegistrationId)
                {
                    //Swap Registrations Id's
                    var newRegistrationId = r.CanonicalRegistrationId;

                    this.Events.RaiseDeviceSubscriptionIdChanged(PlatformType.AndroidGcm, singleResultNotification.RegistrationIds[0], newRegistrationId, singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.Unavailable)
                {
                    this.QueueNotification(singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.NotRegistered)
                {
                    //Raise failure and device expired
                    this.Events.RaiseDeviceSubscriptionExpired(PlatformType.AndroidGcm, singleResultNotification.RegistrationIds[0], singleResultNotification);
                }
                else
                {
                    //Raise failure, for unknown reason
                    this.Events.RaiseNotificationSendFailure(singleResultNotification, new GcmMessageTransportException(r.ResponseStatus.ToString(), response));
                }

                index++;

                //decrement pending results.
                Interlocked.Decrement(ref PendingNotificationsResult);
            }

            Interlocked.Decrement(ref waitCounter);
        }
Esempio n. 9
0
        void transport_MessageResponseReceived(GcmMessageTransportResponse response)
        {
            int index = 0;

            //Loop through every result in the response
            // We will raise events for each individual result so that the consumer of the library
            // can deal with individual registrationid's for the notification
            foreach (var r in response.Results)
            {
                var singleResultNotification = GcmNotification.ForSingleResult(response, index);

                if (r.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                {
                    //It worked! Raise success
                    this.Events.RaiseNotificationSent(singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.CanonicalRegistrationId)
                {
                    //Swap Registrations Id's
                    var newRegistrationId = r.CanonicalRegistrationId;

                    this.Events.RaiseDeviceSubscriptionIdChanged(PlatformType.AndroidGcm, singleResultNotification.RegistrationIds[0], newRegistrationId, singleResultNotification);

                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.Unavailable)
                {
                    this.QueueNotification(singleResultNotification);
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.NotRegistered)
                {
                    //Raise failure and device expired
                    this.Events.RaiseDeviceSubscriptionExpired(PlatformType.AndroidGcm, singleResultNotification.RegistrationIds[0], singleResultNotification);
                }
                else
                {
                    //Raise failure, for unknown reason
                    this.Events.RaiseNotificationSendFailure(singleResultNotification, new GcmMessageTransportException(r.ResponseStatus.ToString(), response));
                }

                index++;
            }

            Interlocked.Decrement(ref waitCounter);
        }
Esempio n. 10
0
 public GcmServiceUnavailableTransportException(TimeSpan retryAfter, GcmMessageTransportResponse response)
     : base("Service Temporarily Unavailable.  Please wait the retryAfter amount and implement an Exponential Backoff", response)
 {
     this.RetryAfter = retryAfter;
 }
Esempio n. 11
0
        void processResponseOk(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse()
            {
                ResponseCode = GcmMessageTransportResponseCode.Ok,
                Message      = asyncParam.Message
            };

            //Get the response body
            var json = new JObject();

            var str = string.Empty;

            try { str = (new StreamReader(asyncParam.WebResponse.GetResponseStream())).ReadToEnd(); }
            catch { }

            try { json = JObject.Parse(str); }
            catch { }

            result.NumberOfCanonicalIds = json.Value <long>("canonical_ids");
            result.NumberOfFailures     = json.Value <long>("failure");
            result.NumberOfSuccesses    = json.Value <long>("success");

            var jsonResults = json["results"] as JArray;

            if (jsonResults == null)
            {
                jsonResults = new JArray();
            }

            foreach (var r in jsonResults)
            {
                var msgResult = new GcmMessageResult();

                msgResult.MessageId = r.Value <string>("message_id");
                msgResult.CanonicalRegistrationId = r.Value <string>("registration_id");
                msgResult.ResponseStatus          = GcmMessageTransportResponseStatus.Ok;

                if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
                {
                    msgResult.ResponseStatus = GcmMessageTransportResponseStatus.CanonicalRegistrationId;
                }
                else if (r["error"] != null)
                {
                    var err = r.Value <string>("error") ?? "";

                    switch (err.ToLower().Trim())
                    {
                    case "ok":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Ok;
                        break;

                    case "missingregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MissingRegistrationId;
                        break;

                    case "unavailable":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Unavailable;
                        break;

                    case "notregistered":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered;
                        break;

                    case "invalidregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration;
                        break;

                    case "mismatchsenderid":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MismatchSenderId;
                        break;

                    case "messagetoobig":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MessageTooBig;
                        break;

                    case "invaliddatakey":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidDataKey;
                        break;

                    case "invalidttl":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidTtl;
                        break;

                    case "internalservererror":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InternalServerError;
                        break;

                    default:
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Error;
                        break;
                    }
                }

                result.Results.Add(msgResult);
            }

            asyncParam.WebResponse.Close();

            int index = 0;

            var response = result;

            //Loop through every result in the response
            // We will raise events for each individual result so that the consumer of the library
            // can deal with individual registrationid's for the notification
            foreach (var r in response.Results)
            {
                var singleResultNotification = GcmNotification.ForSingleResult(response, index);

                if (r.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                {
                    //It worked! Raise success
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification));
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.CanonicalRegistrationId)
                {
                    //Swap Registrations Id's
                    var newRegistrationId = r.CanonicalRegistrationId;
                    var oldRegistrationId = string.Empty;

                    if (singleResultNotification.RegistrationIds != null && singleResultNotification.RegistrationIds.Count > 0)
                    {
                        oldRegistrationId = singleResultNotification.RegistrationIds[0];
                    }

                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new DeviceSubscriptonExpiredException())
                    {
                        OldSubscriptionId = oldRegistrationId, NewSubscriptionId = newRegistrationId, IsSubscriptionExpired = true
                    });
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.Unavailable)
                {
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, true, new Exception("Unavailable Response Status")));
                }
                else if (r.ResponseStatus == GcmMessageTransportResponseStatus.NotRegistered)
                {
                    var oldRegistrationId = string.Empty;

                    if (singleResultNotification.RegistrationIds != null && singleResultNotification.RegistrationIds.Count > 0)
                    {
                        oldRegistrationId = singleResultNotification.RegistrationIds[0];
                    }

                    //Raise failure and device expired
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new DeviceSubscriptonExpiredException())
                    {
                        OldSubscriptionId = oldRegistrationId, IsSubscriptionExpired = true, SubscriptionExpiryUtc = DateTime.UtcNow
                    });
                }
                else
                {
                    //Raise failure, for unknown reason
                    asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new GcmMessageTransportException(r.ResponseStatus.ToString(), response)));
                }

                index++;
            }

            Interlocked.Decrement(ref waitCounter);
        }
        void send(GcmNotification msg, string senderAuthToken, string senderID, string applicationID)
        {
            var result = new GcmMessageTransportResponse();
            result.Message = msg;

            var postData = msg.GetJson();

            var webReq = (HttpWebRequest)WebRequest.Create(GCM_SEND_URL);
            //webReq.ContentLength = postData.Length;
            webReq.Method = "POST";
            webReq.ContentType = "application/json";
            //webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8   can be used for plaintext bodies
            webReq.UserAgent = "PushSharp (version: 1.0)";
            webReq.Headers.Add("Authorization: key=" + senderAuthToken);

            webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new GcmAsyncParameters()
            {
                WebRequest = webReq,
                WebResponse = null,
                Message = msg,
                SenderAuthToken = senderAuthToken,
                SenderId = senderID,
                ApplicationId = applicationID
            });
        }
        void processResponseOk(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse()
            {
                ResponseCode = GcmMessageTransportResponseCode.Ok,
                Message = asyncParam.Message
            };

            var updateClientAuth = asyncParam.WebResponse.GetResponseHeader("Update-Client-Auth");

            if (!string.IsNullOrEmpty(updateClientAuth) && UpdateGoogleClientAuthToken != null)
                UpdateGoogleClientAuthToken(updateClientAuth);

            //Get the response body
            var json = new JObject();

            try { json = JObject.Parse((new StreamReader(asyncParam.WebResponse.GetResponseStream())).ReadToEnd()); }
            catch { }

            result.NumberOfCanonicalIds = json.Value<long>("canonical_ids");
            result.NumberOfFailures = json.Value<long>("failure");
            result.NumberOfSuccesses = json.Value<long>("success");

            var jsonResults = json["results"] as JArray;

            if (jsonResults == null)
                jsonResults = new JArray();

            foreach (var r in json["results"])
            {
                var msgResult = new GcmMessageResult();

                msgResult.MessageId = r.Value<string>("message_id");
                msgResult.CanonicalRegistrationId = r.Value<string>("registration_id");

                if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
                {
                    msgResult.ResponseStatus = GcmMessageTransportResponseStatus.CanonicalRegistrationId;
                }
                else if (r["error"] != null)
                {
                    var err = r.Value<string>("error") ?? "";

                    switch (err.ToLower().Trim())
                    {
                        case "missingregistration":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MissingRegistrationId;
                            break;
                        case "unavailable":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Unavailable;
                            break;
                        case "notregistered":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered;
                            break;
                        case "invalidregistration":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration;
                            break;
                        case "mismatchsenderid":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MismatchSenderId;
                            break;
                        case "messagetoobig":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MessageTooBig;
                            break;
                        default:
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Error;
                            break;
                    }
                }

                result.Results.Add(msgResult);

            }

            asyncParam.WebResponse.Close();

            var evtmrr = MessageResponseReceived;

            if (evtmrr != null)
                evtmrr(result);
        }
Esempio n. 14
0
 public GcmMessageTransportException(string message, GcmMessageTransportResponse response)
     : base(message)
 {
     this.Response = response;
 }
Esempio n. 15
0
		void processResponseOk(GcmAsyncParameters asyncParam)
		{
			var result = new GcmMessageTransportResponse()
			{
				ResponseCode = GcmMessageTransportResponseCode.Ok,
				Message = asyncParam.Message
			};

			//Get the response body
			var json = new JObject();

		    var str = string.Empty;

			try { str = (new StreamReader(asyncParam.WebResponse.GetResponseStream())).ReadToEnd(); }
			catch { }

		    try { json = JObject.Parse(str); }
		    catch { }

			result.NumberOfCanonicalIds = json.Value<long>("canonical_ids");
			result.NumberOfFailures = json.Value<long>("failure");
			result.NumberOfSuccesses = json.Value<long>("success");
					
			var jsonResults = json["results"] as JArray;

			if (jsonResults == null)
				jsonResults = new JArray();

			foreach (var r in jsonResults)
			{
				var msgResult = new GcmMessageResult();
								
				msgResult.MessageId = r.Value<string>("message_id");
				msgResult.CanonicalRegistrationId = r.Value<string>("registration_id");
				msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Ok;
				
				if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
				{
					msgResult.ResponseStatus = GcmMessageTransportResponseStatus.CanonicalRegistrationId;
				}
				else if (r["error"] != null)
				{
					var err = r.Value<string>("error") ?? "";

					switch (err.ToLowerInvariant().Trim())
					{
						case "ok":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Ok;
							break;
						case "missingregistration":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MissingRegistrationId;
							break;
						case "unavailable":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Unavailable;
							break;
						case "notregistered":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered;
							break;
						case "invalidregistration":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration;
							break;
						case "mismatchsenderid":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MismatchSenderId;
							break;
						case "messagetoobig":
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MessageTooBig;
							break;
                        case "invaliddatakey":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidDataKey;
                            break;
                        case "invalidttl":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidTtl;
                            break;
                        case "internalservererror":
                            msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InternalServerError;
                            break;
						default:
							msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Error;
							break;
					}
				}

				result.Results.Add(msgResult);
								
			}

			asyncParam.WebResponse.Close();

			int index = 0;

			var response = result;

			//Loop through every result in the response
			// We will raise events for each individual result so that the consumer of the library
			// can deal with individual registrationid's for the notification
			foreach (var r in response.Results)
			{
				var singleResultNotification = GcmNotification.ForSingleResult(response, index);

				if (r.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
				{
					//It worked! Raise success
					asyncParam.Callback(this, new SendNotificationResult(singleResultNotification));
				}
				else if (r.ResponseStatus == GcmMessageTransportResponseStatus.CanonicalRegistrationId)
				{
					//Swap Registrations Id's
					var newRegistrationId = r.CanonicalRegistrationId;
					var oldRegistrationId = string.Empty;

					if (singleResultNotification.RegistrationIds != null && singleResultNotification.RegistrationIds.Count > 0)
						oldRegistrationId = singleResultNotification.RegistrationIds[0];

					asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new DeviceSubscriptonExpiredException()) { OldSubscriptionId = oldRegistrationId, NewSubscriptionId = newRegistrationId, IsSubscriptionExpired = true });
				}
				else if (r.ResponseStatus == GcmMessageTransportResponseStatus.Unavailable)
				{
					asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, true, new Exception("Unavailable Response Status")));
				}
				else if (r.ResponseStatus == GcmMessageTransportResponseStatus.NotRegistered)
				{
					var oldRegistrationId = string.Empty;
					
					if (singleResultNotification.RegistrationIds != null && singleResultNotification.RegistrationIds.Count > 0)
						oldRegistrationId = singleResultNotification.RegistrationIds[0];

					//Raise failure and device expired
					asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new DeviceSubscriptonExpiredException()) { OldSubscriptionId = oldRegistrationId, IsSubscriptionExpired = true, SubscriptionExpiryUtc = DateTime.UtcNow });
				}
				else
				{
					//Raise failure, for unknown reason
					asyncParam.Callback(this, new SendNotificationResult(singleResultNotification, false, new GcmMessageTransportException(r.ResponseStatus.ToString(), response)));
				}

				index++;
			}

			Interlocked.Decrement(ref waitCounter);
		}
Esempio n. 16
0
        void processResponseOk(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse()
            {
                ResponseCode = GcmMessageTransportResponseCode.Ok,
                Message      = asyncParam.Message
            };

            var updateClientAuth = asyncParam.WebResponse.GetResponseHeader("Update-Client-Auth");

            if (!string.IsNullOrEmpty(updateClientAuth) && UpdateGoogleClientAuthToken != null)
            {
                UpdateGoogleClientAuthToken(updateClientAuth);
            }

            //Get the response body
            var json = new JObject();

            try { json = JObject.Parse((new StreamReader(asyncParam.WebResponse.GetResponseStream())).ReadToEnd()); }
            catch { }


            result.NumberOfCanonicalIds = json.Value <long>("canonical_ids");
            result.NumberOfFailures     = json.Value <long>("failure");
            result.NumberOfSuccesses    = json.Value <long>("success");


            var jsonResults = json["results"] as JArray;

            if (jsonResults == null)
            {
                jsonResults = new JArray();
            }

            foreach (var r in json["results"])
            {
                var msgResult = new GcmMessageResult();

                msgResult.MessageId = r.Value <string>("message_id");
                msgResult.CanonicalRegistrationId = r.Value <string>("registration_id");

                if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
                {
                    msgResult.ResponseStatus = GcmMessageTransportResponseStatus.CanonicalRegistrationId;
                }
                else if (r["error"] != null)
                {
                    var err = r.Value <string>("error") ?? "";

                    switch (err.ToLower().Trim())
                    {
                    case "missingregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MissingRegistrationId;
                        break;

                    case "unavailable":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Unavailable;
                        break;

                    case "notregistered":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered;
                        break;

                    case "invalidregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration;
                        break;

                    case "mismatchsenderid":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MismatchSenderId;
                        break;

                    case "messagetoobig":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MessageTooBig;
                        break;

                    case "invaliddatakey":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidDataKey;
                        break;

                    case "invalidttl":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidTtl;
                        break;

                    case "internalservererror":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InternalServerError;
                        break;

                    default:
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Error;
                        break;
                    }
                }

                result.Results.Add(msgResult);
            }

            asyncParam.WebResponse.Close();

            var evtmrr = MessageResponseReceived;

            if (evtmrr != null)
            {
                evtmrr(result);
            }
        }
Esempio n. 17
0
 public GcmBadRequestTransportException(GcmMessageTransportResponse response)
     : base("Bad Request or Malformed JSON", response)
 {
 }
Esempio n. 18
0
        void processResponseError(GcmAsyncParameters asyncParam)
        {
            try
            {
                var result = new GcmMessageTransportResponse();
                result.ResponseCode = GcmMessageTransportResponseCode.Error;

                if (asyncParam == null || asyncParam.WebResponse == null)
                {
                    throw new GcmMessageTransportException("Unknown Transport Error", result);
                }

                int statusCode = (int)asyncParam.WebResponse.StatusCode;

                if (asyncParam.WebResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    //401 bad auth token
                    result.ResponseCode = GcmMessageTransportResponseCode.InvalidAuthToken;
                    throw new GcmAuthenticationErrorTransportException(result);
                }
                else if (asyncParam.WebResponse.StatusCode == HttpStatusCode.BadRequest)
                {
                    result.ResponseCode = GcmMessageTransportResponseCode.BadRequest;
                    throw new GcmBadRequestTransportException(result);
                }
                else if (statusCode >= 500 && statusCode < 600)
                {
                    //First try grabbing the retry-after header and parsing it.
                    TimeSpan retryAfter = new TimeSpan(0, 0, 120);

                    var wrRetryAfter = asyncParam.WebResponse.GetResponseHeader("Retry-After");

                    if (!string.IsNullOrEmpty(wrRetryAfter))
                    {
                        DateTime wrRetryAfterDate = DateTime.UtcNow;

                        if (DateTime.TryParse(wrRetryAfter, out wrRetryAfterDate))
                        {
                            retryAfter = wrRetryAfterDate - DateTime.UtcNow;
                        }
                        else
                        {
                            int wrRetryAfterSeconds = 120;
                            if (int.TryParse(wrRetryAfter, out wrRetryAfterSeconds))
                            {
                                retryAfter = new TimeSpan(0, 0, wrRetryAfterSeconds);
                            }
                        }
                    }

                    //Compatability for apps written with previous versions of PushSharp.
                    if (asyncParam.WebResponse.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        result.ResponseCode = GcmMessageTransportResponseCode.InternalServiceError;
                    }
                    else
                    {
                        //503 exponential backoff, get retry-after header
                        result.ResponseCode = GcmMessageTransportResponseCode.ServiceUnavailable;
                    }

                    throw new GcmServiceUnavailableTransportException(retryAfter, result);
                }

                throw new GcmMessageTransportException("Unknown Transport Error", result);
            }
            finally
            {
                if (asyncParam != null && asyncParam.WebResponse != null)
                {
                    asyncParam.WebResponse.Close();
                }
            }
        }
Esempio n. 19
0
 public GcmAuthenticationErrorTransportException(GcmMessageTransportResponse response)
     : base("Authentication Failed", response)
 {
 }
Esempio n. 20
0
 public GcmServiceUnavailableTransportException(TimeSpan retryAfter, GcmMessageTransportResponse response)
     : base("Service Temporarily Unavailable.  Please wait the retryAfter amount and implement an Exponential Backoff", response)
 {
     this.RetryAfter = retryAfter;
 }
Esempio n. 21
0
        void processResponseOk(GcmAsyncParameters asyncParam)
        {
            var result = new GcmMessageTransportResponse()
            {
                ResponseCode = GcmMessageTransportResponseCode.Ok,
                Message      = asyncParam.Message
            };

            var updateClientAuth = asyncParam.WebResponse.GetResponseHeader("Update-Client-Auth");

            if (!string.IsNullOrEmpty(updateClientAuth) && UpdateGoogleClientAuthToken != null)
            {
                UpdateGoogleClientAuthToken(updateClientAuth);
            }

            //Get the response body
            var json = new JObject();

            try { json = Utils.FromJSonString((new StreamReader(asyncParam.WebResponse.GetResponseStream())).ReadToEnd()); }
            catch { }

            long jsonResultLong = 0;

            long.TryParse(json["canonical_ids"].ToString(), out jsonResultLong);
            result.NumberOfCanonicalIds = jsonResultLong;
            jsonResultLong = 0;
            long.TryParse(json["failure"].ToString(), out jsonResultLong);
            result.NumberOfFailures = jsonResultLong;
            jsonResultLong          = 0;
            long.TryParse(json["success"].ToString(), out jsonResultLong);
            result.NumberOfSuccesses = jsonResultLong;

            var jsonResults = json["results"] as JArray;

            if (jsonResults == null)
            {
                jsonResults = new JArray();
            }

            foreach (JObject r in (JArray)json["results"])
            {
                var msgResult = new GcmMessageResult();

                msgResult.MessageId = (string)r["message_id"];
                msgResult.CanonicalRegistrationId = (string)r["registration_id"];

                if (!string.IsNullOrEmpty(msgResult.CanonicalRegistrationId))
                {
                    msgResult.ResponseStatus = GcmMessageTransportResponseStatus.CanonicalRegistrationId;
                }
                else if (r["error"] != null)
                {
                    var err = (string)r["error"] ?? "";

                    switch (err.ToLower().Trim())
                    {
                    case "missingregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MissingRegistrationId;
                        break;

                    case "unavailable":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Unavailable;
                        break;

                    case "notregistered":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.NotRegistered;
                        break;

                    case "invalidregistration":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.InvalidRegistration;
                        break;

                    case "mismatchsenderid":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MismatchSenderId;
                        break;

                    case "messagetoobig":
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.MessageTooBig;
                        break;

                    default:
                        msgResult.ResponseStatus = GcmMessageTransportResponseStatus.Error;
                        break;
                    }
                }

                result.Results.Add(msgResult);
            }

            asyncParam.WebResponse.Close();

            var evtmrr = MessageResponseReceived;

            if (evtmrr != null)
            {
                evtmrr(result);
            }
        }
Esempio n. 22
0
 public GcmAuthenticationErrorTransportException(GcmMessageTransportResponse response)
     : base("Authentication Failed", response)
 {
 }
Esempio n. 23
0
 public GcmMessageTransportException(string message, GcmMessageTransportResponse response)
     : base(message)
 {
     this.Response = response;
 }
Esempio n. 24
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {

                var context = listener.EndGetContext(result);

                var request = context.Request;
                var response = context.Response;

                var wrd = string.Empty;

                using (var sr = new StreamReader(request.InputStream))
                    wrd = sr.ReadToEnd();

                var gcm = JsonConvert.DeserializeObject<GcmRequest>(wrd);

                var transportResponse = new GcmMessageTransportResponse();

                foreach (var id in gcm.RegistrationIds)
                {

                    GcmMessageResult singleResult = null;
                    bool matchedFilter = false;

                    foreach (var filter in this.MessageResponseFilters)
                    {
                        if (filter.IsMatch(gcm, id))
                        {
                            singleResult = filter.Status;
                            singleResult.MessageId = "1:" + msgId++;
                            transportResponse.Results.Add(singleResult);
                            matchedFilter = true;
                            break;
                        }
                    }

                    if (!matchedFilter)
                    {
                        singleResult = new GcmMessageResult();
                        singleResult.ResponseStatus = GcmMessageTransportResponseStatus.Ok;
                        singleResult.MessageId = "1:" + msgId++;
                        transportResponse.Results.Add(singleResult);
                    }

                    if (singleResult.ResponseStatus == GcmMessageTransportResponseStatus.Ok)
                    {
                        transportResponse.NumberOfSuccesses++;
                    }
                    else
                        transportResponse.NumberOfFailures++;

                    transportResponse.NumberOfCanonicalIds++;

                }

                transportResponse.ResponseCode = GcmMessageTransportResponseCode.Ok;

                foreach (var filter in TransportResponseFilters)
                {
                    if (filter.IsMatch(gcm))
                    {
                        transportResponse.ResponseCode = filter.Code;
                        break;
                    }
                }

                switch (transportResponse.ResponseCode)
                {
                    case GcmMessageTransportResponseCode.Ok:
                        response.StatusCode = (int)HttpStatusCode.OK;
                        break;
                    case GcmMessageTransportResponseCode.InvalidAuthToken:
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        break;
                    case GcmMessageTransportResponseCode.ServiceUnavailable:
                        response.Headers.Add("Retry-After", "120");
                        response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
                        break;
                    case GcmMessageTransportResponseCode.InternalServiceError:
                        response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        break;
                    case GcmMessageTransportResponseCode.BadRequest:
                        response.StatusCode = (int)HttpStatusCode.BadRequest;
                        break;
                    default:
                        response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        break;
                }

                var responseString = JsonConvert.SerializeObject(transportResponse);
                var buffer = Encoding.UTF8.GetBytes(responseString);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();

                notificationReceived(transportResponse);
            }
            catch (Exception)
            {

            }

            if (listener.IsListening && !cancelServer.IsCancellationRequested)
                listener.BeginGetContext(ProcessRequest, listener);
        }
Esempio n. 25
0
 public GcmBadRequestTransportException(GcmMessageTransportResponse response)
     : base("Bad Request or Malformed JSON", response)
 {
 }