Sign up here and you can log into the forum!

Plugin: YouTube Subscriptions + new subscription videos

Discussion, features, plugins--everything about zoster's UMSP UPnP Media Server software

Plugin: YouTube Subscriptions + new subscription videos   

Postby dan » Wed Jun 02, 2010 12:50 pm

Note: This plugin has been discontinued due to Youtube's APIv2 being deprecated. This is the replacement plugin: Youtube3 http://forum.wdlxtv.com/viewtopic.php?f=53&t=9230&p=74638

Hi,

this plugin shows you a list of videos of your YouTube subscriptions and a combined list of all videos in chronological order (like the YT start page).

Features:
    * super fast list loading by using cron supported caching

Requirements:

Todo:
    * code cleanup
    * subscription artwork
    * use user authentication to avoid enabling account sharing

Thanks to the wdlxtv community for making this possible!


How to use the plugin:

1.) activate CROND by adding in /boot/S00custom-options
Code: Select all
config_tool -c CROND=ON

2.) run "crontab -e" via SSH and add:
Code: Select all
*/4   *   *   *   *   /usr/bin/php5-cgi /tmp/umsp-plugins/youtube-subscriptions/youtube-subscriptions-helper.php

3.) add those files:

/conf/umsp.php
Code: Select all
$myMediaItems[] = array(   
   'id'         => 'umsp://plugins/youtube-subscriptions?t='.microtime(),   #Attribute of item
   'parentID'      => '0',                     #Attribute of item
   'restricted'   => '1',                     #Attribute of item
   'dc:creator'   => 'myCreator',
   'dc:title'      => 'My YouTube Subscriptions',
   'dc:date'      => '2009-12-30',
   'upnp:author'   => 'myAuthor',
   'upnp:artist'   => 'myArtist',
   'upnp:album'   => 'myAlbum',
   'upnp:genre'   => 'myGenre',
   'upnp:length'   => '2:10:20',
   'desc'         => 'myDesc',
   'upnp:class'   => 'object.container',
   'upnp:album_art'=> '',
   'duration'      => 'myDur3',            #Attribute of res
   'size'         => 'mySize3',            #Attribute of res in bytes
   'bitrate'      => 'myBitr',            #Attribute of res
   'protocolInfo'   => '*:*:*:*',      #Attribute of res
   'resolution'   => 'myReso',            #Attribute of res
   'colorDepth'   => 'myColor',            #Attribute of res
);


/etc/umsp/plugins/youtube-subscriptions.php
Code: Select all
<?php
date_default_timezone_set('UTC');
define("PLUGIN_NAME",str_replace('.php','',basename(__file__)));
define("LOG_FILE",'/tmp/umsp-log.txt');
define("PROXY_URL","http://127.0.0.1/umsp/plugins/proxy.php");
define("YT_CACHE_FILE",'/tmp/youtube-subscriptions.cache');
set_time_limit(0);

function _pluginMain($prmQuery)
{
   l('_pluginMain',$prmQuery,microtime());
   $queryData = array();
   parse_str($prmQuery, $queryData);

   if (!is_file(YT_CACHE_FILE)) {
      $cmd = str_replace('.php','',__file__).'-helper.php';
      l("nohup {$cmd} 2> /dev/null & echo $!");
      shell_exec("nohup {$cmd} 2> /dev/null & echo $!");
      return array(array (
         'id'          => 'umsp://plugins/'.PLUGIN_NAME,
         'dc:title'       => "loading content...",
         'upnp:album_art'=> 'http://127.0.0.1/umsp/media/YouTube.png',
         'upnp:class'   => 'object.container',   
         'protocolInfo'   => '*:*:*:*'             
      ));
   }

   if (!isset($queryData['youtube_username'])) return _getUserList();

   switch($queryData['cmd']) {
      case 'overview':
         return _getOverview($queryData['youtube_username']);
      case 'new_subscription_videos':
         return _getNewSubscriptionVideos($queryData['youtube_username']);
      case 'subscription_videos':
         return _getSubscriptionVideos($queryData['youtube_username'], $queryData['user']);
   }
}

