Guest User

Untitled

a guest
Nov 10th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.15 KB | None | 0 0
  1. <?php
  2. namespace wcf\system\cronjob;
  3. use wcf\data\cronjob\Cronjob;
  4. use wcf\data\streaming\partner\StreamingPartnerAction;
  5. use wcf\data\streaming\partner\StreamingPartnerList;
  6. use wcf\util\HTTPRequest;
  7. use wcf\util\JSON;
  8. use wcf\util\StringUtil;
  9.  
  10. /**
  11.  * Refreshes stream data of streaming partners.
  12.  *
  13.  * @author  Sandro Geyer | Grischabock
  14.  * @copyright   GrischaMedia.ch
  15.  * @license All rights reserved
  16.  * @package WoltLabSuite\Core\System\Cronjob
  17.  */
  18. class StreamingPartnerRefreshStreamDataCronjob extends AbstractCronjob {
  19.     /**
  20.      * Twitch.tv API base url
  21.      * @var string
  22.      */
  23.     const API_BASE = 'https://api.twitch.tv/helix';
  24.    
  25.     /**
  26.      * @inheritDoc
  27.      */
  28.     protected $maxLifetime = 3600;
  29.    
  30.     /**
  31.      * Array of channel names
  32.      * @var array
  33.      */
  34.     public $channels = [];
  35.    
  36.     /**
  37.      * @inheritDoc
  38.      */
  39.     public function execute(Cronjob $cronjob) {
  40.         parent::execute($cronjob);
  41.        
  42.         if (!MODULE_STREAMING_PARTNER || StringUtil::trim(STREAMING_PARTNER_TWITCH_CLIENT_ID) == '') {
  43.             return;
  44.         }
  45.        
  46.         $this->getChannelNames();
  47.        
  48.         if (empty($this->channels)) {
  49.             return;
  50.         }
  51.        
  52.         $this->fetchChannelData();
  53.         $this->fetchStreamData();
  54.         $this->prepareData();
  55.         $this->updatePartners();
  56.     }
  57.    
  58.     /**
  59.      * Returns an array of Twitch.tv channel names
  60.      */
  61.     private function getChannelNames() {
  62.         $partnerList = new StreamingPartnerList();
  63.         $partnerList->readObjects();
  64.         $partners = $partnerList->getObjects();
  65.        
  66.         foreach ($partners as $partner) {
  67.             $channel = $partner->twitchUsername;
  68.             $name = StringUtil::trim(preg_replace('~https?://(?:www\.)twitch\.tv/(#?[a-zA-Z0-9][\w]{2,24}).*~i', '\1', mb_strtolower($channel)));
  69.            
  70.             if (!empty($name)) {
  71.                 $index = count($this->channels);
  72.                 $this->channels[$index] = ['data' => [
  73.                     'partnerID' => $partner->partnerID,
  74.                     'name' => $name
  75.                 ]];
  76.             }
  77.         }
  78.     }
  79.    
  80.     /**
  81.      * Fetches Twitch.tv channel data.
  82.      */
  83.     private function fetchChannelData() {
  84.         if (empty($this->channels)) {
  85.             return;
  86.         }
  87.        
  88.         foreach ($this->channels as $channelID => $channelData) {
  89.             try {
  90.                 $request = new HTTPRequest(self::API_BASE . '/channels/' . $channelData['data']['name'] . '?client_id=' . STREAMING_PARTNER_TWITCH_CLIENT_ID);
  91.                 $request->execute();
  92.                 $reply = $request->getReply();
  93.                 $channelData = JSON::decode(StringUtil::trim($reply['body']));
  94.             }
  95.             catch (\Exception $e) {
  96.                 // ignore
  97.             }
  98.            
  99.             if (!is_array($channelData) || empty($channelData['_id'])) {
  100.                 unset($this->channels[$channelID]);
  101.                 continue;
  102.             }
  103.            
  104.             // Remove unneccessary stuff
  105.             unset($channelData['_links']);
  106.            
  107.             $this->channels[$channelID]['data'] = array_merge($this->channels[$channelID]['data'], $channelData);
  108.         }
  109.     }
  110.    
  111.     /**
  112.      * Fetches Twitch.tv channel data.
  113.      */
  114.     private function fetchStreamData() {
  115.         if (empty($this->channels)) {
  116.             return;
  117.         }
  118.        
  119.         $channelNames = [];
  120.        
  121.         foreach ($this->channels as $channelID => $channelData) {
  122.             $channelNames[$channelID] = $channelData['data']['name'];
  123.         }
  124.        
  125.         foreach (array_chunk($channelNames, 25, true) as $channels) {
  126.             $streams = [];
  127.            
  128.             try {
  129.                 $request = new HTTPRequest(self::API_BASE . '/streams/?channel=' . implode(',', $channels) . '&client_id=' . STREAMING_PARTNER_TWITCH_CLIENT_ID);
  130.                 $request->execute();
  131.                 $reply = $request->getReply();
  132.                 $streams = JSON::decode(StringUtil::trim($reply['body']))['streams'];
  133.             }
  134.             catch (\Exception $e) {
  135.                 continue;
  136.             }
  137.            
  138.             if (!is_array($streams) || empty($streams)) {
  139.                 continue;
  140.             }
  141.            
  142.             foreach ($streams as $streamData) {
  143.                 if (empty($streamData['_id'])) {
  144.                     continue;
  145.                 }
  146.                
  147.                 $channelID = array_search($streamData['channel']['name'], $channels);
  148.                
  149.                 // Remove unneccessary stuff
  150.                 unset($streamData['_links']);
  151.                 unset($streamData['channel']);
  152.                
  153.                 if (isset($this->channels[$channelID])) {
  154.                     $this->channels[$channelID]['stream'] = $streamData;
  155.                 }
  156.             }
  157.         }
  158.     }
  159.    
  160.     /**
  161.      * Set stream status.
  162.      */
  163.     private function prepareData() {
  164.         if (empty($this->channels)) {
  165.             return;
  166.         }
  167.        
  168.         // set stream status
  169.         foreach ($this->channels as $k => $v) {
  170.             if (empty($v['stream']['_id'])) {
  171.                 $this->channels[$k]['stream']['status'] = 'offline';
  172.             }
  173.             else {
  174.                 $this->channels[$k]['stream']['status'] = 'online';
  175.             }
  176.         }
  177.     }
  178.    
  179.     /**
  180.      * Update partner stream data
  181.      */
  182.     private function updatePartners() {
  183.         if (empty($this->channels)) {
  184.             return;
  185.         }
  186.        
  187.         foreach ($this->channels as $partner) {
  188.             $lastStreamDate = [];
  189.            
  190.             if ($partner['stream']['status'] == 'online') {
  191.                 $lastStreamDate = ['lastStreamDate' => TIME_NOW];
  192.             }
  193.        
  194.             $objectAction = new StreamingPartnerAction([$partner['data']['partnerID']], 'update', ['data' => array_merge([
  195.                 'twitchUsername' => $partner['data']['display_name'],
  196.                 'followerCount' => $partner['data']['followers'],
  197.                 'streamStatus' => $partner['stream']['status'],
  198.                 'streamTitle' => !empty($partner['data']['status']) ? $partner['data']['status'] : '',
  199.                 'gameName' => !empty($partner['data']['game']) ? $partner['data']['game'] : '',
  200.                 'lastUpdate' => TIME_NOW
  201.             ], $lastStreamDate)]);
  202.             $objectAction->executeAction();
  203.         }
  204.     }
  205. }
Add Comment
Please, Sign In to add comment