Пример #1
2
 public function __invoke(Job $job)
 {
     $job = $this->elasticsearch->getJob($job->getId());
     // find and kill child jobs
     $childJobs = $this->elasticsearch->getJobs(['query' => 'runId:' . $job->getRunId() . '.*', 'project.id' => $job->getProject()['id']]);
     $this->logger->debug("Child jobs found", ['jobs' => $childJobs]);
     $snsClient = new SnsClient(['credentials' => ['key' => $this->snsConfig['key'], 'secret' => $this->snsConfig['secret']], 'region' => isset($this->snsConfig['region']) ? $this->snsConfig['region'] : 'us-east-1', 'version' => '2010-03-31']);
     // kill them all
     if (!empty($childJobs)) {
         foreach ($childJobs as $childJob) {
             $snsClient->publish(['TopicArn' => $this->snsConfig['topic_arn'], 'Message' => json_encode(['jobId' => $childJob['id']])]);
         }
     }
     $callback = $this->cleanupCallback;
     $callback($job);
     $endTime = time();
     $duration = $endTime - strtotime($job->getStartTime());
     $job->setStatus(Job::STATUS_TERMINATED);
     $job->setResult(['message' => 'Job has been terminated']);
     $job->setEndTime(date('c', $endTime));
     $job->setDurationSeconds($duration);
     $this->jobMapper->update($job);
 }
Пример #2
1
 /**
  * @param string      $request
  * @param string|null $resource_type
  * @param string|null $resource_id
  *
  * @return array
  * @throws BadRequestException
  * @throws InternalServerErrorException
  * @throws NotFoundException
  * @throws null
  */
 public function publish($request, $resource_type = null, $resource_id = null)
 {
     /** http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.Sns.SnsClient.html#_publish */
     $data = [];
     if (is_array($request)) {
         if (null !== ($message = ArrayUtils::get($request, 'Message'))) {
             $data = array_merge($data, $request);
             if (is_array($message)) {
                 $data['Message'] = json_encode($message);
                 if (!ArrayUtils::has($request, 'MessageStructure')) {
                     $data['MessageStructure'] = 'json';
                 }
             }
         } else {
             //  This array is the message
             $data['Message'] = json_encode($request);
             $data['MessageStructure'] = 'json';
         }
     } else {
         //  This string is the message
         $data['Message'] = $request;
     }
     switch ($resource_type) {
         case SnsTopic::RESOURCE_NAME:
             $data['TopicArn'] = $this->addArnPrefix($resource_id);
             break;
         case SnsEndpoint::RESOURCE_NAME:
             $data['TargetArn'] = $this->addArnPrefix($resource_id);
             break;
         default:
             //  Must contain resource, either Topic or Endpoint ARN
             $topic = ArrayUtils::get($data, 'Topic', ArrayUtils::get($data, 'TopicArn'));
             $endpoint = ArrayUtils::get($data, 'Endpoint', ArrayUtils::get($data, 'EndpointArn', ArrayUtils::get($data, 'TargetArn')));
             if (!empty($topic)) {
                 $data['TopicArn'] = $this->addArnPrefix($topic);
             } elseif (!empty($endpoint)) {
                 $data['TargetArn'] = $this->addArnPrefix($endpoint);
             } else {
                 throw new BadRequestException("Publish request does not contain resource, either 'Topic' or 'Endpoint'.");
             }
             break;
     }
     try {
         if (null !== ($result = $this->conn->publish($data))) {
             $id = ArrayUtils::get($result->toArray(), 'MessageId', '');
             return ['MessageId' => $id];
         }
     } catch (\Exception $ex) {
         if (null !== ($newEx = static::translateException($ex))) {
             throw $newEx;
         }
         throw new InternalServerErrorException("Failed to push message.\n{$ex->getMessage()}", $ex->getCode());
     }
     return [];
 }
