2014-03-27 5 views
0

비디오 픽커 앱 (LockeVN : https://github.com/lockevn/YouTube-video-picker)을 사용 중이며 YouTube 웹 사이트 (또는 github의 다른 검색 앱)에있는 것처럼 결과가 표시되지 않습니다. .Youtube Api JSON이 결과를 잘못 정렬합니다.

예 : 다음과 같이 입력하십시오. 'Bizarre Inc feat Angie Brown I 'm Gonna Get You'. YouTube에서 내가 처음 접하는 비디오는 'Bizarre Inc feat Angie Brown - 나는 너를 얻을거야 (1992)'입니다. 나는 비디오 선택기 응용 프로그램에서 얻을 첫 번째 비디오는 '엽기 INC - 내가 곧 당신에게 (SAVERY & MILLER 매시업 MIX) GET 'M'

참고 : 모두이 때 I = 관련성 및 비디오 순서 변경을 ORDERBY하도록 설정되어 최대 결과를 변경하십시오; max-result가 1로 설정된 경우에만 결과가 올바르게 정렬됩니다.

누구든지이 문제를 해결할 수 있습니다.

CODE :

(function ($) { 
$.fn.YouTubePicker = function (options) { 
    // default option 
    var defaults = { 
     MaxResults: 10          /* number of YouTube results, per "page" */ 
     , OrderBy: 'relevance'          /* what to order the results by */ 
     , Author: null          /* Author of the video */ 

     , PlayerNumberOp: 1 

     , ShowNumOfViews: true        /* show number of views for the video */ 
     , Thumbnail: 'small'        /* small: 120x90 | large: 480 x 360 */ 

     , ControlIdSuffix: ''       /* should give the unique string here if you have multiply of YouTubePicker. 
                  Using elements in this plugin will fetch by "id + ControlIdSuffix" */ 
     , ControlQueryHolder: '.YouTubePickerQuery'    /* selector to take a element to be query holder (where we take string to query                 YouTube) */ 
     , ControlSearchButton: '.YouTubePickerSearch'   /* selector to take a element to be SearchButton. Click this element to start search. */ 
     , ControlVideoPlayerHolder: '.YouTubePickerVideoPlayer' /* selector to take a element to render VideoPlayer */ 
     , ControlVideoTitleHolder: '.YouTubePickerVideoTitle' 
     , ControlVideoList: '.YouTubePickerVideoList'   /* selector to take a element to render VideoList */ 
     , ControlSelectedUrlHolder: '.YouTubePickerSelectedUrl' /* When user click to select a video, assign the video's url to this input */ 

     , InitVideoUrl: ''         /* Init if no search query existed, you can put YouTubeVideoId here or the full Url */ 
     , PlayerWidth: '240'        /* setting for player */ 
     , PlayerHeight: '220'        /* setting for player */ 
     , AutoPlay: false         /* AutoPlay video right after user click an item in the list */ 
     , ShowRelated: false         /* show relate video after finish playing */ 
     , AllowFullScreen: true       /* enable FullScreen button of Player */ 
     , EnableJsApi: true        /* enable Javascript Api*/ 
    }; 
    options = $.extend(defaults, options); 

    return this.each(function() { 
     var $container = $(this); 

     $(options.ControlSearchButton).click(function() { 
      /// <summary> 
      /// handler click on search button 
      /// </summary> 

      var requestUrl = 'http://gdata.YouTube.com/feeds/api/videos?alt=json&max-results=' + options.MaxResults; 
      try { 
       _RequestYouTubeVideos(requestUrl); 
      } catch (ex) { } 

      return false; 
     }); 

     $(options.ControlQueryHolder).keydown(function (event) { 
      /// <summary> 
      /// handler press Enter in query textbox 
      /// </summary> 

      if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { 
       $(options.ControlSearchButton).trigger('click'); 
       return false; 
      } 
      else { 
       return true; 
      } 
     }); 

     //-------------------------------------------------------// 
     // take the init video and play it if any 

     // ERASED THIS PART 
     // $(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(options.InitVideoUrl))); 
     // _AssignValueToDivOrTextBox(options.ControlSelectedUrlHolder, options.InitVideoUrl); 


     $('a.navigation').click(function() { 
      /// <summary> 
      /// rebind the list whenever user click to change page 
      /// </summary> 
      try { 
       _RequestYouTubeVideos($(this).attr('href')); 
      } catch (ex) { } 

      return false; 
     }); 


     /** 
     * Util function, assign value to element. Element can be div, span, or input 
     */ 
     function _AssignValueToDivOrTextBox(selectorToElement, valueToAssign) { 
      try { 
       $(selectorToElement).val(valueToAssign); 
      } catch (ex) { } 
      try { 
       $(selectorToElement).text(valueToAssign); 
      } catch (ex) { } 
     } 


     function _RequestYouTubeVideos(requestUrl) { 
      /// <summary> 
      /// fire the jsonp request to get data from YouTube Search API 
      /// </summary> 
      var query = $(options.ControlQueryHolder).val(); 
      if (options.Author != null) { 
       requestUrl += '&author=' + options.Author; 
      } 
      if (options.OrderBy != null) { 
       requestUrl += '&orderby=' + options.OrderBy; 
      } 
      if (query != null) { 
       requestUrl += '&q=' + query; 
      } 

      $.ajax({ 
       type: "GET", 
       url: requestUrl, 
       cache: false, 
       dataType: 'jsonp', 
       global: false, 
       success: _OnYouTubeSuccess, 
       error: function (result) { 
        $(options.ControlVideoList).html('<p>Please fill in a search term</p>'); 
       } 
        , 
       ajaxComplete: function (data) { 
        return false; 
       } 
      }); 
     } 


     function _BuildNavigation(feed) { 
      /// <summary> 
      /// Build the navigation link Prev and Next base on the return url in the feed (if existed) 
      /// </summary> 
      if (feed.link) { 
       var nextLink = null; 
       var prevLink = null; 

       for (var i = 0; i < feed.link.length; i++) { 
        var link = feed.link[i]; 
        if (link.rel == 'next') { 
         nextLink = link.href; 
        } 
        else if (link.rel == 'previous') { 
         prevLink = link.href; 
        } 
       } 

       if (nextLink) { 
        $('.navigation.next').attr('href', nextLink).show(); 
       } 
       else { 
        $('.navigation.next').hide(); 
       } 
       if (prevLink) { 
        $('.navigation.prev').attr('href', prevLink).show(); 
       } 
       else { 
        $('.navigation.prev').hide(); 
       } 
      } 
     } 

     function formatSecondsAsTime(secs) { 
     var hr = Math.floor(secs/3600); 
     var min = Math.floor((secs - (hr * 3600))/60); 
     var sec = Math.floor(secs - (hr * 3600) - (min * 60)); 

     if (hr < 10) { 
     hr = "0" + hr; 
     } 
     if (min < 10) { 
     min = "0" + min; 
     } 
     if (sec < 10) { 
     sec = "0" + sec; 
     } 
     if (hr) { 
     hr = "00"; 
     } 

     return hr + ':' + min + ':' + sec; 
     } 

     function _ParseYouTubeFeedItem(feedData) { 
      /// <summary> 
      /// Extract what we want from YouTube feedData     
      /// </summary> 
      var dto = []; 

      dto.id = _StripFeature(feedData.link[0].href.substring(feedData.link[0].href.indexOf('=') + 1, feedData.link[0].href.length)); 
      dto.url = feedData.link[0].href; 
      dto.title = feedData.title.$t; 
      if (options.Thumbnail == 'large') { 
       var index = 0; // first thumb is large size 
      } else { 
       var index = feedData.media$group.media$thumbnail.length - 1; // take the last small thumb 
      } 
      dto.thumbnail = feedData.media$group.media$thumbnail[index].url; 
      dto.description = feedData.media$group.media$description.$t; 
      dto.author = feedData.author[0].name.$t; 
      dto.duration = formatSecondsAsTime(feedData.media$group.media$content[0].duration); 

      if (feedData.yt$statistics) { 
       dto.views = feedData.yt$statistics.viewCount; 
      } 
      else if (!feedData.yt$statistics) { 
       dto.views = '0'; 
      } 

      return dto; 
     } 


     /** 
     * Process the json result, render the list 
     */ 
     function _OnYouTubeSuccess(result) { 
      var feed = result.feed; 
      var rfeed = feed.entry || []; 
      var relVideos = []; 

      var $ctrVideoList = $(options.ControlVideoList); 

      // build the navigation 
      _BuildNavigation(feed); 

      if (rfeed.length > 0) { 
       $(rfeed).each(function (i) { 
        /// <summary> 
        /// from feeditem from YouTube, build the video data object 
        /// </summary> 

        relVideos[i] = _ParseYouTubeFeedItem(rfeed[i]); 

       }).ready(function() { 
        relVideos.sort(_ArraySort); 
        var $itemsHtml = $('<div>'); // temporary DOM node to append VideoItem to 

        $(relVideos).each(function (i) { 
         /// <summary> 
         /// Create each list item 
         /// </summary> 

         $itemsHtml.append('<li class="VideoItem">'); 
         videoItem = $itemsHtml.find('.VideoItem:last'); 

         videoItem.append('<div class="VideoThumb">'); 
         videoThumb = videoItem.find('.VideoThumb'); 
         $('<a>').addClass('YouTubelink').attr('href', relVideos[i].url).append('<img src="' + relVideos[i].thumbnail + '">').appendTo(videoThumb); 

         videoItem.append('<div class="VideoInfo">'); 
         videoInfo = videoItem.find('.VideoInfo'); 
         videoInfo.append('<a href="' + relVideos[i].url + '" title="' + relVideos[i].description + '" class="VideoTitle YouTubelink"><strong>' + relVideos[i].title + ' </strong><br /><span class="VideoNumOfViews">' + relVideos[i].views + ' views</span><br /><span></span>' + relVideos[i].duration + '<br /></a>'); 


        }); 

        // clear the list 
        $ctrVideoList.empty().append($itemsHtml.children()); 
       }); 



       // load inital video after finish rendering the list 
       // take the first video in the list, take it link, take it href, assign to the Player 

       // ERASED THIS PART 
       //var firstVid = $ctrVideoList.children("li:first-child").addClass("selected").find("a").eq(1).attr("href"); 
       //$(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(firstVid))); 


       $ctrVideoList.find("li a").unbind('click').bind('click', function() { 

        /// <summary> 
        /// load video on click of a in li 
        /// </summary> 
        try { 
         var selectedUrl = $(this).attr("href"); 

         // return the selectedUrl to outside (try catch to avoid error in IE) 
         _AssignValueToDivOrTextBox(options.ControlSelectedUrlHolder, selectedUrl); 

         $(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(selectedUrl))); 

         // DIT IS EEN TEST 
         $(options.ControlVideoTitleHolder + "").html(_GetTitleHtml(_GetYouTubeIdFromUrl(selectedUrl))); 

         $(this).parent().parent().parent("ul").find("li.selected").removeClass("selected"); 
         $(this).parent().parent("li").addClass("selected"); 
        } catch (ex) { } 

        return false; 
       }); 

      } else { 
       /* if we have no YouTube videos returned, let's tell user */ 
       $ctrVideoList.html('<p>There is no result</p>'); 
      } 
     } // end _OnYouTubeSuccess 




     function _ArraySort(a, b) { 
      if (a.title < b.title) { 
       return -1; 
      } 
      else if (a.title > b.title) { 
       return 1; 
      } 
      else { 
       return 0; 
      } 
     } 

     function _StripFeature(vidID) { 
      var featureLoc = vidID.indexOf('&feature=YouTube_gdata'); 
      if (featureLoc >= 0) { 
       return vidID.substring(0, featureLoc); 
      } else { 
       return vidID; 
      } 
     } 


     /** 
     * Create a Player HTML code to play an YouTubeID, and return it HTML string 
     */ 
     function _GetPlayerHtml(YouTubeVideoId) { 
      // if YouTubeVideoId is null or empty, we provide an empty div with same dimension of the Player 
      // This will fix a bug of IE (IE will load the swf forever if object movie is empty and/or embbed src is empty    
      if (!YouTubeVideoId) { 
       return '<div style="width:240px;height:220px">'; 
      } 

      var html = ''; 
      var PlayerNumber = options.PlayerNumberOp; 

      html += '<object height="220" width="240">'; 
      html += '<param name="movie" value="http://www.YouTube.com/v/'+YouTubeVideoId+'?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"> </param>'; 
      html += '<param name="wmode" value="transparent"> </param>'; 
      // I HAVE CHANGED THIS 
      html += '<iframe onload="floaded'+PlayerNumber+'()" id="player'+PlayerNumber+'" width="240" height="220" src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen> </iframe>'; 
      html += '</object>'; 

      return html; 
     }; 

     function _GetTitleHtml(YouTubeVideoId) { 

      var html = ''; 
      var PlayerNumber = options.PlayerNumberOp; 

     $.getJSON('http://gdata.youtube.com/feeds/api/videos/'+YouTubeVideoId+'?v=2&alt=jsonc',function(data,status,xhr){ 

     var video_title1=data.data.title; 
     var finaltext1="<div id='title1'><h5 class='redtext'>USER SELECTED</h5><h5>"+video_title1+"</h5></div>"; 
     $('#YouTubePickerVideoTitle'+PlayerNumber+'').html(finaltext1); 

     }); 

      return html; 
     }; 


     function _GetYouTubeIdFromUrl(url) { 
      /// <summary> 
      /// use RegEx too grab a YouTube id from a (clean, no querystring) url (thanks to  http://jquery-howto.blogspot.com/2009/05/jYouTube-jquery-YouTube-thumbnail.html) 
      /// <return>empty string if cannot match.</return> 
      /// </summary> 
      if (url && url != '') { 
       try { 
        var ytid = url.match("[\\?&]v=([^&#]*)"); 
        ytid = ytid[1]; 
        return ytid; 
       } 
       catch (ex) { } 
      } 
      return ''; 
     }; 
    }); 
}; 
})(jQuery); 

답변

0

니즈.

잘 모르겠지만 Youtube는 환경 설정을 사용하여 비디오 검색을 필터링합니다.

다른 종류의 필터를 사용해보고 얻은 것을 확인하십시오.

+0

나는 그렇지 않다고 생각합니다. 예를 들면 : lucasmonteverde (https://github.com/lucasmonteverde/Youtube-Live-Search)의 Youtube Live Search와 같은 다른 앱을 사용할 때 이것은 아닙니다. 문제 –

+0

또한 최대 결과를 변경할 때 결과의 순서가 변경되며 10에서 5 또는 5에서 1로 말할 수 있습니다. 나는 꽤 이상하다고 생각하는 마녀 –

관련 문제