function _getUserList()
{
   $xml = simplexml_load_file('/conf/account_list.xml');
   $accounts = $xml->xpath('//service[@name="YOUTUBE"]/account');
   
   foreach($accounts as $account)
   {
      $data = array(   'youtube_username' => (string)$account->username,
                  'youtube_password' => (string)$account->password,
                  'cmd' => 'overview');

      $retMediaItems[] = array (
         'id'          => 'umsp://plugins/'.PLUGIN_NAME.'?' . http_build_query($data,'','&amp;'),
         'dc:title'       => (string)$account->username,
         'upnp:album_art'=> 'http://127.0.0.1/umsp/media/YouTube.png',
         'upnp:class'   => 'object.container',   
         'protocolInfo'   => '*:*:*:*'             
      );      
   }
   return $retMediaItems;
}

function _getOverview($youtube_username)
{
   $data = unserialize(file_get_contents('/tmp/youtube-subscriptions.cache'));
   $ud = &$data[ $youtube_username ];
   
   $dataString = array('youtube_username'=>$youtube_username,'cmd'=>'new_subscription_videos');
   $retMediaItems[] = array (
      'id'          => 'umsp://plugins/'.PLUGIN_NAME.'?' . http_build_query($dataString,'','&amp;'),
      'dc:title'       => "New Subscriptions Videos",
      'upnp:class'   => 'object.container',
      'upnp:album_art'=> $thumb_url,
      'protocolInfo'   => '*:*:*:*'
   );
   
   foreach($ud['subscriptions'] as $sub) {
      $dataString = array('youtube_username'=>$youtube_username,'cmd'=>'subscription_videos','user'=>$sub);
      $retMediaItems[] = array (
         'id'         => 'umsp://plugins/'.PLUGIN_NAME.'?' . http_build_query($dataString,'','&amp;'),
         'dc:title'      => $sub,
         'upnp:class'   => 'object.container',
         'upnp:album_art'=> $thumb_url,
         'protocolInfo'   => '*:*:*:*'
      );
   }
   return $retMediaItems;
}

function _getNewSubscriptionVideos($youtube_username) {
   $data = unserialize(file_get_contents('/tmp/youtube-subscriptions.cache'));
   $ud = &$data[ $youtube_username ];
   $retMediaItems = array();
   foreach($ud['new_subscription_videos'] as $v) {
      $dataString = array('video_id' => $v['id'] );
      $retMediaItems[] = array (
           'id'         => 'umsp://plugins/'.PLUGIN_NAME.'?' . $v['id'],
           'res'         => PROXY_URL . '?'.http_build_query($dataString,'','&amp;'),
           'dc:title'      => $v['user'].": ".$v['title'],
           'upnp:class'   => 'object.item.videoitem',
           'upnp:album_art'=> $thumb_url,
           'protocolInfo'   => 'http-get:*:video/*:*',
       );   
   }
   return $retMediaItems;
}

function _getSubscriptionVideos($youtube_username, $subscription)
{
   $data = unserialize(file_get_contents('/tmp/youtube-subscriptions.cache'));
   $ud = &$data[ $youtube_username ];
   
   l($youtube_username, $subscription,$ud['subscriptions_videos']);
   $retMediaItems = array();
   foreach($ud['subscriptions_videos'][ $subscription ] as $v) {
      $dataString = array('video_id' => $v['id'] );
      $retMediaItems[] = array (
           'id'         => 'umsp://plugins/'.PLUGIN_NAME.'?' . $v['id'],
           'res'         => PROXY_URL . '?'.http_build_query($dataString,'','&amp;'),
           'dc:title'      => $v['title'],
           'upnp:class'   => 'object.item.videoitem',
           'upnp:album_art'=> $thumb_url,
           'protocolInfo'   => 'http-get:*:video/*:*',
       );   
   }
   return $retMediaItems;
}

/**
* Debug Logs
* stops if last param is 1
*/
function l()
{
   $t = debug_backtrace();
   $args = func_get_args();
   ob_start();
   echo basename($t[0]["file"]).":{$t[0]["line"]} > ";
   var_dump($args);
   $data = ob_get_contents();
   ob_end_clean();
   file_put_contents(LOG_FILE,$data,FILE_APPEND);
   if(end($args) === 1) die;
}


/etc/umsp/plugins/youtube-subscriptions-helper.php
Code: Select all
#!/usr/bin/php5-cgi
<?php
define("LOG_FILE",'/tmp/umsp-log.txt');
set_time_limit(0);

$t = microtime(true);
main();
echo microtime(true) - $t;