Пример #3
1
    public function publish($subject, $body, $channels = [])
    {
        $structured = ['default' => $body];
        foreach ($channels as $channel) {
            $is_supported = true;
            switch ($channel) {
                case self::CHANNEL_EMAIL:
                case self::CHANNEL_SQS:
                case self::CHANNEL_LAMBDA:
                case self::CHANNEL_HTTP:
                case self::CHANNEL_HTTPS:
                case self::CHANNEL_SMS:
                    // don't touch body
                    break;
                case self::CHANNEL_APNS:
                case self::CHANNEL_APNS_SANDBOX:
                case self::CHANNEL_APNS_VOIP:
                case self::CHANNEL_APNS_VOIP_SANDBOX:
                case self::CHANNEL_MACOS:
                case self::CHANNEL_MACOS_SANDBOX:
                    $body = ["aps" => ["alert" => $body]];
                    break;
                case self::CHANNEL_GCM:
                case self::CHANNEL_ADM:
                    $body = ["data" => ["message" => $body]];
                    break;
                case self::CHANNEL_BAIDU:
                    $body = ["title" => $body, "description" => $body];
                    break;
                case self::CHANNEL_MPNS:
                    $body = htmlentities($body, ENT_XML1);
                    $body = <<<XML
<?xml version="1.0" encoding="utf-8"?><wp:Notification xmlns:wp="WPNotification"><wp:Tile><wp:Count>ENTER COUNT</wp:Count><wp:Title>{$body}</wp:Title></wp:Tile></wp:Notification>
XML;
                    break;
                default:
                    mwarning("Channel [%s] is not supported by %s", $channels, static::class);
                    $is_supported = false;
                    break;
            }
            if ($is_supported) {
                $structured[$channel] = $body;
            }
        }
        $json = json_encode($structured);
        $this->client->publish(["Subject" => $subject, "Message" => $json, "MessageStructure" => "json", "TopicArn" => $this->topic_arn]);
    }
Пример #4
0
 /**
  * Send message to sqs and trigger lambda
  *
  * @param string $message to be send via sqs
  *
  */
 public function publish($message)
 {
     // http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Sqs.SqsClient.html#_sendMessage
     $this->sqs->sendMessage(['QueueUrl' => $this->sqsQueueUrl, 'MessageBody' => $message]);
     // http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Sns.SnsClient.html#_publish
     $this->sns->publish(['TopicArn' => $this->snsTopicArn, 'Message' => 'SQS Message send', 'Subject' => 'SQS Message send']);
 }
Пример #5
0
 /**
  * @param             $token
  * @param PushMessage $message
  *
  * @return mixed
  */
 private function sendOne($token, $message)
 {
     $client = new SnsClient(['credentials' => new Credentials($this->accessKey, $this->secretKey), 'region' => $this->region, 'version' => 'latest']);
     $endpoint = $client->createPlatformEndpoint(['PlatformApplicationArn' => $this->appArn, 'Token' => $token]);
     $published = $client->publish(['MessageStructure' => 'json', 'Message' => Json::encode(['default' => $message->getBody(), $message->getService() => $this->formatMessage($message)]), 'TargetArn' => $endpoint['EndpointArn']]);
     return $published['MessageId'];
 }
 public function testExecute()
 {
     $application = new Application($this->httpClient->getKernel());
     $application->add(new InitKillQueueCommand());
     /** @var InitKillQueueCommand $command */
     $command = $application->find('syrup:queue:kill-init');
     $commandTester = new CommandTester($command);
     $commandTester->execute(['command' => $command->getName()]);
     $this->assertEquals(0, $commandTester->getStatusCode());
     /** @var QueueFactory $queueFactory */
     $queueFactory = $this->httpClient->getContainer()->get('syrup.queue_factory');
     $queueId = 'syrup_kill_' . str_replace('.keboola.com', '', gethostname());
     $queueService = $queueFactory->get($queueId);
     $this->assertInstanceOf('Keboola\\Syrup\\Service\\Queue\\QueueService', $queueService);
     $snsConfig = $this->httpClient->getContainer()->getParameter('sns');
     $snsClient = new SnsClient(['credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']], 'region' => isset($snsConfig['region']) ? $snsConfig['region'] : 'us-east-1', 'version' => '2010-03-31']);
     $subscriptions = $snsClient->listSubscriptionsByTopic(['TopicArn' => $snsConfig['topic_arn']]);
     $ssArr = $subscriptions->get('Subscriptions');
     $ourSS = null;
     foreach ($ssArr as $ss) {
         if (false !== strstr($ss['Endpoint'], $queueId)) {
             $ourSS = $ss;
             break;
         }
     }
     $this->assertNotNull($ourSS);
     $this->assertEquals('sqs', $ourSS['Protocol']);
     $this->assertEquals($snsConfig['topic_arn'], $ourSS['TopicArn']);
 }
 function getSnsClient()
 {
     if ($this->snsClient) {
         return $this->snsClient;
     }
     $this->snsClient = $this->aws->get('sns');
     $this->snsClient->setRegion($this->topicRegion);
     return $this->snsClient;
 }
