Advertisement
Guest User

Untitled

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