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