* Modernize java-script
* Add CSP meta tag
* Minor refactor
* Add Makefile to update bootstrap css
* Fix filename in dummytdl tool
This commit is contained in:
Balakrishnan Balasubramanian 2022-07-18 19:21:06 -04:00
parent 44e7d1f1a6
commit 8c85e5f005
6 changed files with 87 additions and 86 deletions

7
Makefile Normal file
View File

@ -0,0 +1,7 @@
update-bootstrap:
curl -L "https://cdn.jsdelivr.net/npm/bootstrap@5/dist/css/bootstrap.min.css" -o assets/bootstrap.min.css
build:
go build .

File diff suppressed because one or more lines are too long

7
assets/bootstrap.min.css vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -4,22 +4,28 @@ import (
"flag" "flag"
"fmt" "fmt"
"os" "os"
"strings"
"time" "time"
) )
// Dummy tool to replace youtube-dl when testing
// Pass -ytdlcmd "go run cmd/dummytdl/main.go"
func main() { func main() {
var op string var op string
var title string var title string
flag.StringVar(&op, "output", "", "path to save file") flag.StringVar(&op, "output", "", "path to save file")
flag.StringVar(&title, "get-title", "", "title") flag.StringVar(&title, "get-title", "", "title")
flag.Bool("newline", false, "sdlkfjdslkfj") flag.Bool("newline", false, "print update as lines")
flag.Parse() flag.Parse()
if title != "" { if title != "" {
time.Sleep(2 * time.Second)
fmt.Println("Dummy title") fmt.Println("Dummy title")
return return
} }
op = fmt.Sprintf("%s.mp4", strings.TrimSuffix(op, ".%(ext)s"))
os.WriteFile(op, []byte("slkfjsdlkfdjkfj"), 0644) os.WriteFile(op, []byte("slkfjsdlkfdjkfj"), 0644)
i := 0 i := 0
for range time.Tick(1 * time.Second) { for range time.Tick(1 * time.Second) {

82
main.go
View File

@ -80,7 +80,7 @@ func main() {
} }
defer d.Save() defer d.Save()
assets := []string{"assets/bootstrap.css"} assets := []string{"assets/bootstrap.min.css"}
if saveAssets { if saveAssets {
for _, assetFile := range assets { for _, assetFile := range assets {
@ -102,41 +102,49 @@ func main() {
} }
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet { if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
switch r.Method {
case http.MethodGet:
td := struct {
Title string
VidoesUrl string
Items []db.Item
}{title, videosUrl, nil}
d.Run(func(jd *db.Jdb) { d.Run(func(jd *db.Jdb) {
td := struct {
Title string
VidoesUrl string
Items []db.Item
}{title, videosUrl, nil}
//reverse order //reverse order
for _, item := range jd.Items { for _, item := range jd.Items {
td.Items = append([]db.Item{item}, td.Items...) td.Items = append([]db.Item{item}, td.Items...)
} }
if err := tmpl.Execute(w, td); err != nil {
log.Panic(err)
}
}) })
return if err := tmpl.Execute(w, td); err != nil {
log.Panic(err)
}
case http.MethodPost:
yturl := r.PostFormValue("youtube_url")
if yturl == "" {
log.Printf("yturl empty, postform:%v\n", r.PostForm)
w.WriteHeader(http.StatusBadRequest)
return
}
id, isNew := d.Add(db.Item{
Date: time.Now().Format("2006-01-02 15:04"),
URL: yturl,
Title: "Loading",
Status: db.NotStarted,
})
if isNew {
go getTitle(id, yturl)
go download(id, yturl)
}
http.Redirect(w, r, "/", http.StatusSeeOther)
default:
w.WriteHeader(http.StatusForbidden)
} }
yturl := r.PostFormValue("youtube_url")
if yturl == "" {
log.Printf("yturl empty, postform:%v\n", r.PostForm)
w.WriteHeader(http.StatusInternalServerError)
return
}
id, isNew := d.Add(db.Item{
Date: time.Now().Format("2006-01-02 15:04"),
URL: yturl,
Title: "Loading",
Status: db.NotStarted,
})
if isNew {
go getTitle(id, yturl)
go download(id, yturl)
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}) })
http.HandleFunc("/ws/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/ws/", func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path p := r.URL.Path
idStr := strings.TrimPrefix(p, "/ws/") idStr := strings.TrimPrefix(p, "/ws/")
@ -164,24 +172,10 @@ func main() {
} }
} }
} }
var status db.DownloadStatus
var fname string
d.Transact(id, false, func(i *db.Item) {
status = i.Status
fname = i.FileName
})
if status != db.Done {
_, err := c.Write([]byte(status))
if err != nil {
log.Printf("err: %v\n", err)
}
return
}
alink := fmt.Sprintf(`<a target="_blank" href="%s/%s">Watch</a>`, videosUrl, fname)
c.Write([]byte(alink))
} }
wh.ServeHTTP(w, r) wh.ServeHTTP(w, r)
}) })
http.HandleFunc("/title/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/title/", func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path p := r.URL.Path
idStr := strings.TrimPrefix(p, "/title/") idStr := strings.TrimPrefix(p, "/title/")
@ -203,8 +197,8 @@ func main() {
}) })
w.Write([]byte(title)) w.Write([]byte(title))
}) })
log.Panic(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
log.Panic(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
} }
func getTitle(id int, yturl string) { func getTitle(id int, yturl string) {

View File

@ -3,52 +3,46 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline' data: ;">
<title>{{ $.Title }}</title> <title>{{ $.Title }}</title>
<!-- Diable favicon requests: https://stackoverflow.com/a/13416784 --> <!-- Diable favicon requests: https://stackoverflow.com/a/13416784 -->
<link rel="icon" href="data:;base64,iVBORw0KGgo="> <link rel="icon" href="data:;base64,iVBORw0KGgo=">
<link href="assets/bootstrap.css" rel="stylesheet" > <link href="assets/bootstrap.min.css" rel="stylesheet" >
<script> <script>
// https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
window.addEventListener('DOMContentLoaded', () => { window.addEventListener('DOMContentLoaded', () => {
progressElems = document.querySelectorAll("[data-ytstatus=progress") progressElems = document.querySelectorAll("[data-ytstatus=progress]")
progressElems.forEach(function(item) { progressElems.forEach(item => {
// https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes // https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
item.innerText = item.dataset.ytid let ytid = item.innerText = item.dataset.ytid
ytid = item.dataset.ytid
// https://stackoverflow.com/a/47472874 // https://stackoverflow.com/a/47472874
var url = new URL("/ws/" + ytid, window.location.href); let url = new URL("/ws/" + ytid, window.location.href);
url.protocol = url.protocol.replace('http', 'ws'); url.protocol = url.protocol.replace('http', 'ws');
let socket = new WebSocket(url.href) let socket = new WebSocket(url.href)
socket.onmessage = function(event) { socket.onmessage = event => item.innerText = event.data
item.innerHTML = event.data socket.onclose = () => window.location.reload()
} });
socket.onclose = function(event) {
window.location.reload();
}
});
pendingTitles = document.querySelectorAll("[data-yttitle]") pendingTitles = document.querySelectorAll("[data-yttitle]")
pendingTitles.forEach(function(item) { pendingTitles.forEach(async item => {
ytid = item.dataset.ytid let ytid = item.dataset.ytid
fetch("/title/" + ytid).then(function(response) { let resp = await fetch("/title/" + ytid)
if(response.ok) { if(resp.ok) {
return response.text().then(function(text) { let text = await resp.text()
item.innerText = text item.innerText = text
}) } else {
} console.log("Response not ok: ", response)
console.log("Response not ok") }
}); })
}) })
});
</script> </script>
</head> </head>
<body> <body>
<h1 class="text-center"> {{ $.Title }} </h1> <h1 class="text-center">{{ $.Title }}</h1>
<div class="container"> <div class="container">
<div class="row my-4 text-center"> <div class="row my-4 text-center">
<form method="POST" action="/"> <form method="post" action="/">
<input class="col-md-8 h-100" placeholder="Enter video link" type="text" name="youtube_url"> <input class="col-md-8 h-100" placeholder="Enter video link" type="text" name="youtube_url">
<input class="btn btn-outline-primary mx-2" type="submit" value="Download"> <input class="btn btn-outline-primary mx-2" type="submit" value="Download">
</form> </form>
@ -72,7 +66,7 @@
{{ else if eq .Status "InProgress" }} {{ else if eq .Status "InProgress" }}
<span class="border border-info w-100 text-center d-block" data-ytstatus="progress" data-ytid="{{.Id}}">In Progress</span> <span class="border border-info w-100 text-center d-block" data-ytstatus="progress" data-ytid="{{.Id}}">In Progress</span>
{{ else }} {{ else }}
<span class="border border-danger w-100 text-center d-block"> {{ .Status }} </span> <span class="border border-danger w-100 text-center d-block">{{ .Status }}</span>
{{ end }} {{ end }}
</div> </div>
</div> </div>