Пример #8
0
function sms($number, $message)
{
    if (empty($number) || empty($message)) {
        return false;
    }
    $SnsClient = new Aws\Sns\SnsClient(['version' => 'latest', 'region' => "ap-southeast-1"]);
    $result = $SnsClient->publish(array('Message' => $message, 'PhoneNumber' => $number, 'MessageAttributes' => array('AWS.SNS.SMS.SMSType' => array('StringValue' => 'Transactional', 'DataType' => 'String'), 'AWS.SNS.SMS.SenderID' => array('StringValue' => explode('.', getenv('HOST'), 2)[0], 'DataType' => 'String'))));
    return $result['MessageId'];
}
Пример #9
0
 /**
  * {@inheritDoc}
  */
 protected function write(array $record)
 {
     try {
         $this->sns->publish(['TopicArn' => $this->topicArn, 'Message' => mb_strcut($this->getFormatter()->format($record), 0, 262144), 'Subject' => $this->subject]);
     } catch (SnsException $e) {
         if ($this->logger) {
             $this->logger->error("Failed to send message via AmazonSNS", ['exception' => $e]);
         }
     }
 }
Пример #10
0
 private function showEndpoints($platformArn, $title = 'List of endpoints:')
 {
     $result = $this->client->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $platformArn));
     $output = $this->output;
     $output->writeln("<comment>{$title}</comment>");
     foreach ($result['Endpoints'] as $endpoint) {
         $output->writeln($endpoint['EndpointArn']);
         $output->writeln("<info>CustomUserData:</info> {$endpoint['Attributes']['CustomUserData']}");
         $output->writeln("<info>Enabled:</info> {$endpoint['Attributes']['Enabled']}");
     }
 }
Пример #11
0
 private function subscribePlatform($platform, $topic)
 {
     foreach ($this->sns->getPaginator('ListEndpointsByPlatformApplication', ['PlatformApplicationArn' => $this->arns[$platform]]) as $endpoint) {
         $this->logger && $this->logger->info('Subscribing device to topic', ['device' => $endpoint['EndpointArn'], 'topic' => $topic, 'platform' => $platform]);
         try {
             $this->sns->subscribe(['TopicArn' => $topic, 'Protocol' => 'application', 'Endpoint' => $endpoint['EndpointArn']]);
         } catch (SnsException $e) {
             $this->logger && $this->logger->info('Error subscribing device to topic', ['device' => $endpoint['EndpointArn'], 'topic' => $topic, 'platform' => $platform, 'exception' => $e]);
         }
     }
 }
 public function testPublishAlteredMessage()
 {
     $args = ['Message' => $originalMessage = 'MyOriginalMessage'];
     $this->snsClient->method('__call')->with('publish')->willReturnCallback(function ($name, array $args) use($originalMessage) {
         $params = array_key_exists(0, $args) ? $args[0] : [];
         \PHPUnit_Framework_Assert::assertNotEquals($originalMessage, $params['Message']);
         return new Result();
     });
     $actual = $this->sut->publish($args);
     self::assertInstanceOf(Result::class, $actual);
 }
Пример #13
0
 /**
  * Enable all devices registered on platform
  *
  * @param string $platform
  */
 private function enablePlatform($platform)
 {
     foreach ($this->sns->getPaginator('ListEndpointsByPlatformApplication', ['PlatformApplicationArn' => $this->arns[$platform]]) as $endpoint) {
         if ($endpoint['Attributes']['Enabled'] == "false") {
             try {
                 $this->sns->setEndpointAttributes(['EndpointArn' => $endpoint['EndpointArn'], 'Attributes' => ['Enabled' => "true"]]);
                 $this->logger && $this->logger->info("Enabled {$endpoint['EndpointArn']}");
             } catch (\Exception $e) {
                 $this->logger && $this->logger->error("Failed to push set attributes on {$endpoint['EndpointArn']}", ['exception' => $e, 'endpoint' => $endpoint]);
             }
         }
     }
 }
