-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
120 lines (98 loc) · 2.22 KB
/
utils.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/kkdai/youtube/v2"
)
const YOUTUBE = "youtube"
func errorHandler(err error, message string) {
if err != nil && len(message) > 0 {
log.Fatalf("Err: %s\n Trace: %s", message, err.Error())
}
}
func isUrl(str string) bool {
u, err := url.Parse(str)
return err == nil && u.Scheme != "" && u.Host != ""
}
func isYoutubeUrl(str string) (string, error) {
u, err := url.Parse(str)
if err != nil {
return "", err
}
if !strings.Contains(u.Host, YOUTUBE) {
return "", nil
}
return u.Query().Get("v"), nil
}
func getFileExtensionFromUrl(rawUrl string) (string, error) {
u, err := url.Parse(rawUrl)
if err != nil {
return "", err
}
pos := strings.LastIndex(u.Path, ".")
if pos == -1 {
return "", errors.New("couldn't find a period to indicate a file extension")
}
return u.Path[pos+1 : len(u.Path)], nil
}
func fetchYoutubeVideo(videoId string, pathToSave string) string {
errString := "Error fetching resource."
client := youtube.Client{}
video, err := client.GetVideo(videoId)
if err != nil {
errorHandler(err, errString)
return ""
}
formats := video.Formats.WithAudioChannels() // only get videos with audio
stream, _, err := client.GetStream(video, &formats[0])
if err != nil {
errorHandler(err, errString)
return ""
}
defer stream.Close()
path := fmt.Sprintf("%s/input.mp4", pathToSave)
file, err := os.Create(path)
if err != nil {
errorHandler(err, errString)
return ""
}
defer file.Close()
_, err = io.Copy(file, stream)
if err != nil {
errorHandler(err, errString)
return ""
}
return path
}
func fetchVideo(url string, pathToSave string) string {
videoExtension, err := getFileExtensionFromUrl(url)
errString := "Error fetching resource."
if err != nil {
errorHandler(err, errString)
return ""
}
resp, err := http.Get(url)
if err != nil {
errorHandler(err, errString)
return ""
}
defer resp.Body.Close()
path := fmt.Sprintf("%s/input.%s", pathToSave, videoExtension)
out, err := os.Create(path)
if err != nil {
errorHandler(err, errString)
return ""
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
errorHandler(err, errString)
}
return path
}