function main()
{
   $user = _getUser();
   
   $user_data = array();

   foreach ($user as $u) {
      $us = _getUserSubscriptions($u['youtube_username'], $u['youtube_password']);
      $t = _getUserVideos($us,20);
      l(count($us));
      $user_data[ $u['youtube_username'] ]['new_subscription_videos'] = $t['videos'];
      $user_data[ $u['youtube_username'] ]['subscriptions_videos'] = $t['user_videos'];
      
      //remove subscriptions without any content
      $user_with_videos = array_keys($t['user_videos']);
      foreach($us as $k => $v) {
         if (!in_array($v, $user_with_videos))
            unset($us[ $k ]);
      }l(count($us));
      $user_data[ $u['youtube_username'] ]['subscriptions'] = $us;
   }
   
   file_put_contents('/tmp/youtube-subscriptions.cache',serialize($user_data));
}

function _getUserVideos(array $users, $count)
{
   $videos = array();
   $user_videos = array();
   foreach($users as $user)
   {
      $t = _get_youtube_feed("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$user}/uploads?orderby=published&max-results={$count}");
      $x = simplexml_load_string($t);
      if(!$x) {
         continue;
      }

      $x->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
      $entries = $x->xpath("//a:entry");

      foreach($entries as $t) {
         $ts = strtotime(substr($t->published, 0, 10).' '.substr($t->published, 11, 8));
         $vid = mb_substr($t->id,mb_strrpos($t->id,'/')+1,mb_strlen($t->id));
         $d = array(
            'user'=>$user,
            'title'=>(string)$t->title,
            'id'=>$vid,
             #'video_link'=>"http://www.youtube.com/watch?v={$vid}&t=&fmt=22",
            );
         $user_videos[ $user ][] = $d;
         $videos[ $ts ] = $d;
      }
   }
   
   foreach($user_videos as $k=>$v) {
      if (count($v) == 0) unset($user_videos[ $k ]);
   }

   krsort($videos);
   $videos = array_slice($videos,0,150,true);
   
   return array('videos'=>$videos, 'user_videos'=>$user_videos);
}


function _getUserSubscriptions($YouTubeUserName, $YouTubePassword)
{
   preg_match("/openSearch:totalResults>(\d+)</s",_get_youtube_feed("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$YouTubeUserName}/subscriptions?v=2&start-index=1&max-results=1"),$m);

   $total_subscriptions = $m[1];
   $subscriptions = array();
   $pr = 20;

   //get channels
   for($i=0;$i<(int)ceil($total_subscriptions/$pr);$i++) {

      $start = ($i*$pr) + 1;
      $t = _get_youtube_feed("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$YouTubeUserName}/subscriptions?v=2&start-index={$start}&max-results={$pr}");
      $x = simplexml_load_string($t);
      if(!$x) continue;

      $x->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
      $t = $x->xpath("//a:entry//a:title");
      foreach($t as $v) {
         preg_match("/:(.+)$/",$v,$s);
         $s = (string)trim($s[1]);
         if (!empty($s)) $subscriptions[] = $s;
         #break(2);
      }
   }
   natcasesort($subscriptions);
   return $subscriptions;   
}



function _getUser()
{
   $xml = simplexml_load_file('/conf/account_list.xml');
   $data = $xml->xpath('//service[@name="YOUTUBE"]/account');
   
   $accounts = array();
   
   foreach($data as $account)
   {
      $accounts[] = array('youtube_username' => (string)$account->username,
                     'youtube_password' => (string)$account->password);      
   }
   return $accounts;
}

/**
* Debug Logs
* stops if last param is 1
*/
function l()
{
   $t = debug_backtrace();
   $args = func_get_args();
   ob_start();
   echo basename($t[0]["file"]).":{$t[0]["line"]} > ";
   var_dump($args);
   $data = ob_get_contents();
   ob_end_clean();
   file_put_contents(LOG_FILE,$data,FILE_APPEND);
   if(end($args) === 1) die;
}

