{@inheritdoc}

@throws \Sly\NotificationPusher\Exception\PushException
18006
public function push(PushInterface $push)
    {
        $client = $this->getOpenedClient();

        $ecdsaCryptoKey = $this->getECDSACryptoKey();
        $orign = null;
        $token = null;

        $message = $this->createMessageBody($push->getMessage());

        foreach ($push->getDevices() as $device) {
            $endPoint = $device->getToken();

            $newOrigin = $this->getOrigin($endPoint);
            if (is_null($token) || $orign != $newOrigin) {
                $origin = $newOrigin;
                $token = $this->createSignatureToken($origin);
            }

            $headers = $client->getRequest()->getHeaders();
            $headers
                ->addHeaderLine('Crypto-Key', 'p256ecdsa="'.$ecdsaCryptoKey.'"')
                ->addHeaderLine('Authorization', 'Bearer '.$token)
            ;

            if (!empty($message)
                && !empty($device->getParameter('publicKey'))
                && !empty($device->getParameter('authToken'))
            ) {
                $encryptor = $this->getMessageEncryptor();
                $body = $encryptor->encrypt(
                    $message,
                    $device->getParameter('publicKey'),
                    $device->getParameter('authToken')
                );

                $headers
                    ->addHeaderLine('Content-Encoding', 'aesgcm')
                    ->addHeaderLine('Encryption', 'keyid="p256dh";salt="'.$encryptor->getSalt().'"')
                ;
                $cryptoKeyHead = $headers->get('Crypto-Key');
                $cryptoKeyValue = 'keyid="p256dh";dh="'.$encryptor->getServerPublicKey().'"'.';'.$cryptoKeyHead->getFieldValue();
                $headers->addHeaderLine('Crypto-Key', $cryptoKeyValue);

                $encType = 'application/octet-stream';
            } else {
                $body = '';
                $encType = null;
            }

            $messageObj = $push->getMessage();
            if ($messageObj instanceof BaseOptionedModel) {
                $headers->addHeaderLine('TTL', $messageObj->getOption('ttl', $this->getParameter('ttl')));

                if ($messageObj->hasOption('urgency')) {
                    $headers->addHeaderLine('Urgency', $messageObj->getOption('urgency'));
                }
                if ($messageObj->hasOption('topic')) {
                    $headers->addHeaderLine('Topic', $messageObj->getOption('topic'));
                }
            }

            $this->response = $client->setUri($endPoint)
                                     ->setHeaders($headers)
                                     ->setMethod('POST')
                                     ->setRawBody($body)
                                     ->setEncType($encType)
                                     ->send();

            switch ($this->response->getStatusCode()) {
                case 500:
                    throw new PushException('500 Internal Server Error');
                    break;
                case 503:
                    $exceptionMessage = '503 Server Unavailable';
                    if ($retry = $this->response->getHeaders()->get('Retry-After')) {
                        $exceptionMessage .= '; Retry After: '.$retry;
                    }

                    throw new PushException($exceptionMessage);
                    break;
                case 401:
                    throw new PushException('401 Forbidden; Authentication Error');
                    break;
                case 400:
                    throw new PushException('400 Bad Request; invalid message');
                    break;
                case 410:
                    // FCM returns 410 on sending to the unsubscribed endpoint.
                    $this->notRegisteredDevices->add($device);

                    break;
            }

            if ($this->response->isSuccess()) {
                $this->pushedDevices->add($device);
            }
        }

        return $this->pushedDevices;
    }
31163
public function push($message)
    {
        $message = json_decode($message, true);
        $topic = array_get($this->getTopics(), $message['topic']);
        $data = $message['data'];
        $recipient = array_get($message, 'recipient');
        
        // Handle TwoStream::stop();
        if ($message['topic'] == 'cupoftea/twostream/server/stop') {
            if ($data['secret'] == config('app.key')) {
                event(new ServerStopped());
                $this->line('Stop Command fired.');
                $this->question('Stopping Server.');
                
                die();
            } else {
                // report malicious attempt
            }
        }
        
        if (! $topic) {
            return;
        }
        
        $this->setTopic($topic);
        
        if ($recipient == 'all') {
            $topic->broadcast($data);
        } else {
            foreach ((array) $recipient as $recipient) {
                if (($sessionId = $this->getUserSessionId($recipient)) || ($sessionId = WsSession::isValidId($recipient) ? $recipient : false)) {
                    foreach ($topic->getIterator() as $client) {
                        if ($client->session == $sessionId) {
                            $client->event($topic->getId(), $data);
                        }
                    }
                } else {
                    throw new InvalidRecipientException($recipient);
                }
            }
        }
    }
1104222
public function push($value)
    {
        $this->offsetSet($this->count(), $value);
        $this->seek($this->count() - 1);
    }
