« UNIXコマンドの実行 | トップページ | rectangle 矩形指定でスクリーンキャプチャーを取得する »

[Youtube]YoutubeのURLからチャンネルIDを取得する


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
(*
API
https://developers.google.com/youtube/v3
コンソール
https://console.cloud.google.com/apis/dashboard?pli=1
*)
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807
property strVideoID : (missing value)
property strPlayListID : (missing value)
property strChannelID : (missing value)
property strUserID : (missing value)
property strCustomUrl : (missing value)
############設定項目 
####API ID
property strAPIkey : "ここにAPIキー" as text

########################
## クリップボードの中身取り出し
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
log "テキストなし"
    set strReadString to "YouTubeのビデオURLを入力" as text
  end if
end if

########################
##ダイアログを前面に出す
set strName to (name of current application) as text
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
########################
##ダイアログ
set aliasIconPath to (POSIX file "/System/Library/CoreServices/Tips.app/Contents/Resources/AppIcon.icns") as alias
set strTitle to ("入力してください") as text
set strMes to ("YouTubeURLを入力してください\r") as text
set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)
if (gave up of recordResult) is true then
return "時間切れです"
else if (button returned of recordResult) is "キャンセル" then
return "キャンセルです"
else
  set strReturnedText to (text returned of recordResult) as text
end if
set ocidReturnedText to refMe's NSString's stringWithString:(strReturnedText)
########################
##改行を取る
set ocidURLStr to ocidReturnedText's stringByReplacingOccurrencesOfString:("\r") withString:("")
set ocidURLStr to ocidURLStr's stringByReplacingOccurrencesOfString:("\n") withString:("")
########################
##NSURLに
set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLStr)
##NSURLComponentsに分解
set ocidURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidURL) resolvingAgainstBaseURL:(true)
########################
##以下はチャンネルと関係ない
##ホスト判定
set strHost to ocidURL's |host|() as text
if strHost is not "www.youtube.com" then
return "Youtube URL 専用"
end if
##パスで判定
set strPath to ocidURL's |path|() as text
if strPath starts with "/feed" then
return "feedぺージは処理しない"
else if strPath starts with "/results" then
return "resultsぺージは処理しない"
else if strPath starts with "/hashtag" then
return "hashtagぺージは処理しない"
else if strPath is "" then
return "トップぺージは処理しない"
else if strPath is "/" then
return "トップぺージは処理しない"
end if

########################
##クエリーの有無をチェック
set recordRange to ocidURLComponents's rangeOfQuery()
set ocidLocation to location of recordRange
log ocidLocation ≠ refNSNotFound
if ocidLocation ≠ refNSNotFound then
  ########################
  ##【Aクエリーあり】
  set ocidQueryArray to ocidURLComponents's queryItems
  ##【Aー1】ラストパスで判定
  set strLastPath to ocidURL's lastPathComponent() as text
  ##【Aー1−1】ビデオ再生のwatchの場合
  if strLastPath is "watch" then
    ##queryItemsから各種ID
    repeat with itemQuery in ocidQueryArray
      set strQueryName to itemQuery's |name| as text
      if strQueryName is "v" then
        #再生中ビデオID
        set strVideoID to itemQuery's value as text
      else if strQueryName is "list" then
        #プレイリストのID
        set strPlayListID to itemQuery's value as text
      else if strQueryName is "index" then
        #プレイリストの曲順番号
        set strPlayListIndex to itemQuery's value as text
      end if
    end repeat
    ##【Aー1−2】プレイリスト画面の場合
  else if strLastPath is "playlist" then
    repeat with itemQuery in ocidQueryArray
      set strQueryName to itemQuery's |name| as text
      if strQueryName is "list" then
        #プレイリストのID
        set strPlayListID to itemQuery's value as text
      end if
    end repeat
  end if