function _get_youtube_feed($ip,$host,$path)
{
   $fp = fsockopen($ip, 80, $errno, $errstr, 30);
   if (!$fp) {
       echo "$errstr ($errno)<br />\n";
   } else {
       $out = "GET {$path} HTTP/1.0\r\n";
       $out .= "Host: {$host}\r\n";
       $out .= "Connection: Close\r\n\r\n";
       fwrite($fp, $out);
      
      $content = '';
      $headerPassed = false;
       while (!feof($fp)) {
           $l = fgets($fp);
         if($l == "\r\n") $headerPassed = true;
         if($headerPassed) $content .= $l;
   
       }
       fclose($fp);

      preg_match("/(<\?.*>)/s",$content,$m);
      return trim($m[1]);
   }
}

?>


/etc/umsp/plugins/youtube-get-subscription-proxy.php
Code: Select all
<?php
// This code is assemled from b-rads youtubeHD.php and the apple-trailer.php supplied with UMSP //
#include_once('funcs-misc.php');
date_default_timezone_set('UTC');
define("PLUGIN_NAME",str_replace('.php','',basename(__file__)));
define("LOG_FILE",'/tmp/umsp-log.txt');
define("PROXY_URL","http://127.0.0.1/umsp/plugins/proxy.php");
set_time_limit(0);


function _pluginMain($prmQuery)
{
   #l('_pluginMain',$prmQuery,microtime());
   $queryData = array();
   parse_str($prmQuery, $queryData);

    if (isset($queryData['youtube_xmlfeed'])) {
      $items = _generateVideoList($queryData['youtube_xmlfeed']);
      return $items;
   }
   else
   {
      if (isset($queryData['youtube_username'])) return _getLatestSubscriptions($queryData['youtube_username'],$queryData['youtube_password']);
      else return $items = _getUser();
   }
}

function _getLatestSubscriptions($YouTubeUserName, $YouTubePassword)
{
   preg_match("/openSearch:totalResults>(\d+)</s",_get_youtube_feed("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$YouTubeUserName}/subscriptions?v=2&start-index=1&max-results=1"),$m);

   $total_subscriptions = $m[1];
   $subscriptions = array();
   $pr = 20;

   //get channels
   for($i=0;$i<(int)ceil($total_subscriptions/$pr);$i++) {

      $start = ($i*$pr) + 1;
      $t = _get_youtube_feed("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$YouTubeUserName}/subscriptions?v=2&start-index={$start}&max-results={$pr}");
      $x = simplexml_load_string($t);
      if(!$x) continue;

      $x->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
      $t = $x->xpath("//a:entry//a:title");
      foreach($t as $v) {
         preg_match("/:(.+)$/",$v,$s);
         $s = (string)trim($s[1]);
         if (!empty($s)) $subscriptions[] = $s;
         #break(2);
      }
   }

   //get user videos
   $videos = array();
   foreach($subscriptions as $sub)
   {
      $t = _get_youtube_feed("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$sub}/uploads?orderby=published&max-results=5");
      #die(get_url("74.125.39.118","gdata.youtube.com","/feeds/api/users/{$sub}/uploads?orderby=published&max-results=5"));
      $x = simplexml_load_string($t);
      if(!$x) {
         continue;
      }

      $x->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
      $entries = $x->xpath("//a:entry");

      foreach($entries as $t) {
         $ts = strtotime(substr($t->published, 0, 10).' '.substr($t->published, 11, 8));
         $vid = mb_substr($t->id,mb_strrpos($t->id,'/')+1,mb_strlen($t->id));
         $videos[ $ts ] = array(
            'user'=>$sub,
            'title'=>(string)$t->title,
            'id'=>$vid,
             'video_link'=>"http://www.youtube.com/watch?v={$vid}&t=&fmt=22",
            );
      }
   }

   krsort($videos);
   $videos = array_slice($videos,0,50,true);
   $retMediaItems = array();
   
   foreach($videos as $v)
   {
      $data = array('video_id' => $v['id'] );

      $retMediaItems[] = array (
           'id'         => 'umsp://plugins/'.PLUGIN_NAME.'?' . $v['id'],
           'res'         => PROXY_URL . '?'.http_build_query($data,'','&amp;'),
           'dc:title'      => $v['user'].": ".html_entity_decode(utf8_encode($v['title']),ENT_QUOTES, 'ISO-8859-15'),
           'upnp:class'   => 'object.item.videoitem',
           'upnp:album_art'=> $thumb_url,
           'protocolInfo'   => 'http-get:*:video/*:*',
       );
   }
   return $retMediaItems;
}