Пример #14
0
 /**
  * Enable all devices registered on platform
  *
  * @param string $platform
  */
 private function removeFromPlatform($platform)
 {
     foreach ($this->sns->getPaginator('ListEndpointsByPlatformApplication', ['PlatformApplicationArn' => $this->arns[$platform]]) as $endpoint) {
         if ($endpoint['Attributes']['Enabled'] == "false") {
             try {
                 $this->sns->deleteEndpoint(['EndpointArn' => $endpoint['EndpointArn']]);
                 $this->logger && $this->logger->info("Removed {$endpoint['EndpointArn']}");
             } catch (\Exception $e) {
                 $this->logger && $this->logger->error("Failed to remove endpoint {$endpoint['EndpointArn']}", ['exception' => $e, 'endpoint' => $endpoint]);
             }
         }
     }
 }
Пример #15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $noWatch = $input->getOption('no-watch');
     $queueId = $this->getQueueId();
     $snsConfig = $this->getContainer()->getParameter('sns');
     $region = isset($snsConfig['region']) ? $snsConfig['region'] : 'us-east-1';
     /** @var QueueFactory $queueFactory */
     $queueFactory = $this->getContainer()->get('syrup.queue_factory');
     $sqs = $queueFactory->create($queueId, $region, $snsConfig['key'], $snsConfig['secret']);
     /** @var Connection $conn */
     $conn = $this->getContainer()->get('doctrine.dbal.syrup_connection');
     $stmt = $conn->query("SELECT * FROM queues WHERE id='{$queueId}'");
     $res = $stmt->fetchAll();
     if (empty($res)) {
         $conn->insert('queues', ['id' => $queueId, 'access_key' => $snsConfig['key'], 'secret_key' => $snsConfig['secret'], 'region' => $region, 'url' => $sqs->get('QueueUrl')]);
     }
     $sqsClient = new SqsClient(['region' => $region, 'version' => '2012-11-05', 'credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']]]);
     $sqsArn = $sqsClient->getQueueArn($sqs->get('QueueUrl'));
     // subscribe SQS to SNS
     $snsClient = new SnsClient(['region' => $region, 'version' => '2010-03-31', 'credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']]]);
     $snsClient->subscribe(['TopicArn' => $snsConfig['topic_arn'], 'Protocol' => 'sqs', 'Endpoint' => $sqsArn]);
     // add policy to SQS to allow SNS sending messages to it
     $sqsPolicy = '{
       "Version": "2008-10-17",
       "Id": "' . $sqsArn . '/SQSDefaultPolicy",
       "Statement": [
         {
           "Sid": "sqs-sns",
           "Effect": "Allow",
           "Principal": {
             "AWS": "*"
           },
           "Action": "SQS:SendMessage",
           "Resource": "' . $sqsArn . '",
           "Condition": {
             "ArnEquals": {
               "aws:SourceArn": "' . $snsConfig['topic_arn'] . '"
             }
           }
         }
       ]
     }';
     $sqsClient->setQueueAttributes(['QueueUrl' => $sqs->get('QueueUrl'), 'Attributes' => ['Policy' => $sqsPolicy]]);
     $output->writeln("SQS created and registered to SNS");
     // Add Cloudwatch alarm
     if (!$noWatch) {
         $cwClient = new CloudWatchClient(['region' => $region, 'version' => '2010-08-01', 'credentials' => ['key' => $snsConfig['key'], 'secret' => $snsConfig['secret']]]);
         $cwClient->putMetricAlarm(['AlarmName' => sprintf('Syrup %s queue is full', $queueId), 'ActionsEnabled' => true, 'AlarmActions' => [$snsConfig['alarm_topic_arn']], 'MetricName' => 'ApproximateNumberOfMessagesVisible', 'Namespace' => 'AWS/SQS', 'Statistic' => 'Average', 'Dimensions' => [['Name' => 'QueueName', 'Value' => $queueId]], 'Period' => 300, 'EvaluationPeriods' => 1, 'Threshold' => 5, 'ComparisonOperator' => 'GreaterThanOrEqualToThreshold']);
         $output->writeln("Cloudwatch alarm created");
     }
 }
 private function addEndpoint(Model\AbstractEndpoint $endpoint)
 {
     try {
         $result = $this->sns->createPlatformEndpoint(['PlatformApplicationArn' => $this->getPlatformArn($endpoint), 'Token' => $endpoint->getToken(), 'CustomUserData' => $endpoint->getUser()->getId()]);
     } catch (\Aws\Sns\Exception\InvalidParameterException $e) {
         if (preg_match('/Endpoint (.*) already exists/', $e->getResponse()->getMessage(), $matches)) {
             $this->sns->deleteEndpoint(array('EndpointArn' => $matches[1]));
             $result = $this->sns->createPlatformEndpoint(['PlatformApplicationArn' => $this->getPlatformArn($endpoint), 'Token' => $endpoint->getToken(), 'CustomUserData' => $endpoint->getUser()->getId()]);
         } else {
             return;
         }
     }
     $endpoint->setArn($result['EndpointArn']);
     $this->em->persist($endpoint);
     $this->em->flush($endpoint);
 }
