You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ids.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package api
  2. import (
  3. "regexp"
  4. "strings"
  5. "log"
  6. "net/url"
  7. )
  8. // FIXME: API package should be abstract, no utility code in here
  9. var matchChannelID = regexp.MustCompile("^([\\w\\-]|(%3[dD]))+$")
  10. var matchVideoID = regexp.MustCompile("^[\\w\\-]+$")
  11. // Input: Channel ID or link to YT channel page
  12. // Output: Channel ID or "" on error
  13. func GetChannelID(chanURL string) string {
  14. if !matchChannelID.MatchString(chanURL) {
  15. // Check if youtube.com domain
  16. _url, err := url.Parse(chanURL)
  17. if err != nil || (_url.Host != "www.youtube.com" && _url.Host != "youtube.com") {
  18. log.Fatal("Not a channel ID:", chanURL)
  19. return ""
  20. }
  21. // Check if old /user/ URL
  22. if strings.HasPrefix(_url.Path, "/user/") {
  23. // TODO Implement extraction of channel ID
  24. log.Print("New /channel/ link is required!\n" +
  25. "The old /user/ links do not work:", chanURL)
  26. return ""
  27. }
  28. // Remove /channel/ path
  29. channelID := strings.TrimPrefix(_url.Path, "/channel/")
  30. if len(channelID) == len(_url.Path) {
  31. // No such prefix to be removed
  32. log.Print("Not a channel ID:", channelID)
  33. return ""
  34. }
  35. // Remove rest of path from channel ID
  36. slashIndex := strings.IndexRune(channelID, '/')
  37. if slashIndex != -1 {
  38. channelID = channelID[:slashIndex]
  39. }
  40. return channelID
  41. } else {
  42. // It's already a channel ID
  43. return chanURL
  44. }
  45. }
  46. func GetVideoID(vidURL string) string {
  47. if !matchVideoID.MatchString(vidURL) {
  48. // Check if youtube.com domain
  49. _url, err := url.Parse(vidURL)
  50. if err != nil || (_url.Host != "www.youtube.com" && _url.Host != "youtube.com") {
  51. log.Fatal("Not a video ID:", vidURL)
  52. return ""
  53. }
  54. // TODO Support other URLs (/v or /embed)
  55. // Check if watch path
  56. if !strings.HasPrefix(_url.Path, "/watch") {
  57. log.Fatal("Not a watch URL:", vidURL)
  58. return ""
  59. }
  60. // Parse query string
  61. query := _url.Query()
  62. videoID := query.Get("v")
  63. if videoID == "" {
  64. log.Fatal("Invalid watch URL:", vidURL)
  65. return ""
  66. }
  67. return videoID
  68. } else {
  69. return vidURL
  70. }
  71. }