else
  ########################
  ##【Bクエリー無し】
  if strPath starts with "/shorts" then
    set strVideoID to ocidURL's lastPathComponent() as text
  else if strPath starts with "/channel" then
    set strChannelID to ocidURL's lastPathComponent() as text
  else if strPath starts with "/@" then
    set ocidPathStr to refMe's NSString's stringWithString:(strPath)
    set ocidPathArray to ocidPathStr's componentsSeparatedByString:("/")
    set ocidCustomUrl to (ocidPathArray's objectAtIndex:(1))
    set strUserID to ocidCustomUrl's stringByReplacingOccurrencesOfString:("@") withString:("")
    set strCustomUrl to strUserID as text
  else if strPath starts with "/user/" then
    set ocidPathStr to refMe's NSString's stringWithString:(strPath)
    set ocidPathArray to ocidPathStr's componentsSeparatedByString:("/")
    set ocidCustomUrl to (ocidPathArray's objectAtIndex:(2))
    set strUserID to ocidCustomUrl as text
  else if strPath starts with "/c/" then
    set ocidPathStr to refMe's NSString's stringWithString:(strPath)
    set ocidPathArray to ocidPathStr's componentsSeparatedByString:("/")
    set ocidCustomUrl to (ocidPathArray's objectAtIndex:(2))
    set strCustomUrl to ocidCustomUrl as text
  end if
end if

########################
##APIURL 


if strVideoID ≠ (missing value) then
  #ビデオIDが見つかった場合のクエリー
  set strBaseURL to ("https://www.googleapis.com/youtube/v3/videos") as text
  set ocidBaseURLStr to refMe's NSString's stringWithString:(strBaseURL)
  set ocidBaseURL to refMe's NSURL's alloc()'s initWithString:(ocidBaseURLStr)
  set ocidBaseURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidBaseURL) resolvingAgainstBaseURL:(true)
  set ocidQueryArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("part") value:("snippet")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("id") value:(strVideoID)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("key") value:(strAPIkey)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("maxResults") value:("50")
ocidQueryArray's addObject:(ocidQueryItem)
  ###
else if strChannelID ≠ (missing value) then
  #チャンネルIDからユーザーIDを取得する場合
  set strBaseURL to ("https://www.googleapis.com/youtube/v3/channels") as text
  set ocidBaseURLStr to refMe's NSString's stringWithString:(strBaseURL)
  set ocidBaseURL to refMe's NSURL's alloc()'s initWithString:(ocidBaseURLStr)
  set ocidBaseURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidBaseURL) resolvingAgainstBaseURL:(true)
  set ocidQueryArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("part") value:("snippet")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("id") value:(strChannelID)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("key") value:(strAPIkey)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("maxResults") value:("50")
ocidQueryArray's addObject:(ocidQueryItem)
else if strUserID ≠ (missing value) then
  #ユーザーIDからチャンネルIDを検索
  set strBaseURL to ("https://www.googleapis.com/youtube/v3/search") as text
  set ocidBaseURLStr to refMe's NSString's stringWithString:(strBaseURL)
  set ocidBaseURL to refMe's NSURL's alloc()'s initWithString:(ocidBaseURLStr)
  set ocidBaseURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidBaseURL) resolvingAgainstBaseURL:(true)
  set ocidQueryArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("part") value:("snippet")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("q") value:(strUserID)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("type") value:("channel")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("key") value:(strAPIkey)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("maxResults") value:("1")
ocidQueryArray's addObject:(ocidQueryItem)
else if strCustomUrl ≠ (missing value) then
  #ユーザーIDからチャンネルIDを検索
  set strBaseURL to ("https://www.googleapis.com/youtube/v3/search") as text
  set ocidBaseURLStr to refMe's NSString's stringWithString:(strBaseURL)
  set ocidBaseURL to refMe's NSURL's alloc()'s initWithString:(ocidBaseURLStr)
  set ocidBaseURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidBaseURL) resolvingAgainstBaseURL:(true)
  set ocidQueryArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("part") value:("snippet")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("q") value:(strCustomUrl)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("type") value:("channel")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("key") value:(strAPIkey)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("maxResults") value:("1")
ocidQueryArray's addObject:(ocidQueryItem)
else if strPlayListID ≠ (missing value) then
  #playlistsからチャンネルIDを取得
  set strBaseURL to ("https://www.googleapis.com/youtube/v3/playlists") as text
  set ocidBaseURLStr to refMe's NSString's stringWithString:(strBaseURL)
  set ocidBaseURL to refMe's NSURL's alloc()'s initWithString:(ocidBaseURLStr)
  set ocidBaseURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidBaseURL) resolvingAgainstBaseURL:(true)
  set ocidQueryArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("part") value:("id,snippet,status")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("id") value:(strPlayListID)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("key") value:(strAPIkey)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("maxResults") value:("1")
