; youtube video search
; returns the first search result for your search terms
; usage for you
;
; trigger: /yt
; syntax: /yt <search terms>
; example: /yt charleston daft punk
; usage for other people
;
; triggers: !youtube @youtube !tube @tube
; syntax: @youtube <search terms>
; example: !tube charleston daft punk

; if you want to sort search by VIEW COUNT, use this line below
; sockwrite -nt $sockname GET /results?search_sort=video_view_count&search_query= $+ %yts.searchstring
;
; if you want the regular search, use this line below
; sockwrite -nt $sockname GET /results?search_query= $+ %yts.searchstring HTTP//1.1
;
; the place im referring to is: under the heading on *:sockopen:ytsearch:{
alias yt {
  %yts.channel = $chan
  if (%yts.channel) { %yts.saystyle = echo -t %yts.channel }
  else { %yts.saystyle = echo -at }
  %yts.searchstring = $replace($1-,$chr(32),+)
  sockclose ytsearch
  sockopen ytsearch www.youtube.com 80
}
on *:text:*:*: {
  ; youtube video search
  ; returns the first search result for your search terms
  if ( $regex($1-,/^[!@](yt|youtube) */Si) ) { 
    %yts.channel = $chan
    %yts.nick = $nick
    if (%yts.channel) { %yts.saystyle = /msg %yts.channel }
    if (%yts.channel == $null && %yts.nick) { %yts.saystyle = /msg %yts.nick }
    %yts.searchstring = $replace($2-,$chr(32),+)
    if ($2 == $null) { %yts.saystyle Search could not be completed | halt }
    sockclose ytsearch
    sockopen ytsearch www.youtube.com 80
  }
}
on *:sockopen:ytsearch:{
  sockwrite -nt $sockname GET /results?search_query= $+ %yts.searchstring HTTP//1.1
  sockwrite -nt $sockname Host: youtube.com 
  sockwrite -nt $sockname $crlf $crlf 
}
on *:sockread:ytsearch:{
  sockread -n %yts.temp
  if (%yts.founddesc_be) { unset %yts.founddesc_be | %yts.desc_be = $replace($replace($replace($remove(%yts.temp,<b>,</b>, ),<br/>,$chr(32)),&quot;,$chr(34)),&#39;,') }
  if (<span id="BeginvidDesc isin %yts.temp) %yts.founddesc_be = k
  if (*<a href="/watch?v=* iswm %yts.temp) { %yts.resulturl = $remove($gettok(%yts.temp,2,32),href=",") }
  if (<a class="newvtitlelink" isin %yts.temp) { %yts.searchtitle = $replace($replace($remove($regsubex(%yts.temp,/<a [^>]+>(.+?)</a>/,1),<b>,</b>,<br/>, ),&quot;,$chr(34)),&#39;,') }
  if (<img class="rating icn_star_full_11x11gif" isin %yts.temp) { %yts.done = k }  
  if (%yts.done) {
    sockclose ytsearch
    unset %yts.done
    %yts.saystyle Link: http://www.youtube.com $+ %yts.resulturl
    %yts.saystyle Title: http://www.youtube.com $+ %yts.resulturl
    %yts.saystyle Description: http://www.youtube.com $+ %yts.resulturl
    unset %yts.*
    halt
  }
  if (*No Videos found* iswm %yts.temp) {
    sockclose ytsearch
    %yts.saystyle No videos found for %yts.searchstring
    unset %yts.*
    halt
  }
  if (*start search results* iswm %yts.temp) { %yts.searchres = 0  }  
  if (*<a href="/watch?v=* iswm %yts.temp) { inc %yts.searchres }
}
