<commit_before><?php

namespace Garbetjie\WeChatClient\Media;

use DateTime;
use Garbetjie\WeChatClient\Media\Exception\MediaException;
use Garbetjie\WeChatClient\Media\ItemType\ArticleMedia;
use Garbetjie\WeChatClient\Media\ItemType\ArticleMediaItem;
use Garbetjie\WeChatClient\Media\ItemType\LocalMedia;
use Garbetjie\WeChatClient\Media\ItemType\RemoteMedia;
use Garbetjie\WeChatClient\Service;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use InvalidArgumentException;

class MediaService extends Service
{
    /**
     * Uploads the supplied media item to the WeChat API.
     *
     * This method assumes that the item has not been uploaded previously, and so will ignore any previously created
     * date and media id that has been set. The supplied media item will be modified.
     *
     * @param LocalMedia|ArticleMedia $mediaItem
     *
     * @return RemoteMedia
     *
     * @throws InvalidArgumentException
     * @throws MediaException
     */
    public function uploadTemporaryItem ($mediaItem)
    {
        // Must be a local media item or an article media item.
        $this->ensureMediaItem($mediaItem);

        if ($mediaItem instanceof ArticleMedia) {
            return $this->uploadArticle('https://api.weixin.qq.com/cgi-bin/media/uploadnews', $mediaItem);
        } else {
            return $this->uploadFile('http://api.weixin.qq.com/cgi-bin/media/upload', $mediaItem);
        }
    }
    
    private function ensureMediaItem ($mediaItem)
    {
        if (! ($mediaItem instanceof LocalMedia || $mediaItem instanceof ArticleMedia)) {
            throw new InvalidArgumentException(
                sprintf(
                    "unexpected value %s%s given as media item for upload.",
                    gettype($mediaItem),
                    is_object($mediaItem) ? " (" . get_class($mediaItem) . ")" : ''
                )
            );
        }
    }
    
    public function uploadPermanentItem ($mediaItem)
    {
        // Must be a local media item or an article media item.
        $this->ensureMediaItem($mediaItem);

        if ($mediaItem instanceof ArticleMedia) {
            return $this->uploadArticle('https://api.weixin.qq.com/cgi-bin/material/add_news', $mediaItem);
        } else {
            return $this->uploadFile('https://api.weixin.qq.com/cgi-bin/material/add_material', $mediaItem);
        }
    }

    /**
     * Uploads the given media file to the WeChat content servers, and populates the item's ID and created date.
     *
     * @param LocalMedia $media
     *
     * @return RemoteMedia
     *
     * @throws InvalidArgumentException
     */
    protected function uploadFile ($endpoint, LocalMedia $media)
    {
        if ($media->getPath() === null) {
            throw new InvalidArgumentException("path not set when uploading media item. cannot upload.");
        }

        $stream = fopen($media->getPath(), 'rb');
        if (! $stream) {
            throw new InvalidArgumentException("unable to open `{$media->getPath()}` for reading.");
        }

        $json = json_decode(
            $this->client->send(
                new Request(
                    'POST',
                    Uri::withQueryValue(new Uri($endpoint), 'type', $media->getType()),
                    [],
                    new MultipartStream ([
                        [
                            'name'     => 'media',
                            'contents' => $stream,
                        ],
                    ])
                )
            )
        );

        $mediaID = $media->getType() == MediaType::THUMBNAIL ? $json->thumb_media_id : $json->media_id;
        $uploadDate = DateTime::createFromFormat('U', $json->created_at);

        return (new RemoteMedia($media->getType(), $mediaID))->withLastModifiedDate($uploadDate);
    }