ocidQueryArray's addObject:(ocidQueryItem)
end if

########################
##APIを呼び出すURL
ocidBaseURLComponents's setQueryItems:(ocidQueryArray)
set ocidOpenURL to ocidBaseURLComponents's |URL|()
set strOpenURL to ocidOpenURL's absoluteString() as text
log "呼び出したURL: " & strOpenURL

########################
##Get JSON
### 【1】JSONのURL
set ocidApiURL to ocidOpenURL
### 【2】URLの内容JSONをNSdataに格納
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidApiURL) options:(ocidOption) |error|:(reference)
set ocidReadData to (item 1 of listReadData)
### 【3】NSPropertyListSerializationしてレコードに
set ocidOption to (refMe's NSJSONReadingMutableContainers)
set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
set ocidPlistDict to item 1 of listJSONSerialization
##
set ocidItemsArray to (ocidPlistDict's valueForKey:("items"))
repeat with itemItemsDict in ocidItemsArray
  set ocidSnipetDict to (itemItemsDict's valueForKey:("snippet"))
  set ocidChannelID to (ocidSnipetDict's valueForKey:("channelId"))
  set ocidUserID to (ocidSnipetDict's valueForKey:("customUrl"))
  if ocidChannelID = (missing value) then
    set ocidChannelID to (itemItemsDict's valueForKey:("id"))
  end if
end repeat


################################
##ユーザーIDが取得出来なかった場合用
if ocidUserID = (missing value) then
  set strBaseURL to ("https://www.googleapis.com/youtube/v3/channels") as text
  set ocidBaseURLStr to refMe's NSString's stringWithString:(strBaseURL)
  set ocidBaseURL to refMe's NSURL's alloc()'s initWithString:(ocidBaseURLStr)
  set ocidBaseURLComponents to refMe's NSURLComponents's componentsWithURL:(ocidBaseURL) resolvingAgainstBaseURL:(true)
  set ocidQueryArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("part") value:("snippet")
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("id") value:(ocidChannelID)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("key") value:(strAPIkey)
ocidQueryArray's addObject:(ocidQueryItem)
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("maxResults") value:("50")
ocidQueryArray's addObject:(ocidQueryItem)
  ####
ocidBaseURLComponents's setQueryItems:(ocidQueryArray)
  set ocidOpenURL to ocidBaseURLComponents's |URL|()
  set strOpenURL to ocidOpenURL's absoluteString() as text
log "呼び出したURL: " & strOpenURL
  ### 【2】URLの内容JSONをNSdataに格納
  set ocidOption to (refMe's NSDataReadingMappedIfSafe)
  set listReadData to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidOpenURL) options:(ocidOption) |error|:(reference)
  set ocidReadData to (item 1 of listReadData)
  ### 【3】NSPropertyListSerializationしてレコードに
  set ocidOption to (refMe's NSJSONReadingMutableContainers)
  set listJSONSerialization to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidReadData) options:(ocidOption) |error|:(reference))
  set ocidPlistDict to item 1 of listJSONSerialization
  ##
  set ocidItemsArray to (ocidPlistDict's valueForKey:("items"))
  repeat with itemItemsDict in ocidItemsArray
    set ocidSnipetDict to (itemItemsDict's valueForKey:("snippet"))
    set ocidChannelID to (ocidSnipetDict's valueForKey:("channelId"))
    set ocidUserID to (ocidSnipetDict's valueForKey:("customUrl"))
    set strCustomUrl to ocidUserID as text
  end repeat
  
  
end if


########################
log "チャンネルID: " & ocidChannelID as text
log "ユーザーID: " & ocidUserID as text
log "カスタムチャンネルID: " & strCustomUrl as text

return


|

« UNIXコマンドの実行 | トップページ | rectangle 矩形指定でスクリーンキャプチャーを取得する »

YouTube」カテゴリの記事