Пример #17
0
 /**
  * @covers Aws\Sns\SnsClient::factory
  */
 public function testFactoryInitializesClient()
 {
     $client = SnsClient::factory(array('key' => 'foo', 'secret' => 'bar', 'region' => 'us-east-1'));
     $this->assertInstanceOf('Aws\\Common\\Signature\\SignatureV2', $client->getSignature());
     $this->assertInstanceOf('Aws\\Common\\Credentials\\Credentials', $client->getCredentials());
     $this->assertEquals('https://sns.us-east-1.amazonaws.com', $client->getBaseUrl());
 }
 public function __construct($region = false)
 {
     if (!$region && !($region = getenv("AWS_DEFAULT_REGION"))) {
         throw new \Exception("Set 'AWS_DEFAULT_REGION' environment variable!");
     }
     $this->region = $region;
     $this->sns = SnsClient::factory(['region' => $region]);
     $this->ddb = DynamoDbClient::factory(['region' => $region]);
 }
 function __construct()
 {
     $this->snsARNs = explode(',', $_ENV['snsTopicARNs']);
     if ('POST' === $_SERVER['REQUEST_METHOD'] && !empty($_POST['text'])) {
         $this->setText();
         $this->setARN();
         $this->awsClient = SnsClient::factory(array('region' => $_ENV['awsSNSRegion']));
         $this->processForm();
     } else {
         $this->renderForm();
     }
 }
Пример #20
0
 /**
  * Handles SNS Notifications
  *
  * For Subscription notifications, this method will automatically confirm
  * the Subscription request
  *
  * For Message notifications, this method polls the queue and dispatches
  * the `{queue}.message_received` event for each message retrieved
  *
  * @param NotificationEvent $event The Notification Event
  * @param string $eventName Name of the event
  * @param EventDispatcherInterface $dispatcher
  * @return bool|void
  */
 public function onNotification(NotificationEvent $event, $eventName, EventDispatcherInterface $dispatcher)
 {
     if (NotificationEvent::TYPE_SUBSCRIPTION == $event->getType()) {
         $topicArn = $event->getNotification()->getMetadata()->get('TopicArn');
         $token = $event->getNotification()->getMetadata()->get('Token');
         $this->sns->confirmSubscription(['TopicArn' => $topicArn, 'Token' => $token]);
         $context = ['TopicArn' => $topicArn];
         $this->log(200, "Subscription to SNS Confirmed", $context);
         return;
     }
     $messages = $this->receive();
     foreach ($messages as $message) {
         $messageEvent = new MessageEvent($this->name, $message);
         $dispatcher->dispatch(Events::Message($this->name), $messageEvent);
     }
 }