function _getUser()
{
   $xml = simplexml_load_file('/conf/account_list.xml');
   $accounts = $xml->xpath('//service[@name="YOUTUBE"]/account');
   
   foreach($accounts as $account)
   {
      $data = array(   'youtube_username' => (string)$account->username,
                  'youtube_password' => (string)$account->password);

      $retMediaItems[] = array (
         'id'          => 'umsp://plugins/'.PLUGIN_NAME.'?' . http_build_query($data,'','&amp;'),
         'dc:title'       => (string)$account->username,
         'upnp:album_art'=> 'http://127.0.0.1/umsp/media/YouTube.png',
         'upnp:class'   => 'object.container',   
         'protocolInfo'   => '*:*:*:*'             
      );      
   }
   return $retMediaItems;
}




function _generateSubscriptions($YouTubeUserName, $YouTubePassword)
{
   /*
   curl \
     --location https://www.google.com/youtube/accounts/ClientLogin \
     --data 'Email=testuser&Passwd=testpw&service=youtube&source=Test' \
     --header 'Content-Type:application/x-www-form-urlencoded'
   */
   

   #$userAuthResonse = do_post_request('https://www.google.com/youtube/accounts/ClientLogin',"Email={$YouTubeUserName}&Passwd={$YouTubePassword}&service=youtube&source=WDLive");
   #preg_match("/Auth=([a-z0-9_\-]+)/i", $userAuthResonse, $matches);
   #$userAuth = $matches[1];
   
   #l($userAuth);
   /*
   $header = array("Authorization: GoogleLogin auth=" . $userAuth,
                "GData-Version: 3.0",);

            $opts = array(
              'http'=>array(
                'method'=>"GET",
                'header'=>   "Content-Type: application/x-www-form-urlencoded\r\n" .
                        "Authorization: GoogleLogin auth=" . $userAuth."\r\n" .
                             "X-GData-Key: key=AOuj_Ro5qJP5oked_1To2qf5c4szbRRq0QCE88bHOG_vvltKLqQfov0qBPmpUGU7SQZOAMCdKyIeZsSYN-pFZqfSWKTR0TDnh0223DxoxMbyJ6NgvzbC_Ds\r\n"
              )
            );

            //$context = stream_context_create($opts);
*/
            // Open the file using the HTTP headers set above
            #$file = file_get_contents('http://gdata.youtube.com/feeds/base/users/google/subscriptions?start-index=1&max-results=2?key=AI39si51B11qtCIyZTWIyc4M0k5TvVPlLIWy0NVBSGl_9p1wIN9-sHh9RT3ZucCwQQ4unywx3BlgZkVUwCIdYjy-Jg-aW1SsEg');
$file = file_get_contents('http://gdata.youtube.com/feeds/base/users/google/subscriptions?start-index=1&max-results=2','r');
l($file,microtime());
return;

   $userAuthResonse = do_post_request('http://gdata.youtube.com/feeds/api/users/default/newsubscriptionvideos',join("\r\n",$header),join("\r\n",$header));
   l($userAuthResonse);
   return;

   
   //$url = "http://gdata.youtube.com/feeds/api/users/" . $YouTubeUserName . "/subscriptions?v=2";
    //l($Rec_Data);


$reader = new XMLReader();
    $url = "http://gdata.youtube.com/feeds/api/users/" . $YouTubeUserName . "/subscriptions?v=2";
    // As documented in - http://code.google.com/intl/sv-SE/apis/youtube/2.0/reference.html#Subscriptions_Feed - Must be PUBLIC!
    $stationlistXML = file_get_contents($url);

    $reader->XML($stationlistXML);
    while ($reader->read()) {   
        if (($reader->nodeType == XMLReader::ELEMENT) && ($reader->localName == 'entry')) {
            do {
                $reader->read();
                if ($reader->name == "yt:username") {
                    $reader->read();
                    if ($reader->nodeType == XMLReader::TEXT) {
                        $chan_owner = $reader->value;
                        $YouTube_XMLFeed = "http://gdata.youtube.com/feeds/api/videos?author=" . $chan_owner . "&orderby=published";
                    } # end if
                } #end if
                if ($reader->localName == "thumbnail") {
                    $thumb_url = $reader->getAttribute('url');
                }
            }
            while (!(($reader->nodeType == XMLReader::END_ELEMENT) && ($reader->localName == 'entry')));
            $data = array(
            'chan_owner'       => $chan_owner,
            'thumb_url'           => $thumb_url,
                'youtube_xmlfeed'   => $YouTube_XMLFeed
         );
         $dataString = http_build_query($data, 'pluginvar_');
         $retMediaItems[] = array (
            'id'          => 'umsp://plugins/'.PLUGIN_NAME.'?' . $dataString,
            'dc:title'       => $chan_owner,
            'upnp:class'   => 'object.container',
            'upnp:album_art'=> $thumb_url,
                'protocolInfo'   => '*:*:*:*'
         );           
        } # end if
    }; #end while
    return $retMediaItems;
} # end function