    /**
     * Uploads the given news article items to the WeChat content servers, and populates the media item's ID and created
     * date.
     *
     * @param ArticleMedia $media
     *
     * @return RemoteMedia
     *
     * @throws MediaException
     */
    protected function uploadArticle ($endpoint, ArticleMedia $media)
    {
        $jsonBody = [
            'articles' => [],
        ];

        foreach ($media->getItems() as $item) {
            $article = [
                'title'          => $item->getTitle(),
                'content'        => $item->getContent(),
                'thumb_media_id' => $item->getThumbnailMediaID(),
            ];<commit_msg>Fixed incorrect return value being passed to json_decode<commit_after><?php

namespace Garbetjie\WeChatClient\Media;

use DateTime;
use Garbetjie\WeChatClient\Media\Exception\MediaException;
use Garbetjie\WeChatClient\Media\ItemType\ArticleMedia;
use Garbetjie\WeChatClient\Media\ItemType\ArticleMediaItem;
use Garbetjie\WeChatClient\Media\ItemType\LocalMedia;
use Garbetjie\WeChatClient\Media\ItemType\RemoteMedia;
use Garbetjie\WeChatClient\Service;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use InvalidArgumentException;

class MediaService extends Service
{
    /**
     * Uploads the supplied media item to the WeChat API.
     *
     * This method assumes that the item has not been uploaded previously, and so will ignore any previously created
     * date and media id that has been set. The supplied media item will be modified.
     *
     * @param LocalMedia|ArticleMedia $mediaItem
     *
     * @return RemoteMedia
     *
     * @throws InvalidArgumentException
     * @throws MediaException
     */
    public function uploadTemporaryItem ($mediaItem)
    {
        // Must be a local media item or an article media item.
        $this->ensureMediaItem($mediaItem);

        if ($mediaItem instanceof ArticleMedia) {
            return $this->uploadArticle('https://api.weixin.qq.com/cgi-bin/media/uploadnews', $mediaItem);
        } else {
            return $this->uploadFile('http://api.weixin.qq.com/cgi-bin/media/upload', $mediaItem);
        }
    }
    
    private function ensureMediaItem ($mediaItem)
    {
        if (! ($mediaItem instanceof LocalMedia || $mediaItem instanceof ArticleMedia)) {
            throw new InvalidArgumentException(
                sprintf(
                    "unexpected value %s%s given as media item for upload.",
                    gettype($mediaItem),
                    is_object($mediaItem) ? " (" . get_class($mediaItem) . ")" : ''
                )
            );
        }
    }
    
    public function uploadPermanentItem ($mediaItem)
    {
        // Must be a local media item or an article media item.
        $this->ensureMediaItem($mediaItem);

        if ($mediaItem instanceof ArticleMedia) {
            return $this->uploadArticle('https://api.weixin.qq.com/cgi-bin/material/add_news', $mediaItem);
        } else {
            return $this->uploadFile('https://api.weixin.qq.com/cgi-bin/material/add_material', $mediaItem);
        }
    }

    /**
     * Uploads the given media file to the WeChat content servers, and populates the item's ID and created date.
     *
     * @param LocalMedia $media
     *
     * @return RemoteMedia
     *
     * @throws InvalidArgumentException
     */
    protected function uploadFile ($endpoint, LocalMedia $media)
    {
        if ($media->getPath() === null) {
            throw new InvalidArgumentException("path not set when uploading media item. cannot upload.");
        }

        $stream = fopen($media->getPath(), 'rb');
        if (! $stream) {
            throw new InvalidArgumentException("unable to open `{$media->getPath()}` for reading.");
        }

        $json = json_decode(
            $this->client->send(
                new Request(
                    'POST',
                    Uri::withQueryValue(new Uri($endpoint), 'type', $media->getType()),
                    [],
                    new MultipartStream ([
                        [
                            'name'     => 'media',
                            'contents' => $stream,
                        ],
                    ])
                )
            )->getBody()
        );

        $mediaID = $media->getType() == MediaType::THUMBNAIL ? $json->thumb_media_id : $json->media_id;
        $uploadDate = DateTime::createFromFormat('U', $json->created_at);

        return (new RemoteMedia($media->getType(), $mediaID))->withLastModifiedDate($uploadDate);
    }

    /**
     * Uploads the given news article items to the WeChat content servers, and populates the media item's ID and created
     * date.
     *
     * @param ArticleMedia $media
     *
     * @return RemoteMedia
     *
     * @throws MediaException
     */
    protected function uploadArticle ($endpoint, ArticleMedia $media)
    {
        $jsonBody = [
            'articles' => [],
        ];

        foreach ($media->getItems() as $item) {
            $article = [
                'title'          => $item->getTitle(),
                'content'        => $item->getContent(),
                'thumb_media_id' => $item->getThumbnailMediaID(),
            ];
{'fraction_non_alphanumeric': 0.1129242819843342, 'fraction_numerical': 0.0006527415143603133, 'mean_word_length': 2.0674007340674008, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 60, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3485766', 'n_tokens_mistral': 2536, 'n_tokens_neox': 2440, 'n_words': 600}