Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added qBittorrent #543

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions internal/glance/static/css/widget-qbittorrent.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.qbittorrent-torrent + .qbittorrent-torrent {
margin-top: 1.2rem;
}
1 change: 1 addition & 0 deletions internal/glance/static/css/widgets.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
@import "widget-group.css";
@import "widget-markets.css";
@import "widget-monitor.css";
@import "widget-qbittorrent.css";
@import "widget-reddit.css";
@import "widget-releases.css";
@import "widget-rss.css";
Expand Down
85 changes: 66 additions & 19 deletions internal/glance/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"html/template"
"math"
"strconv"
"strings"

"golang.org/x/text/language"
"golang.org/x/text/message"
Expand All @@ -24,34 +25,22 @@ var globalTemplateFunctions = template.FuncMap{
"absInt": func(i int) int {
return int(math.Abs(float64(i)))
},
"multiply": multiply,
"formatPrice": func(price float64) string {
return intl.Sprintf("%.2f", price)
},
"formatPriceWithPrecision": func(precision int, price float64) string {
return intl.Sprintf("%."+strconv.Itoa(precision)+"f", price)
},
"dynamicRelativeTimeAttrs": dynamicRelativeTimeAttrs,
"formatBytes": formatBytes,
"formatServerMegabytes": func(mb uint64) template.HTML {
var value string
var label string

if mb < 1_000 {
value = strconv.FormatUint(mb, 10)
label = "MB"
} else if mb < 1_000_000 {
if mb < 10_000 {
value = fmt.Sprintf("%.1f", float64(mb)/1_000)
} else {
value = strconv.FormatUint(mb/1_000, 10)
}

label = "GB"
} else {
value = fmt.Sprintf("%.1f", float64(mb)/1_000_000)
label = "TB"
formatted := formatBytes(mb * 1024 * 1024)
parts := strings.Split(formatted, " ")
if len(parts) == 2 {
return template.HTML(parts[0] + ` <span class="color-base size-h5">` + parts[1] + `</span>`)
}

return template.HTML(value + ` <span class="color-base size-h5">` + label + `</span>`)
return template.HTML(formatted)
},
}

Expand Down Expand Up @@ -86,3 +75,61 @@ func formatApproxNumber(count int) string {
func dynamicRelativeTimeAttrs(t interface{ Unix() int64 }) template.HTMLAttr {
return template.HTMLAttr(`data-dynamic-relative-time="` + strconv.FormatInt(t.Unix(), 10) + `"`)
}

func multiply(a, b interface{}) float64 {
var result float64

switch v := a.(type) {
case int:
result = float64(v)
case float64:
result = v
default:
panic("Unsupported type for 'a', only int and float64 are supported")
}

switch v := b.(type) {
case int:
return result * float64(v)
case float64:
return result * v
default:
panic("Unsupported type for 'b', only int and float64 are supported")
}
}

func formatBytes(bytes uint64) string {
var value string
var unit string

if bytes < 1024 {
value = strconv.FormatUint(bytes, 10)
unit = "B"
} else if bytes < 1024*1024 {
if bytes < 10*1024 {
value = fmt.Sprintf("%.1f", float64(bytes)/1024)
} else {
value = strconv.FormatUint(bytes/1024, 10)
}
unit = "KB"
} else if bytes < 1024*1024*1024 {
if bytes < 10*1024*1024 {
value = fmt.Sprintf("%.1f", float64(bytes)/(1024*1024))
} else {
value = strconv.FormatUint(bytes/(1024*1024), 10)
}
unit = "MB"
} else if bytes < 1024*1024*1024*1024 {
if bytes < 10*1024*1024*1024 {
value = fmt.Sprintf("%.1f", float64(bytes)/(1024*1024*1024))
} else {
value = strconv.FormatUint(bytes/(1024*1024*1024), 10)
}
unit = "GB"
} else {
value = fmt.Sprintf("%.1f", float64(bytes)/(1024*1024*1024*1024))
unit = "TB"
}

return value + " " + unit
}
32 changes: 32 additions & 0 deletions internal/glance/templates/qbittorrent.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{{ template "widget-base.html" . }}

{{ define "widget-content" }}
<div class="qbittorrent-torrents">
{{- if .Torrents }}
{{- range .Torrents }}
<div class="qbittorrent-torrent">
<div class="qbittorrent-torrent-header text-truncate">
<span class="qbittorrent-torrent-name">{{ .Name }}</span>
</div>
<div class="qbittorrent-torrent-progress flex items-center gap-10">
<div class="progress-bar flex-1">
<div class="progress-value" style="--percent: {{ (multiply .Progress 100) }};"></div>
</div>
<span class="qbittorrent-progress-text color-highlight text-very-compact">{{ printf "%.1f" (multiply
.Progress 100) }}
<span class="color-base">%</span></span>
</div>
<div class="qbittorrent-torrent-info">
{{- if eq .Progress 1.0 }}
<span class="qbittorrent-torrent-completed color-primary">Completed</span>
{{- else }}
<span class="qbittorrent-torrent-speed">{{ .Speed | formatBytes }}/s</span>
{{- end }}
</div>
</div>
{{- end }}
{{- else }}
<div class="text-center color-subdue">No active torrents</div>
{{- end }}
</div>
{{ end }}
148 changes: 148 additions & 0 deletions internal/glance/widget-qbittorrent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package glance

import (
"context"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"strings"
"time"
)

const (
qBittorrentAPIPrefix = "/api/v2"
qBittorrentLoginPath = qBittorrentAPIPrefix + "/auth/login"
qBittorrentTorrentsPath = qBittorrentAPIPrefix + "/torrents/info"
)

var qbittorrentWidgetTemplate = mustParseTemplate("qbittorrent.html", "widget-base.html")

type qbittorrentWidget struct {
widgetBase `yaml:",inline"`
URL string `yaml:"url"`
Username string `yaml:"username"`
Password string `yaml:"password"`
Limit int `yaml:"limit"`
Torrents []qbittorrentTorrent `yaml:"-"`
client *http.Client `yaml:"-"`
}

type qbittorrentTorrent struct {
Name string `json:"name"`
Progress float64 `json:"progress"`
State string `json:"state"`
Size int64 `json:"size"`
Downloaded int64 `json:"downloaded"`
Speed uint64 `json:"dlspeed"`
}

func (widget *qbittorrentWidget) initialize() error {
widget.
withTitle("qBittorrent").
withTitleURL(widget.URL).
withCacheDuration(time.Second * 5)

if widget.URL == "" {
return errors.New("URL is required")
}

if _, err := url.Parse(widget.URL); err != nil {
return fmt.Errorf("invalid URL: %w", err)
}

if widget.Limit <= 0 {
widget.Limit = 5
}

jar, err := cookiejar.New(nil)
if err != nil {
return fmt.Errorf("error creating cookie jar: %w", err)
}

widget.client = &http.Client{Jar: jar}

if err := widget.login(); err != nil {
return fmt.Errorf("login failed: %w", err)
}

return nil
}

func (widget *qbittorrentWidget) login() error {
loginData := url.Values{}
loginData.Set("username", widget.Username)
loginData.Set("password", widget.Password)

req, err := http.NewRequest("POST", widget.URL+qBittorrentLoginPath, strings.NewReader(loginData.Encode()))
if err != nil {
return fmt.Errorf("creating login request: %w", err)
}

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", widget.URL)

resp, err := widget.client.Do(req)
if err != nil {
return fmt.Errorf("login request failed: %w", err)
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("login failed with status %d: %s", resp.StatusCode, string(body))
}

return nil
}

func (widget *qbittorrentWidget) update(ctx context.Context) {
params := url.Values{}
params.Set("limit", strconv.Itoa(widget.Limit))
params.Set("sort", "dlspeed")
params.Set("reverse", "true")

requestURL := widget.URL + qBittorrentTorrentsPath + "?" + params.Encode()
req, err := http.NewRequestWithContext(ctx, "GET", requestURL, nil)
if err != nil {
widget.withError(fmt.Errorf("creating torrents request: %w", err))
return
}

req.Header.Set("Referer", widget.URL)

resp, err := widget.client.Do(req)
if err != nil {
widget.withError(fmt.Errorf("torrents request failed: %w", err))
return
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
widget.withError(fmt.Errorf("torrents request failed with status %d: %s", resp.StatusCode, string(body)))
return
}

var torrents []qbittorrentTorrent
if err := json.NewDecoder(resp.Body).Decode(&torrents); err != nil {
widget.withError(fmt.Errorf("decoding torrents response: %w", err))
return
}

widget.Torrents = torrents
widget.withError(nil)
}

func (widget *qbittorrentWidget) Render() template.HTML {
return widget.renderTemplate(widget, qbittorrentWidgetTemplate)
}
2 changes: 2 additions & 0 deletions internal/glance/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ func newWidget(widgetType string) (widget, error) {
w = &dockerContainersWidget{}
case "server-stats":
w = &serverStatsWidget{}
case "qbittorrent":
w = &qbittorrentWidget{}
default:
return nil, fmt.Errorf("unknown widget type: %s", widgetType)
}
Expand Down