function _generateVideoList($YoutubeXMLFeed) { 
   
    $reader = new XMLReader();
_var_dump_to_file($YoutubeXMLFeed);
    $stationlistXML = file_get_contents($YoutubeXMLFeed);   
    $reader->XML($stationlistXML);
   while ($reader->read()) {   
      if (($reader->nodeType == XMLReader::ELEMENT) && ($reader->localName == 'entry')) {
         do {
            $reader->read();
                if (($reader->localName == "player") && ($reader->getAttribute('yt:format') == 3)) {
                        $mov_xml_url  = $reader->getAttribute('url');
                        $html = file_get_contents($mov_xml_url);
                        if(preg_match('/"video_id": "(.*?)"/', $html, $id) && preg_match('/"t": "(.*?)"/', $html, $t) && preg_match('/"fmt_map": "(.*?)"/', $html, $fmt_map)) {
                            $var_id = $id[1];
                            $var_t  = $t[1];
                            $var_fmt_map = $fmt_map[1];
                            $quality = "270P";
                            if (file_exists('/conf/config')) {
                                $config = file_get_contents('/conf/config');
                                if(preg_match('/YOUTUBE_QUALITY=\'(.+)\'/', $config, $config_quality)) {
                                    $quality = $config_quality[1];
                                }
                            }
                            $quality_map = array('1080P' => 37, '720P' => 22, '480P' => 35, '360P' => 34, '270P' => 18);
                            $quality_map_values = array_values($quality_map);
                            foreach (split(",",urldecode($var_fmt_map)) as $key) {
                                list($current_list[],$rest) = split("/",$key,2);
                            }
                            $index = array_search($quality_map[$quality], $quality_map_values);
                            while (!in_array($quality_map_values[$index], $current_list) && ($index < (count($quality_map_values) - 1))) {
                                $index++;
                            }
                            $quality = $quality_map_values[$index];
                            $mov_url = "http://www.youtube.com/watch?v=".$var_id."&t=".$var_t."&fmt=".$quality;
                    }
                        if ($reader->localName == "title") {
                            $reader->read();
                        if ($reader->nodeType == XMLReader::TEXT) {
                            $mov_title = $reader->value;
                        } # end if
                        }
                    if ($reader->localName == "player") {
                            $reader->read();
                            if ($reader->nodeType == XMLReader::TEXT) {
                                $video_id = $reader->value;
                            }
                    }
                        if ($reader->localName == "thumbnail") {
                            $thumb_url = $reader->getAttribute('url');
                        }
                    }
                } while (!(($reader->nodeType == XMLReader::END_ELEMENT) && ($reader->localName == 'entry')));
                $_SESSION['id_' . str_replace("-","_",$mov_id)] = $mov_url;
                 
                $data = array(
                    'mov_id'   => $mov_id,
                    'mov_url'   => $mov_url
                );
                     
                $dataString = http_build_query($data, 'pluginvar_');

                $retMediaItems[] = array (
                    'id'             => 'umsp://plugins/'.PLUGIN_NAME.'?' . $dataString,
                    'res'            => $proxyUrl.'?'.$dataString,
                    'dc:title'          => $mov_title,
                    'upnp:class'      => 'object.item.videoitem',
                    'upnp:album_art'   => $thumb_url,
                    'protocolInfo'     => 'http-get:*:video/*:*',
                );
_var_dump_to_file($retMediaItems);
            } // end if
    }; // end while
    return $retMediaItems;
} // end function


/**
* HELPER FUNCTIONS
*/

//Thanks to http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);

  $fp = fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