85862
public function execute() {
        global $CFG, $DB;

        $timenow = time();

        // Cleanup read and unread notifications.
        if (!empty($CFG->messagingdeleteallnotificationsdelay)) {
            $notificationdeletetime = $timenow - $CFG->messagingdeleteallnotificationsdelay;
            $params = array('notificationdeletetime' => $notificationdeletetime);
            $DB->delete_records_select('notifications', 'timecreated < :notificationdeletetime', $params);
        }

        // Cleanup read notifications.
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = $timenow - $CFG->messagingdeletereadnotificationsdelay;
            $params = array('notificationdeletetime' => $notificationdeletetime);
            $DB->delete_records_select('notifications', 'timeread < :notificationdeletetime', $params);
        }
    }
45741
public function pushNotificationAsync(PushNotification $notification, PushSubscription $subscription, int $ttl = 3600) : PromiseInterface
    {
        $cipher = $this->cryptograph->encrypt($notification, $subscription);

        $pushMessage = new Message($cipher, $subscription, $ttl);

        $request = $this->pushService->createRequest($pushMessage, $subscription);
        $promise = $this->httpClient->sendAsync($request);

        return $promise;
    }
90561
public function forgetPushed()
    {
        foreach ($this->listeners as $key => $value) {
            if (Str::endsWith($key, '_pushed')) {
                $this->forget($key);
            }
        }
    }
1070187
private static function pushTokens(TokenInterface $token, TokenInterface $prev = null, array &$tokens = [])
    {
        if (null !== $prev) {
            $prev->next = $token;
        }

        $token->prev = $prev;

        $tokens[] = $token;
    }
1074991
public function push(array $tokens = [], array $notifications = [], array $params = [])
    {
        if (!$tokens || !$notifications) {
            return null;
        }

        $adapterParams = [];
        $deviceParams  = [];
        $messageParams = [];
        if (isset($params) && !empty($params)) {
            if (isset($params['adapter'])) {
                $adapterParams = $params['adapter'];
            }

            if (isset($params['device'])) {
                $deviceParams = $params['device'];
            }

            if (isset($params['message'])) {
                $messageParams = $params['message'];
            }

            //because we have now notification and data separated
            if (isset($params['notificationData'])) {
                $messageParams['notificationData'] = $params['notificationData'];
            }
        }

        $adapterParams['apiKey'] = $this->apiKey;

        if (!$this->apiKey) {
            throw new \RuntimeException('Android api key must be set');
        }

        // Development one by default (without argument).
        /** @var PushManager $pushManager */
        $pushManager = new PushManager($this->environment);

        // Then declare an adapter.
        $gcmAdapter = new GcmAdapter($adapterParams);

        // Set the device(s) to push the notification to.
        $devices = new DeviceCollection([]);

        //devices
        foreach ($tokens as $token) {
            $devices->add(new Device($token, $deviceParams));
        }

        foreach ($notifications as $notificationText) {
            // Then, create the push skel.
            $message = new Message($notificationText, $messageParams);

            // Finally, create and add the push to the manager, and push it!
            $push = new Push($gcmAdapter, $devices, $message);
            $pushManager->add($push);
        }

        // Returns a collection of notified devices
        $pushes = $pushManager->push();

        $this->response = $gcmAdapter->getResponse();

        return $this->response;
    }
