Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace wcf\system\cronjob;
- use wcf\data\cronjob\Cronjob;
- use wcf\data\streaming\partner\StreamingPartnerAction;
- use wcf\data\streaming\partner\StreamingPartnerList;
- use wcf\util\HTTPRequest;
- use wcf\util\JSON;
- use wcf\util\StringUtil;
- class StreamingPartnerRefreshStreamDataCronjob extends AbstractCronjob {
- /**
- * Twitch.tv API base url
- * @var string
- */
- const API_BASE = 'https://api.twitch.tv/helix';
- /**
- * @inheritDoc
- */
- protected $maxLifetime = 3600;
- /**
- * Array of channel names
- * @var array
- */
- public $channels = [];
- /**
- * @inheritDoc
- */
- public function execute(Cronjob $cronjob) {
- parent::execute($cronjob);
- if (!MODULE_STREAMING_PARTNER || StringUtil::trim(STREAMING_PARTNER_TWITCH_CLIENT_ID) == '') {
- return;
- }
- $this->getChannelNames();
- if (empty($this->channels)) {
- return;
- }
- $this->fetchChannelData();
- $this->fetchStreamData();
- $this->prepareData();
- $this->updatePartners();
- }
- /**
- * Returns an array of Twitch.tv channel names
- */
- private function getChannelNames() {
- $partnerList = new StreamingPartnerList();
- $partnerList->readObjects();
- $partners = $partnerList->getObjects();
- foreach ($partners as $partner) {
- $channel = $partner->twitchUsername;
- $name = StringUtil::trim(preg_replace('~https?://(?:www\.)twitch\.tv/(#?[a-zA-Z0-9][\w]{2,24}).*~i', '\1', mb_strtolower($channel)));
- if (!empty($name)) {
- $index = count($this->channels);
- $this->channels[$index] = ['data' => [
- 'partnerID' => $partner->partnerID,
- 'name' => $name
- ]];
- }
- }
- }
- /**
- * Fetches Twitch.tv channel data.
- */
- private function fetchChannelData() {
- if (empty($this->channels)) {
- return;
- }
- foreach ($this->channels as $channelID => $channelData) {
- $request = new HTTPRequest(self::API_BASE . '/users/?id' . $channelData['data']['name'],
- [
- 'method' => 'GET'
- ],);
- $request->addHeader('Client-ID:', STREAMING_PARTNER_TWITCH_CLIENT_ID);
- $request->addHeader('Accept:', 'application/vnd.twitchtv.v5+json');
- try {
- $request->execute();
- }
- catch (HTTPException $e) {
- throw new SystemException("unexpected response from server: ".print_r($e->getExtraInformation(), 1), $e->getCode(), $e->getDescription(), $e);
- }
- $reply = $request->getReply();
- $channelData = JSON::decode(StringUtil::trim($reply['body']));
- if (!is_array($channelData) || empty($channelData['_id'])) {
- unset($this->channels[$channelID]);
- continue;
- }
- // Remove unneccessary stuff
- unset($channelData['_links']);
- $this->channels[$channelID]['data'] = array_merge($this->channels[$channelID]['data'], $channelData);
- }
- }
- /**
- * Fetches Twitch.tv channel data.
- */
- private function fetchStreamData() {
- if (empty($this->channels)) {
- return;
- }
- $channelNames = [];
- foreach ($this->channels as $channelID => $channelData) {
- $channelNames[$channelID] = $channelData['data']['name'];
- }
- foreach (array_chunk($channelNames, 25, true) as $channels) {
- $streams = [];
- $request = new HTTPRequest(self::API_BASE . '/streams/?login=' . implode('&login=', $channels),
- [
- 'method' => 'GET'
- ],);
- $request->addHeader('Client-ID', STREAMING_PARTNER_TWITCH_CLIENT_ID);
- $request->addHeader('Accept:', 'application/vnd.twitchtv.v5+json');
- try {
- $request->execute();
- }
- catch (HTTPException $e) {
- throw new SystemException("unexpected response from server: ".print_r($e->getExtraInformation(), 1), $e->getCode(), $e->getDescription(), $e);
- }
- $reply = $request->getReply();
- $streams = JSON::decode(StringUtil::trim($reply['body']))['streams'];
- if (!is_array($streams) || empty($streams)) {
- continue;
- }
- foreach ($streams as $streamData) {
- if (empty($streamData['_id'])) {
- continue;
- }
- $channelID = array_search($streamData['channel']['name'], $channels);
- // Remove unneccessary stuff
- unset($streamData['_links']);
- unset($streamData['channel']);
- if (isset($this->channels[$channelID])) {
- $this->channels[$channelID]['stream'] = $streamData;
- }
- }
- }
- }
- /**
- * Set stream status.
- */
- private function prepareData() {
- if (empty($this->channels)) {
- return;
- }
- // set stream status
- foreach ($this->channels as $k => $v) {
- if (empty($v['stream']['_id'])) {
- $this->channels[$k]['stream']['status'] = 'offline';
- }
- else {
- $this->channels[$k]['stream']['status'] = 'online';
- }
- }
- }
- /**
- * Update partner stream data
- */
- private function updatePartners() {
- if (empty($this->channels)) {
- return;
- }
- foreach ($this->channels as $partner) {
- $lastStreamDate = [];
- if ($partner['stream']['status'] == 'online') {
- $lastStreamDate = ['lastStreamDate' => TIME_NOW];
- }
- $objectAction = new StreamingPartnerAction([$partner['data']['partnerID']], 'update', ['data' => array_merge([
- 'twitchUsername' => $partner['data']['display_name'],
- 'followerCount' => $partner['data']['followers'],
- 'streamStatus' => $partner['stream']['status'],
- 'streamTitle' => !empty($partner['data']['status']) ? $partner['data']['status'] : '',
- 'gameName' => !empty($partner['data']['game']) ? $partner['data']['game'] : '',
- 'lastUpdate' => TIME_NOW
- ], $lastStreamDate)]);
- $objectAction->executeAction();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement