<?php


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Aws\CloudFront\CloudFrontClient;
use Aws\Credentials\Credentials;

// Download：https://github.com/aliyun/openapi-sdk-php
// Usage：https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
class CdnRefresh
{
    const accessKeyId = "LTAI4G6in86ShrwQDAvGgatS";
    const accessKeySecret = "Q8Nz6U5fxMfbYGNl1zR3EpPEvQWNOy";
    const AliyunCdnUrl = "https://coin.gworldtek.com";

    const AWSCdnUrl = "https://d2svcr1pzfa3gs.cloudfront.net/";
    const AWSCDNDistributionId="E38Q9KCU1R69A7";
    const AWSCNDKeyId = "AKIASBFCV66S6L7LJ6WR";
    const AWSCNDSecret = "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";
    private function action($action, $param)
    {
        AlibabaCloud::accessKeyClient(self::accessKeyId, self::accessKeySecret)->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('DCdn')
                // ->scheme('https') // https | http
                ->regionId('us-east-1')
                ->version('2018-01-15')
                ->action($action)
                ->method('POST')
                ->host('dcdn.aliyuncs.com')
                ->options($param)
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
            return $e->getErrorMessage();
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
            return $e->getErrorMessage();
        }
    }

    /**
     * 刷新目录
     * @param $dir
     * @return array
     * Created by: wsc
     * Created on: 2023/02/2 19:11
     */
    static function refreshDir($dir)
    {
        $result = [];
        $dir = "/public/game/" . $dir;
        $awsDomains = [
            self::AWSCdnUrl => [
                'DistributionId' => self::AWSCDNDistributionId,
                'key' => self::AWSCNDKeyId,
                'secret' => self::AWSCNDSecret,
            ],
        ];
        foreach ($awsDomains as $domain => $accessConfig) {
            $credentials = new Aws\Credentials\Credentials($accessConfig['key'], $accessConfig['secret']);
            $config['credentials'] = $credentials;
            $config['version'] = '2020-05-31';
            $config['version'] = '2019-03-26';
            $config['region'] = 'us-east-1';
            $client = new CloudFrontClient($config);
            $params = [
                'DistributionId' => $accessConfig['DistributionId'],
                'InvalidationBatch' => [
                    'CallerReference' => time(), // REQUIRED
                    'Paths' => [ // REQUIRED
                        'Items' => [$dir . '*'],
                        'Quantity' => 1, // REQUIRED
                    ],
                ],
            ];
            $res = $client->createInvalidation($params);
            $metadata = $res->get('@metadata');

            if ($metadata['statusCode'] == 201) {
                $result[$domain] = [
                    'RequestId' => $metadata['headers']['x-amzn-requestid']
                ];
            } else {
                $result[$domain] = [];
            }
        }
        $domains = [
            self::AliyunCdnUrl,
        ];
        foreach ($domains as $domain) {
            $result[$domain . $dir] = self::action('RefreshDcdnObjectCaches', [
                'query' => [
                    'ObjectPath' => self::AliyunCdnUrl . $dir,
                    'ObjectType' => "Directory",
                ],
            ]);
        }
        return $result;
    }

    /**
     * 刷新路径
     * @param $url
     * @return array
     * Created by: wsc
     * Created on: 2023/02/2 19:11
     */
    static function refreshUrl($file)
    {
        $file = "/public/game/{$file}";
        $awsDomains = [
            self::AWSCdnUrl => [
                'DistributionId' => self::AWSCDNDistributionId,
                'key' => self::AWSCNDKeyId,
                'secret' => self::AWSCNDSecret,
            ],
        ];
        foreach ($awsDomains as $domain => $accessConfig) {
            $credentials = new Aws\Credentials\Credentials($accessConfig['key'], $accessConfig['secret']);
            $config['credentials'] = $credentials;
            $config['version'] = '2020-05-31';
            $config['version'] = '2019-03-26';
            $config['region'] = 'us-east-1';
            $client = new CloudFrontClient($config);
            $params = [
                'DistributionId' => $accessConfig['DistributionId'],
                'InvalidationBatch' => [
                    'CallerReference' => time(), // REQUIRED
                    'Paths' => [ // REQUIRED
                        'Items' => [$file . '*'],
                        'Quantity' => 1, // REQUIRED
                    ],
                ],
            ];
            $res = $client->createInvalidation($params);
            $metadata = $res->get('@metadata');

            if ($metadata['statusCode'] == 201) {
                $result[$domain] = [
                    'RequestId' => $metadata['headers']['x-amzn-requestid']
                ];
            } else {
                $result[$domain] = [];
            }
        }
        return self::action('RefreshDcdnObjectCaches', [
            'query' => [
                'ObjectPath' => self::AliyunCdnUrl . $file,
                'ObjectType' => "File",
            ],
        ]);
    }

    /**
     * 预热路径
     * @param $url
     * @return array
     * Created by: Owen
     * Created on: 2021/3/13 17:12
     */
    static function PushUrl($url)
    {
        return self::action('PreloadDcdnObjectCaches', [
            'query' => [
                'ObjectPath' => $url,
                'ObjectType' => "File",
            ],
        ]);
    }
}