Пример #21
0
 public function testAttributesSerializeCorrectly()
 {
     $client = SnsClient::factory(array('key' => 'foo', 'secret' => 'bar', 'region' => 'us-east-1'));
     // Mock the response so no request is sent to the service
     $mockPlugin = new MockPlugin();
     $mockPlugin->addResponse(new Response(200));
     $client->addSubscriber($mockPlugin);
     // Listener to grab the request body about to be sent
     $client->getEventDispatcher()->addListener('request.before_send', function ($event) use(&$actualRequestBody) {
         list(, $actualRequestBody) = explode("\r\n\r\n", $event['request']);
     }, -255);
     // Expected serialization; extracted from service API documentation
     $expectedRequestBody = 'Action=SetPlatformApplicationAttributes&Version=2010-03-31&PlatformApplicationArn=arn%3' . 'Aaws%3Asns%3Aus-west-2%3A123456789012%3Aapp%2FGCM%2Fgcmpushapp&Attributes.entry.1.key=EventEndpointCreat' . 'ed&Attributes.entry.1.value=arn%3Aaws%3Asns%3Aus-west-2%3A123456789012%3Atopicarn';
     // Perform the operation
     $client->setPlatformApplicationAttributes(array('PlatformApplicationArn' => 'arn:aws:sns:us-west-2:123456789012:app/GCM/gcmpushapp', 'Attributes' => array('EventEndpointCreated' => urldecode('arn:aws:sns:us-west-2:123456789012:topicarn'))));
     $this->assertEquals($expectedRequestBody, $actualRequestBody);
 }
Пример #22
0
 /**
  * Send a message to all devices on a platform
  *
  * @param Message|string $message
  * @param string $platform
  */
 private function broadcastToPlatform($message, $platform)
 {
     if ($this->debug) {
         $this->logger && $this->logger->notice("Message would have been sent to {$platform}", ['Message' => $message]);
         return;
     }
     foreach ($this->sns->getPaginator('ListEndpointsByPlatformApplication', ['PlatformApplicationArn' => $this->arns[$platform]]) as $endpoint) {
         if ($endpoint['Attributes']['Enabled'] == "true") {
             try {
                 $this->send($message, $endpoint['EndpointArn']);
             } catch (\Exception $e) {
                 $this->logger && $this->logger->error("Failed to push to {$endpoint['EndpointArn']}", ['Message' => $message, 'Exception' => $e, 'Endpoint' => $endpoint]);
             }
         } else {
             $this->logger && $this->logger->info("Disabled endpoint {$endpoint['EndpointArn']}", ['Message' => $message, 'Endpoint' => $endpoint]);
         }
     }
 }
 /**
  * @param $strAccountUrl
  * @param $strUserId
  * @param $strApplication
  * @param $strEndpoint
  * @param $arrJsonData
  * @throws \Exception (on missing parameters)
  * @throws Aws\Sns\Exception\SnsException (on method failure)
  */
 public function sendMessage($strAccountUrl, $strUserId, $strApplication, $strEndpoint, $arrJsonData)
 {
     if (empty($strAccountUrl)) {
         throw new \Exception('Missing Account URL');
     }
     if (empty($strUserId)) {
         throw new \Exception('Missing User ID');
     }
     if (empty($strApplication)) {
         throw new \Exception('Missing Application Name');
     }
     if (empty($strEndpoint)) {
         throw new \Exception('Missing URL Endpoint');
     }
     $strTarget = $this->_strTarget;
     $arrMessage = ['accounturl' => $strAccountUrl, 'userid' => $strUserId, 'application' => $strApplication, 'endpoint' => $strEndpoint];
     if (isset($arrJsonData)) {
         $arrJsonData = is_array($arrJsonData) ? json_encode($arrJsonData) : $arrJsonData;
         $arrMessage['json_data'] = $arrJsonData;
     }
     $client = SnsClient::factory($this->_arrCredentials);
     $arrMessage = json_encode(['default' => json_encode($arrMessage), 'lambda' => json_encode($arrMessage)]);
     $client->publish(['TargetArn' => $strTarget, 'MessageStructure' => 'json', 'Message' => $arrMessage]);
 }