403107
public function send()
	{
		if (!$this->_hSocket) {
			throw new ApnsPHP_Push_Exception(
				'Not connected to Push Notification Service'
			);
		}

		if (empty($this->_aMessageQueue)) {
			throw new ApnsPHP_Push_Exception(
				'No notifications queued to be sent'
			);
		}

		$this->_aErrors = array();
		$nRun = 1;
		while (($nMessages = count($this->_aMessageQueue)) > 0) {
			$this->_log("INFO: Sending messages queue, run #{$nRun}: $nMessages message(s) left in queue.");

			$bError = false;
			foreach($this->_aMessageQueue as $k => &$aMessage) {
				if (function_exists('pcntl_signal_dispatch')) {
					pcntl_signal_dispatch();
				}

				$message = $aMessage['MESSAGE'];
				$sCustomIdentifier = (string)$message->getCustomIdentifier();
				$sCustomIdentifier = sprintf('[custom identifier: %s]', empty($sCustomIdentifier) ? 'unset' : $sCustomIdentifier);

				$nErrors = 0;
				if (!empty($aMessage['ERRORS'])) {
					foreach($aMessage['ERRORS'] as $aError) {
						if ($aError['statusCode'] == 0) {
							$this->_log("INFO: Message ID {$k} {$sCustomIdentifier} has no error ({$aError['statusCode']}), removing from queue...");
							$this->_removeMessageFromQueue($k);
							continue 2;
						} else if ($aError['statusCode'] > 1 && $aError['statusCode'] <= 8) {
							$this->_log("WARNING: Message ID {$k} {$sCustomIdentifier} has an unrecoverable error ({$aError['statusCode']}), removing from queue without retrying...");
							$this->_removeMessageFromQueue($k, true);
							continue 2;
						}
					}
					if (($nErrors = count($aMessage['ERRORS'])) >= $this->_nSendRetryTimes) {
						$this->_log(
							"WARNING: Message ID {$k} {$sCustomIdentifier} has {$nErrors} errors, removing from queue..."
						);
						$this->_removeMessageFromQueue($k, true);
						continue;
					}
				}

				$nLen = strlen($aMessage['BINARY_NOTIFICATION']);
				$this->_log("STATUS: Sending message ID {$k} {$sCustomIdentifier} (" . ($nErrors + 1) . "/{$this->_nSendRetryTimes}): {$nLen} bytes.");

				$aErrorMessage = null;
				if ($nLen !== ($nWritten = (int)@fwrite($this->_hSocket, $aMessage['BINARY_NOTIFICATION']))) {
					$aErrorMessage = array(
						'identifier' => $k,
						'statusCode' => self::STATUS_CODE_INTERNAL_ERROR,
						'statusMessage' => sprintf('%s (%d bytes written instead of %d bytes)',
							$this->_aErrorResponseMessages[self::STATUS_CODE_INTERNAL_ERROR], $nWritten, $nLen
						)
					);
				}
				usleep($this->_nWriteInterval);

				$bError = $this->_updateQueue($aErrorMessage);
				if ($bError) {
					break;
				}
			}

			if (!$bError) {
				$read = array($this->_hSocket);
				$null = NULL;
				$nChangedStreams = @stream_select($read, $null, $null, 0, $this->_nSocketSelectTimeout);
				if ($nChangedStreams === false) {
					$this->_log('ERROR: Unable to wait for a stream availability.');
					break;
				} else if ($nChangedStreams > 0) {
					$bError = $this->_updateQueue();
					if (!$bError) {
						$this->_aMessageQueue = array();
					}
				} else {
					$this->_aMessageQueue = array();
				}
			}

			$nRun++;
		}
	}
1232622
protected function pushGroup()
    {
        if( $this->group ) {
            $this->parts[] = 'GROUP BY';
            $this->parts[] = $this->quoteIdentifierIfNotExpression($this->group);
        }
    }
503485
public function push(string $data) {
        $result = hash_update($this->getHandle(), $data);
        if(!$result) {
            throw new RuntimeException();
        }
    }
623949
public function send($notifiable, LaravelNotification $notification)
    {
        $entity = $this->getEntity($notifiable, $notification);

        if ($channel = $notifiable->routeNotificationFor('doctrine')) {
            $em = $this->registry->getManager($channel);
        } else {
            $em = $this->registry->getManagerForClass(get_class($entity));
        }

        if (is_null($em)) {
            throw new NoEntityManagerFound;
        }

        $em->persist($entity);
        $em->flush();
    }
339055
protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $output->writeln([
                '<bg=yellow;>Push Script Starting...</>',
                '=====================',
            ]);
            $push = new PushService($this->config);
            $type = $input->getArgument('type');
            $push->run($type);
            $output->writeln([
                '=====================',
                '<bg=yellow;>Push Script End!</>'
            ]);
        } catch (Exception $e) {
            $output->writeln('<bg=red;>'.$e->getMessage().'</> <options=bold></>');
            $output->writeln('');
        }
    }
564675
public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor($this->notificationFor())) {
            return;
        }

        $message = $this->buildMessage($notifiable, $notification);

        $data = $this->buildData($message);

        $this->push($this->pushServiceName(), $to, $data, $message);
    }
22314
public function withNotification($notification): self
    {
        $new = clone $this;
        $new->notification = $notification instanceof Notification ? $notification : Notification::fromArray($notification);

        return $new;
    }
940325
public function pushValue($value)
    {
        $old = $this->value;
        if (!$this->stackable) {
            $this->setValue($value);
            return;
        }
        if (!is_array($this->value)) {
            $this->value = [$this->value, $value];
        } else {
            $f = false;
            foreach ($this->value as $k => $v) {
                if (!is_int($k)) {
                    $f = true;
                    break;
                }
            }
            if (!$f) {
                $this->value[] = $value;
            } else {
                $this->value = [$this->value, $value];
            }
        }
        $this->onUpdate($old);
    }
94542
protected function withoutNotifications()
    {
        $mock = Mockery::mock(NotificationDispatcher::class);

        $mock->shouldReceive('send')->andReturnUsing(function ($notifiable, $instance, $channels = []) {
            $this->dispatchedNotifications[] = compact(
                'notifiable', 'instance', 'channels'
            );
        });

        $this->app->instance(NotificationDispatcher::class, $mock);

        return $this;
    }