forked from Kethsar/ytarchive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netscape_cookies.go
102 lines (85 loc) · 2.02 KB
/
netscape_cookies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"bufio"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"strconv"
"strings"
"time"
"golang.org/x/net/publicsuffix"
)
const (
CookieDomain = iota
CookieHostOnly
CookiePath
CookieSecure
CookieExpiration
CookieName
CookieValue
CookiePieces
)
func (di *DownloadInfo) ParseNetscapeCookiesFile(fname string) (*cookiejar.Jar, error) {
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
return nil, err
}
file, err := os.Open(fname)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
cookieMap := make(map[string][]*http.Cookie)
for scanner.Scan() {
// Could move everything in this loop into its own function
cookieParts := strings.Split(scanner.Text(), "\t")
secure := false
httpOnly := false
var expire int64
var domain string
// Netscape cookie entries should always have 7 pieces to them
if len(cookieParts) != CookiePieces {
continue
}
domain = strings.ToLower(cookieParts[CookieDomain])
expire, _ = strconv.ParseInt(cookieParts[CookieExpiration], 10, 64)
expireTime := time.Unix(expire, 0)
if strings.HasPrefix(domain, "#httponly_") {
httpOnly = true
domain = strings.TrimPrefix(domain, "#httponly_")
}
if strings.ToLower(cookieParts[CookieSecure]) == "true" {
secure = true
}
cookie := &http.Cookie{
Domain: domain,
Path: cookieParts[CookiePath],
Secure: secure,
Expires: expireTime,
Name: cookieParts[CookieName],
Value: cookieParts[CookieValue],
HttpOnly: httpOnly,
}
if _, ok := cookieMap[domain]; !ok {
cookieMap[domain] = make([]*http.Cookie, 0)
}
cookieMap[domain] = append(cookieMap[domain], cookie)
}
if len(cookieMap) > 0 {
for _, cookies := range cookieMap {
url, err := url.Parse(fmt.Sprintf("https://%s", cookies[0].Domain))
if err == nil {
jar.SetCookies(url, cookies)
if strings.HasSuffix(url.Host, "youtube.com") {
di.CookiesURL = url
}
}
}
}
return jar, nil
}