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.

parsevideo.go 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package apijson
  2. import (
  3. "github.com/valyala/fastjson"
  4. "github.com/terorie/yt-mango/data"
  5. "errors"
  6. "io/ioutil"
  7. "net/http"
  8. )
  9. var missingData = errors.New("missing data")
  10. var unexpectedType = errors.New("unexpected type")
  11. func ParseVideo(v *data.Video, res *http.Response) error {
  12. defer res.Body.Close()
  13. // Download response
  14. body, err := ioutil.ReadAll(res.Body)
  15. if err != nil { return err }
  16. // Parse JSON
  17. var p fastjson.Parser
  18. root, err := p.ParseBytes(body)
  19. if err != nil { return err }
  20. rootArray := root.GetArray()
  21. if rootArray == nil { return unexpectedType }
  22. var videoDetails *fastjson.Value
  23. for _, sub := range rootArray {
  24. videoDetails = sub.Get("page", "playerResponse", "videoDetails")
  25. if videoDetails != nil { break }
  26. }
  27. keywords := videoDetails.GetArray("keywords")
  28. if keywords == nil { return missingData }
  29. for _, keywordValue := range keywords {
  30. keywordBytes, _ := keywordValue.StringBytes()
  31. if keywordBytes == nil { continue }
  32. keyword := string(keywordBytes)
  33. v.Tags = append(v.Tags, keyword)
  34. }
  35. titleBytes := videoDetails.GetStringBytes("title")
  36. if titleBytes != nil { v.Title = string(titleBytes) }
  37. return nil
  38. }