From 5bab60036663fc8339d152bef08ef8247ae320a0 Mon Sep 17 00:00:00 2001 From: Kendrick Chan Date: Tue, 26 Jun 2018 02:27:56 +0800 Subject: [PATCH] Add intitial version of APNSPusher #125 --- config/services.yaml | 5 +++ src/Service/APNSPusher.php | 88 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 src/Service/APNSPusher.php diff --git a/config/services.yaml b/config/services.yaml index 57b8885e..1fd9c3cc 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -69,3 +69,8 @@ services: arguments: $ip_address: "%env(MQTT_IP_ADDRESS)%" $port: "%env(MQTT_PORT)%" + + App\Service\APNSPusher: + arguments: + $gateway_url: "%env(APNS_GATEWAY_URL)%" + $pem_file: "%env(PEM_FILE)%" diff --git a/src/Service/APNSPusher.php b/src/Service/APNSPusher.php new file mode 100644 index 00000000..98164ae1 --- /dev/null +++ b/src/Service/APNSPusher.php @@ -0,0 +1,88 @@ +gateway_url = $gateway_url; + $this->pem_file = $pem_file; + $this->is_connected = false; + } + + public function connect() + { + $passphrase = ''; + $ctx = stream_context_create(); + stream_context_set_option($ctx, 'ssl', 'local_cert', $this->pem_file); + stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); + + // attempt connection + $conn = stream_socket_client($gateway_url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); + + if (!$conn) + { + // can't connect to pusher + error_log("Failed to connect to APNS: $err $errstr"); + $this->conn = null; + $this->is_connected = false; + } + else + { + error_log("Connected to APNS"); + $this->conn = $conn; + $this->is_connected = true; + } + } + + public function buildPayload($message) + { + $payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}'; + return $payload; + } + + public function send($device_id, $payload) + { + // connect + if (!$this->is_connected) + $this->connect(); + + // build the binary notification + $msg = chr(0) . pack('n', 32) . pack('H*', $device_id) . pack('n', strlen($payload)) . $payload; + + // Send it to the server + $result = fwrite($this->conn, $msg, strlen($msg)); + + if (!$result) + { + echo 'Undelivered message count: ' . $device_id . '
'; + } + else + { + echo 'Delivered message count: ' . $device_id . '
'; + } + + if ($this->conn) + { + fclose($this->conn); + $this->is_connected = false; + error_log("connection closed"); + } + } + + + protected function tr_to_utf($text) + { + $text = trim($text); + $search = array('Ü', 'Þ', 'Ð', 'Ç', 'Ý', 'Ö', 'ü', 'þ', 'ð', 'ç', 'ý', 'ö'); + $replace = array('Ü', 'Åž', 'Ğž', 'Ç', 'İ', 'Ö', 'ü', 'ÅŸ', 'ÄŸ', 'ç', 'ı', 'ö'); + $new_text = str_replace($search, $replace, $text); + return $new_text; + } +}