function _get_youtube_feed($ip,$host,$path)
{
   $fp = fsockopen($ip, 80, $errno, $errstr, 30);
   if (!$fp) {
       echo "$errstr ($errno)<br />\n";
   } else {
       $out = "GET {$path} HTTP/1.0\r\n";
       $out .= "Host: {$host}\r\n";
       $out .= "Connection: Close\r\n\r\n";
       fwrite($fp, $out);
      
      $content = '';
      $headerPassed = false;
       while (!feof($fp)) {
           $l = fgets($fp);
         if($l == "\r\n") $headerPassed = true;
         if($headerPassed) $content .= $l;
   
       }
       fclose($fp);

      preg_match("/(<\?.*>)/s",$content,$m);
      return trim($m[1]);
   }
}



function _getYTVideo($id)
{
   $c = file_get_contents("http://www.youtube.com/watch?v={$id}&fmt=22");

   preg_match("/\&t=([^(\&|$)]*)/", $c, $m);
   $ticket = $m[1];

   preg_match("/\&fmt_url_map=([^(\&|$)]*)/", $c, $m);

   $formats = explode('%2C',$m[1]);

   $data = array();
   foreach($formats as $v) {
      $t = explode('%7C',$v);
      if ($t[0] == 37) continue;
      $data[ $t[0] ] = urldecode($t[1]);
   }
   
   return !empty($data)?reset($data):array();
}


/**
* Debug Logs
* stops if last param is 1
*/
function l()
{
   $t = debug_backtrace();
   $args = func_get_args();
   ob_start();
   echo basename($t[0]["file"]).":{$t[0]["line"]} > ";
   var_dump($args);
   $data = ob_get_contents();
   ob_end_clean();
   file_put_contents(LOG_FILE,$data,FILE_APPEND);
   if(end($args) === 1) die;
}
?>


4.) run "reboot" via SSH

Now you are set and ready to check out your latest YT subscription videos.

Feedback is welcome :P
Last edited by dan on Sat Aug 14, 2010 3:08 pm, edited 1 time in total.
dan
Developer
 
Posts: 40
Joined: Fri May 28, 2010 11:35 pm

Re: [PLUGIN] YouTube Subscriptions + new subscription videos   

Postby absorber123 » Thu Jun 03, 2010 11:59 pm

Hi Dan,

I followed the procedure, if you click on You tube subscriptions in UMSP, its displaying "loading content... windows".

I checked umsp-log.txt in /tmp folder, the errors are as below,

