-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
340 lines (295 loc) · 9.19 KB
/
main.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package main
import (
"encoding/gob"
"errors"
"flag"
"fmt"
"hash/fnv"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/omakoto/mlib"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
youtube "google.golang.org/api/youtube/v3"
)
var (
clientID = flag.String("clientid", "", "OAuth 2.0 Client ID. If non-empty, overrides --clientid_file")
clientIDFile = flag.String("clientid-file", "clientid.dat",
"Name of a file containing just the project's OAuth 2.0 Client ID from https://developers.google.com/console.")
secret = flag.String("secret", "", "OAuth 2.0 Client Secret. If non-empty, overrides --secret_file")
secretFile = flag.String("secret-file", "clientsecret.dat",
"Name of a file containing just the project's OAuth 2.0 Client Secret from https://developers.google.com/console.")
cacheToken = flag.Bool("cachetoken", true, "cache the OAuth 2.0 token")
deleteId = flag.String("deleteid", "", "Video delete")
filename = flag.String("filename", "", "Name of video file to upload")
title = flag.String("title", "Test Title", "Video title")
description = flag.String("description", "Test Description", "Video description")
category = flag.String("category", "22", "Video category")
keywords = flag.String("keywords", "", "Comma separated list of video keywords")
privacy = flag.String("privacy", "public", "Video privacy status")
playlist = flag.String("playlist", "", "Playlist name to add video to")
playlistidfordelete string
)
func main() {
flag.Parse()
config := &oauth2.Config{
ClientID: valueOrFileContents(*clientID, *clientIDFile),
ClientSecret: valueOrFileContents(*secret, *secretFile),
Endpoint: google.Endpoint,
Scopes: []string{youtube.YoutubeScope, youtube.YoutubepartnerScope, youtube.YoutubeForceSslScope},
}
ctx := context.Background()
client := newOAuthClient(ctx, config)
service, err := youtube.New(client)
if err != nil {
log.Fatalf("Error creating YouTube client: %v", err)
}
if *deleteId != "" {
playlistId := findPlaylist(service, *playlist)
nextPageToken := ""
for {
// Call the playlistItems.list method to retrieve the
// list of uploaded videos. Each request retrieves 50
// videos until all videos have been retrieved.
playlistCall := service.PlaylistItems.List("snippet").
PlaylistId(playlistId).
MaxResults(50).
PageToken(nextPageToken)
playlistResponse, err := playlistCall.Do()
if err != nil {
// The playlistItems.list method call returned an error.
log.Fatalf("Error fetching playlist items: %v", err.Error())
}
for _, playlistItem := range playlistResponse.Items {
// title := playlistItem.Snippet.Title
playlistItemId := playlistItem.Id
videoId := playlistItem.Snippet.ResourceId.VideoId
// playlistId := playlistItem.Snippet.PlaylistId
if *deleteId == videoId {
playlistidfordelete = playlistItemId
// log.Printf(" %v, %v, %v ,%v ", title, videoId, playlistId, playlistItemId)
}
}
// Set the token to retrieve the next page of results
// or exit the loop if all results have been retrieved.
// nextPageToken = playlistResponse.NextPageToken
if nextPageToken == "" {
break
}
}
// }
del_call := service.PlaylistItems.Delete(playlistidfordelete)
if del_call.Do() != nil {
log.Fatalf("Error delete for Playlists element. %s", del_call.Do())
}
log.Println("Delete Video from Playlist")
del := service.Videos.Delete(*deleteId)
if del.Do() != nil {
log.Fatalf("Error delete YouTube : %v", del.Do())
}
log.Println("Delete Video")
} else {
if *filename == "" {
log.Fatalf("You must provide a filename of a video file to upload")
}
upload := &youtube.Video{
Snippet: &youtube.VideoSnippet{
Title: *title,
Description: *description,
CategoryId: *category,
},
Status: &youtube.VideoStatus{PrivacyStatus: *privacy},
}
// The API returns a 400 Bad Request response if tags is an empty string.
if strings.Trim(*keywords, "") != "" {
upload.Snippet.Tags = strings.Split(*keywords, ",")
}
call := service.Videos.Insert("snippet,status", upload)
file, err := os.Open(*filename)
defer file.Close()
if err != nil {
log.Fatalf("Error opening %v: %v", *filename, err)
}
response, err := call.Media(file).Do()
if err != nil {
log.Fatalf("Error making YouTube API call: %v", err)
}
fmt.Printf("Upload successful! Video ID: %v\n", response.Id)
if *playlist != "" {
playlistId := findPlaylist(service, *playlist)
if playlistId != "" {
log.Printf("Playlist found: %s\n", playlistId)
} else {
playlistId = createPlaylist(service, *playlist)
log.Printf("Playlist created: id=%s", playlistId)
}
addToPlaylist(service, response.Id, playlistId)
log.Printf("Video added to playlist")
}
}
}
func newOAuthClient(ctx context.Context, config *oauth2.Config) *http.Client {
cacheFile := tokenCacheFile(config)
token, err := tokenFromFile(cacheFile)
if err != nil {
token = tokenFromWeb(ctx, config)
saveToken(cacheFile, token)
} else {
log.Printf("Using cached token %#v from %q", token, cacheFile)
}
return config.Client(ctx, token)
}
func saveToken(file string, token *oauth2.Token) {
f, err := os.Create(file)
if err != nil {
log.Printf("Warning: failed to cache oauth token: %v", err)
return
}
defer f.Close()
gob.NewEncoder(f).Encode(token)
}
func valueOrFileContents(value string, filename string) string {
if value != "" {
return value
}
slurp, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("Error reading %q: %v", filename, err)
}
return strings.TrimSpace(string(slurp))
}
func tokenCacheFile(config *oauth2.Config) string {
hash := fnv.New32a()
hash.Write([]byte(config.ClientID))
hash.Write([]byte(config.ClientSecret))
hash.Write([]byte(strings.Join(config.Scopes, " ")))
fn := fmt.Sprintf("go-api-youtube-tok%v", hash.Sum32())
return filepath.Join(osUserCacheDir(), url.QueryEscape(fn))
}
func tokenFromFile(file string) (*oauth2.Token, error) {
if !*cacheToken {
return nil, errors.New("--cachetoken is false")
}
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := new(oauth2.Token)
err = gob.NewDecoder(f).Decode(t)
return t, err
}
func tokenFromWeb(ctx context.Context, config *oauth2.Config) *oauth2.Token {
ch := make(chan string)
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/favicon.ico" {
http.Error(rw, "", 404)
return
}
if req.FormValue("state") != randState {
log.Printf("State doesn't match: req = %#v", req)
http.Error(rw, "", 500)
return
}
if code := req.FormValue("code"); code != "" {
fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
rw.(http.Flusher).Flush()
ch <- code
return
}
log.Printf("no code")
http.Error(rw, "", 500)
}))
defer ts.Close()
config.RedirectURL = ts.URL
authURL := config.AuthCodeURL(randState)
go openURL(authURL)
log.Printf("Authorize this app at: %s", authURL)
code := <-ch
log.Printf("Got code: %s", code)
token, err := config.Exchange(ctx, code)
if err != nil {
log.Fatalf("Token exchange error: %v", err)
}
return token
}
func osUserCacheDir() string {
switch runtime.GOOS {
case "darwin":
return filepath.Join(os.Getenv("HOME"), "Library", "Caches")
case "linux", "freebsd":
return filepath.Join(os.Getenv("HOME"), ".cache")
}
log.Printf("TODO: osUserCacheDir on GOOS %q", runtime.GOOS)
return "."
}
func openURL(url string) {
try := []string{"xdg-open", "google-chrome", "open"}
for _, bin := range try {
err := exec.Command(bin, url).Run()
if err == nil {
return
}
}
log.Printf("Error opening URL in browser.")
}
func findPlaylist(service *youtube.Service, title string) string {
playlists := youtube.NewPlaylistsService(service)
playListsCall := playlists.List("snippet")
playListsCall.Mine(true)
playlistsResult, err := playListsCall.Do()
if err != nil {
log.Fatalf("Error listing playlists: %v", err)
}
for _, item := range playlistsResult.Items {
mlib.DebugDump(item)
if item.Snippet.Title == title {
return item.Id
}
}
return ""
}
func addToPlaylist(service *youtube.Service, videoId string, playlistId string) {
items := youtube.NewPlaylistItemsService(service)
itemInsertCall := items.Insert("snippet", &youtube.PlaylistItem{
Snippet: &youtube.PlaylistItemSnippet{
PlaylistId: playlistId,
ResourceId: &youtube.ResourceId{
Kind: "youtube#video",
VideoId: videoId,
},
},
})
_, err := itemInsertCall.Do()
if err != nil {
log.Fatalf("Error adding video to playlist: %v", err)
}
}
func createPlaylist(service *youtube.Service, title string) string {
playlists := youtube.NewPlaylistsService(service)
playlist := youtube.Playlist{
Snippet: &youtube.PlaylistSnippet{
Title: title,
},
Status: &youtube.PlaylistStatus{
PrivacyStatus: *privacy,
},
}
playListsCall := playlists.Insert("snippet,status", &playlist)
playlistsResult, err := playListsCall.Do()
if err != nil {
log.Fatalf("Error inserting playlist: %v", err)
}
mlib.DebugDump(playlistsResult)
return playlistsResult.Id
}