Пример #24
0
$lastfmApi = "http://ws.audioscrobbler.com/2.0/?method=user.gettopalbums&user="******"&period=" . $request['period'] . "&api_key=" . $config['api_key'] . "&limit={$limit}&format=json";
$validUser = "******" . $request['user'] . "&api_key=" . $config['api_key'] . "&format=json";
//Check if a valid user
$infoJson = json_decode(getJson($validUser));
//If an error is thrown, generate an error image and exit
if (isset($infoJson->{"error"})) {
    header("Content-Type: image/png");
    error_log($infoJson->{"message"} . " - " . $request['user']);
    imagepng(errorImage($infoJson->{"message"}));
    $sns = SnsClient::factory(array('credentials.cache' => $cache, 'region' => 'eu-west-1'));
    $sns->publish(array('TopicArn' => 'arn:aws:sns:eu-west-1:346795263809:LastFM-Errors', 'Message' => $infoJson->{"message"} . " - " . $request['user'], 'Subject' => "Lastfm Error: " . $infoJson->{"error"}));
    return;
}
//Get User's albums and generate a MD5 hash based on this
$json = getJson($lastfmApi);
$sns = SnsClient::factory(array('credentials.cache' => $cache, 'region' => 'eu-west-1'));
$sns->publish(array('TopicArn' => 'arn:aws:sns:eu-west-1:346795263809:LastFM-API-CAlls', 'Message' => $json, 'Subject' => $user . "s JSON API Call"));
$jsonhash = md5($json);
//Cache based on user set variables and JSON hash
$filename = "images/{$user}.{$period}.{$rows}.{$cols}.{$albumInfo}.{$plays}.{$jsonhash}";
//if a previous file exists - request is cached, serve from cache and exit
if (file_exists($filename)) {
    header("Content-Type: image/jpeg");
    error_log("Serving from cache - " . $filename);
    echo file_get_contents($filename);
    exit;
}
//otherwise carry on and getAlbums from LastFM.
$albums = getAlbums(json_decode($json));
//Pass the Albums to getArt to download the art into a $covers array
$covers = getArt($albums, 3);
 public function boot()
 {
     $this->app->make('Illuminate\\Broadcasting\\BroadcastManager')->extend('sns', function ($app, $config) {
         return new SnsBroadcaster(SnsClient::factory(array('credentials' => array('key' => $config['aws_key'], 'secret' => $config['aws_secret']), 'version' => 'latest', 'region' => $config['aws_region'])));
     });
 }
Пример #26
0
 public function connect()
 {
     $this->_connection = SnsClient::factory($this->config);
     $this->connected = true;
 }
Пример #27
0
 /**
  * Returns a S3Client instance
  * @return \Aws\Sns\SnsClient
  */
 private function getClient()
 {
     if ($this->_client === null) {
         $this->_client = SnsClient::factory(['key' => $this->key, 'secret' => $this->secret, 'region' => $this->region]);
     }
     return $this->_client;
 }
 private function subscribePlatform($platform, $topic)
 {
     foreach ($this->sns->getListEndpointsByPlatformApplicationIterator(['PlatformApplicationArn' => $this->arns[$platform]]) as $endpoint) {
         $this->logger && $this->logger->info('Subscribing device to topic', ['device' => $endpoint['EndpointArn'], 'topic' => $topic, 'platform' => $platform]);
         $this->topics->registerDeviceOnTopic($endpoint['EndpointArn'], $topic);
     }
 }
 /**
  * @param mixed[] $args
  * @return Result
  * @throws ExceptionInterface
  */
 private function publishClaimCheck(array $args = [])
 {
     $claimCheckSerializer = $this->configuration->getClaimCheckSerializer();
     $message = array_key_exists('Message', $args) ? $args['Message'] : '';
     $claimCheck = $this->storeMessageInS3($message);
     $args['Message'] = $claimCheckSerializer->serialize($claimCheck);
     return $this->snsClient->publish($args);
 }
Пример #30
-1
 /**
  * @depends testCreatesTopic
  */
 public function testListsTopicAttributes($topicArn)
 {
     $result = $this->sns->getTopicAttributes(array('TopicArn' => $topicArn));
     $result = $result->toArray();
     // Ensure that the map was deserialized correctly
     $this->assertArrayHasKey('TopicArn', $result['Attributes']);
     $this->assertArrayHasKey('Policy', $result['Attributes']);
     $this->assertArrayHasKey('Owner', $result['Attributes']);
 }