youtube-subscriptions.php:11 > array(3) {
[0]=>
string(11) "_pluginMain"
[1]=>
string(22) "t=0.95952100 946685481"
[2]=>
string(20) "0.38230700 946685487"
}
youtube-subscriptions.php:17 > array(1) {
[0]=>
string(79) "nohup /etc/umsp/plugins/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}
youtube-subscriptions.php:11 > array(3) {
[0]=>
string(11) "_pluginMain"
[1]=>
NULL
[2]=>
string(20) "0.62263300 946685490"
}
youtube-subscriptions.php:17 > array(1) {
[0]=>
string(79) "nohup /etc/umsp/plugins/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}


What must have went wrong, I could not trace out.

Please do the needful
absorber123
n00b
 
Posts: 14
Joined: Sun May 09, 2010 12:00 pm

Re: [PLUGIN] YouTube Subscriptions + new subscription videos   

Postby dan » Fri Jun 04, 2010 3:54 am

Hi absorber123,

if you have a lot of subscriptions it takes a little longer to fetch all your subscriptions. After a few minutes press the home buttom on your remote to refresh your menu cache, then go back to your subscription page and you should see your subscriptions.

May I ask how many subscriptions you have?
dan
Developer
 
Posts: 40
Joined: Fri May 28, 2010 11:35 pm

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby kandukuriv » Sat Jul 10, 2010 12:12 pm

I am also getting the same error.
youtube-subscriptions.php:11 > array(3) {
[0]=>
string(11) "_pluginMain"
[1]=>
string(22) "t=0.16112300 946684897"
[2]=>
string(20) "0.37415400 946684903"
}
youtube-subscriptions.php:17 > array(1) {
[0]=>
string(79) "nohup /etc/umsp/plugins/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}
youtube-subscriptions.php:11 > array(3) {
[0]=>
string(11) "_pluginMain"
[1]=>
NULL
[2]=>
string(20) "0.12835600 946684908"
}
youtube-subscriptions.php:17 > array(1) {
[0]=>
string(79) "nohup /etc/umsp/plugins/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}
youtube-subscriptions.php:11 > array(3) {
[0]=>
string(11) "_pluginMain"
[1]=>
string(22) "t=0.57704900 946685186"
[2]=>
string(20) "0.35251500 946685191"
}
youtube-subscriptions.php:17 > array(1) {
[0]=>
string(79) "nohup /etc/umsp/plugins/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}
youtube-subscriptions.php:11 > array(3) {
[0]=>
string(11) "_pluginMain"
[1]=>
NULL
[2]=>
string(20) "0.69191400 946685192"
}
youtube-subscriptions.php:17 > array(1) {
[0]=>
string(79) "nohup /etc/umsp/plugins/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}


I have only 4 subscriptions in my account. can you please help me to fix this
kandukuriv
n00b
 
Posts: 2
Joined: Sun Jul 04, 2010 6:56 pm

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby jeppe » Fri Jul 30, 2010 4:58 am

Hi,

For some reason I can't get this to work properly.

I can see the list of my subscriptions, new subscriptions included and all, but when I try to
play on of these videos, I can only get an error:

" Unable to play the selected file. Please refer to the user manual for a list of supported file formats"

Any ideas where the error might be?

Thanks.
jeppe
n00b
 
Posts: 1
Joined: Fri Jul 30, 2010 4:47 am

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby balthazar » Sat Aug 07, 2010 8:25 am

Some commenting in this code would be great as the errors it produces are pretty useless in telling you what failed, as opposed to just the general area in which something happened that maybe failed, or maybe completed but didn't do anything.
balthazar
n00b
 
Posts: 16
Joined: Fri Aug 06, 2010 6:21 pm

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby balthazar » Sat Aug 14, 2010 12:41 pm

So can anyone get this to work? If so, how, if not, why is it being included?

It just hangs at "loading content..." (I have three subscriptions) and if I create the cache file manually it never populates it.

The code comments and logging are a joke. It tells you what step its on, but not what the result was, and therefore why it failed.
balthazar
n00b
 
Posts: 16
Joined: Fri Aug 06, 2010 6:21 pm

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby dan » Sat Aug 14, 2010 1:07 pm

it's working perfectly. did you enable YT account sharing? whats in your /tmp/youtube-subscriptions.cache?

balthazar wrote:The code comments and logging are a joke.

feel free to add / improve the code / comments / logging...
dan
Developer
 
Posts: 40
Joined: Fri May 28, 2010 11:35 pm

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby balthazar » Sat Aug 14, 2010 4:11 pm

Yes and nothing. It wont even create the file, I have to create it manually. I have no other UMSP plugins manually entered, I copied and pasted the code above (with opening and closing php tags of course).

If I create the file, it does nothing. php error log shows an error on foreach (line, 96 I believe, in the main script) when pulling from the file (because it's empty) but it never populates the cache. Even if I let it sit for an hour.

The only other things I've ever done to my config are switching to/from YouTubeHD. Oh and changed the root password, otherwise...

As for your suggestion. I guess I COULD comment your code, but that seems like a) a somewhat less than useful suggestion b) asking for trouble since, you know, I didn't write it, so I'd have to go through line by line and try to keep it all straight.
balthazar
n00b
 
Posts: 16
Joined: Fri Aug 06, 2010 6:21 pm

Re: Plugin: YouTube Subscriptions + new subscription videos   

Postby balthazar » Sat Aug 14, 2010 4:17 pm

Code: Select all
youtube-subscriptions.php:14 > array(3) {
  [0]=>
  string(11) "_pluginMain"
  [1]=>
  string(22) "t=0.56662200 946723733"
  [2]=>
  string(20) "0.23929000 946723901"
}
youtube-subscriptions.php:20 > array(1) {
  [0]=>
  string(101) "nohup /tmp/umsp-plugins/youtube-subscriptions/youtube-subscriptions-helper.php 2> /dev/null & echo $!"
}


Look familiar? Same error everyone else in the thread has.
balthazar
n00b
 
Posts: 16
Joined: Fri Aug 06, 2010 6:21 pm

Next

Return to UMSP Media Server

Who is online

Users browsing this forum: No registered users and 3 guests