diff -r 877f952ae2bd -r 6b6c2214f778 web/lib/Zend/Mobile/Push/Gcm.php --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/web/lib/Zend/Mobile/Push/Gcm.php Thu Mar 21 19:52:38 2013 +0100 @@ -0,0 +1,172 @@ +_apiKey; + } + + /** + * Set API Key + * + * @param string $key + * @return Zend_Mobile_Push_Gcm + * @throws Zend_Mobile_Push_Exception + */ + public function setApiKey($key) + { + if (!is_string($key) || empty($key)) { + throw new Zend_Mobile_Push_Exception('The api key must be a string and not empty'); + } + $this->_apiKey = $key; + return $this; + } + + /** + * Get Http Client + * + * @return Zend_Http_Client + */ + public function getHttpClient() + { + if (!$this->_httpClient) { + $this->_httpClient = new Zend_Http_Client(); + $this->_httpClient->setConfig(array( + 'strictredirects' => true, + )); + } + return $this->_httpClient; + } + + /** + * Set Http Client + * + * @return Zend_Mobile_Push_Gcm + */ + public function setHttpClient(Zend_Http_Client $client) + { + $this->_httpClient = $client; + return $this; + } + + /** + * Send Message + * + * @param Zend_Mobile_Push_Message_Gcm $message + * @return Zend_Mobile_Push_Response_Gcm + * @throws Zend_Mobile_Push_Exception + */ + public function send(Zend_Mobile_Push_Message_Abstract $message) + { + if (!$message->validate()) { + throw new Zend_Mobile_Push_Exception('The message is not valid.'); + } + + $this->connect(); + + $client = $this->getHttpClient(); + $client->setUri(self::SERVER_URI); + $client->setHeaders('Authorization', 'key=' . $this->getApiKey()); + + $json = array('registration_ids' => $message->getToken()); + if ($data = $message->getData()) { + $json['data'] = $data; + } + if ($id = $message->getId()) { + $json['id'] = $id; + } + + $response = $client->setRawData($message->toJson(), 'application/json') + ->request('POST'); + $this->close(); + + switch ($response->getStatus()) + { + case 500: + require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; + throw new Zend_Mobile_Push_Exception_ServerUnavailable('The server encountered an internal error, try again'); + break; + case 503: + require_once 'Zend/Mobile/Push/Exception/ServerUnavailable.php'; + throw new Zend_Mobile_Push_Exception_ServerUnavailable('The server was unavailable, check Retry-After header'); + break; + case 401: + require_once 'Zend/Mobile/Push/Exception/InvalidAuthToken.php'; + throw new Zend_Mobile_Push_Exception_InvalidAuthToken('There was an error authenticating the sender account'); + break; + case 400: + require_once 'Zend/Mobile/Push/Exception/InvalidPayload.php'; + throw new Zend_Mobile_Push_Exception_InvalidPayload('The request could not be parsed as JSON or contains invalid fields'); + break; + } + return new Zend_Mobile_Push_Response_Gcm($response->getBody(), $message); + } +}