mirror of
https://github.com/hrfee/jfa-go.git
synced 2026-01-19 00:57:37 +01:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e35d0579c8 | ||
|
|
ea80d2cb78 | ||
|
|
f3c3b3ce76 | ||
|
|
fa96f21429 | ||
|
|
b6f3cd7c1f | ||
|
|
d64e98da37 | ||
|
|
ba601935b5 | ||
|
|
34135d645d | ||
|
|
47abf20e1d | ||
|
|
493f10fa36 | ||
|
|
8e45ecb214 | ||
|
|
d4a92adc65 | ||
|
|
c84ea17af4 | ||
|
|
0f4e77364b | ||
|
|
d64d5c194f | ||
|
|
95c9f4f42d | ||
|
|
a89dc40ff2 | ||
|
|
8089187b3e | ||
|
|
29775e2e75 | ||
|
|
9d62b70daa | ||
|
|
301f502052 | ||
|
|
2d6b1717db | ||
|
|
9abb177427 | ||
|
|
2f9965bcda | ||
|
|
82d07e423c | ||
|
|
8e6cf799cd | ||
|
|
8672d7dc18 | ||
|
|
5fd2e81fe4 | ||
|
|
a12678bd4d | ||
|
|
0e415020f7 | ||
|
|
a834aa30cf | ||
|
|
e3644e8fbf | ||
|
|
04198f3d49 | ||
|
|
8f7a65bebb | ||
|
|
1ef37f91b2 | ||
|
|
64c5badddd | ||
|
|
2e0519b183 | ||
|
|
9e739e79e7 | ||
|
|
2a2435ae11 | ||
|
|
04a4a4ca95 | ||
|
|
7628e5d71d |
47
.drone.yml
Normal file
47
.drone.yml
Normal file
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: jfa-go
|
||||
kind: pipeline
|
||||
type: docker
|
||||
|
||||
steps:
|
||||
- name: fetch
|
||||
image: docker:git
|
||||
commands:
|
||||
- git fetch --tags
|
||||
- name: release
|
||||
image: golang:latest
|
||||
environment:
|
||||
GITHUB_TOKEN:
|
||||
from_secret: github_token
|
||||
commands:
|
||||
- apt update -y
|
||||
- apt install build-essential python3-pip curl software-properties-common sed upx -y
|
||||
- (curl -sL https://deb.nodesource.com/setup_14.x | bash -)
|
||||
- apt install nodejs
|
||||
- curl -sL https://git.io/goreleaser | bash
|
||||
when:
|
||||
event: tag
|
||||
|
||||
---
|
||||
name: jfa-go-git
|
||||
kind: pipeline
|
||||
type: docker
|
||||
|
||||
steps:
|
||||
- name: build
|
||||
image: golang:latest
|
||||
commands:
|
||||
- apt update -y
|
||||
- apt install build-essential python3-pip curl software-properties-common sed upx -y
|
||||
- (curl -sL https://deb.nodesource.com/setup_14.x | bash -)
|
||||
- apt install nodejs
|
||||
- curl -sL https://git.io/goreleaser > goreleaser.sh
|
||||
- chmod +x goreleaser.sh
|
||||
- ./goreleaser.sh --snapshot --skip-publish --rm-dist
|
||||
- wget https://builds.hrfee.pw/upload.py
|
||||
- pip3 install requests
|
||||
- bash -c 'python3 upload.py https://builds.hrfee.pw hrfee jfa-go ./dist/*.tar.gz'
|
||||
environment:
|
||||
BUILDRONE_KEY:
|
||||
from_secret: BUILDRONE_KEY
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,6 +8,7 @@ data/static/*.css
|
||||
data/static/*.js
|
||||
data/static/*.js.map
|
||||
data/static/ts/
|
||||
data/static/modules/
|
||||
!data/static/setup.js
|
||||
data/config-base.json
|
||||
data/config-default.ini
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# This is an example goreleaser.yaml file with some sane defaults.
|
||||
# Make sure to check the documentation at http://goreleaser.com
|
||||
project_name: jfa-go
|
||||
release:
|
||||
github:
|
||||
@@ -10,13 +8,14 @@ before:
|
||||
hooks:
|
||||
- go mod download
|
||||
- python3 config/fixconfig.py -i config/config-base.json -o data/config-base.json
|
||||
- python3 config/generate_ini.py -i config/config-base.json -o data/config-default.ini --version {{.Version}}
|
||||
- python3 config/generate_ini.py -i config/config-base.json -o data/config-default.ini
|
||||
- python3 -m pip install libsass
|
||||
- python3 scss/get_node_deps.py
|
||||
- python3 scss/compile.py -y
|
||||
- python3 mail/generate.py -y
|
||||
- npm install
|
||||
- python3 scss/compile.py
|
||||
- python3 mail/generate.py
|
||||
- python3 version.py {{.Version}} version.go
|
||||
- ./tsc-silent.sh
|
||||
- bash -c 'npx esbuild ts/*.ts ts/modules/*.ts --outdir=data/static --minify'
|
||||
- go get -u github.com/swaggo/swag/cmd/swag
|
||||
- swag init -g main.go
|
||||
builds:
|
||||
- dir: ./
|
||||
@@ -40,10 +39,11 @@ archives:
|
||||
- data/*
|
||||
- data/templates/*
|
||||
- data/static/*
|
||||
- data/static/modules/*
|
||||
checksum:
|
||||
name_template: 'checksums.txt'
|
||||
snapshot:
|
||||
name_template: "{{ .Tag }}-testing"
|
||||
name_template: "git-{{.ShortCommit}}"
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
|
||||
@@ -6,7 +6,7 @@ RUN apt update -y \
|
||||
&& apt install build-essential python3-pip curl software-properties-common sed upx -y \
|
||||
&& (curl -sL https://deb.nodesource.com/setup_14.x | bash -) \
|
||||
&& apt install nodejs \
|
||||
&& (cd /opt/build; make headless; make compress) \
|
||||
&& (cd /opt/build; make all; make compress) \
|
||||
&& sed -i 's#id="pwrJfPath" placeholder="Folder"#id="pwrJfPath" value="/jf" disabled#g' /opt/build/build/data/templates/setup.html
|
||||
|
||||
FROM golang:latest
|
||||
|
||||
32
Makefile
32
Makefile
@@ -2,38 +2,31 @@ configuration:
|
||||
$(info Fixing config-base)
|
||||
python3 config/fixconfig.py -i config/config-base.json -o data/config-base.json
|
||||
$(info Generating config-default.ini)
|
||||
python3 config/generate_ini.py -i config/config-base.json -o data/config-default.ini --version git
|
||||
python3 config/generate_ini.py -i config/config-base.json -o data/config-default.ini
|
||||
|
||||
sass:
|
||||
$(info Getting libsass)
|
||||
python3 -m pip install libsass
|
||||
$(info Getting node dependencies)
|
||||
python3 scss/get_node_deps.py
|
||||
npm install
|
||||
$(info Compiling sass)
|
||||
python3 scss/compile.py
|
||||
|
||||
sass-headless:
|
||||
$(info Getting libsass)
|
||||
python3 -m pip install libsass
|
||||
$(info Getting node dependencies)
|
||||
python3 scss/get_node_deps.py
|
||||
$(info Compiling sass)
|
||||
python3 scss/compile.py -y
|
||||
|
||||
mail-headless:
|
||||
$(info Generating email html)
|
||||
python3 mail/generate.py -y
|
||||
|
||||
mail:
|
||||
email:
|
||||
$(info Generating email html)
|
||||
python3 mail/generate.py
|
||||
|
||||
typescript:
|
||||
$(info Compiling typescript)
|
||||
-npx tsc -p ts/
|
||||
npx esbuild ts/*.ts ts/modules/*.ts --outdir=data/static --minify
|
||||
-rm -r data/static/ts
|
||||
-rm -r data/static/typings
|
||||
-rm data/static/*.map
|
||||
|
||||
ts-debug:
|
||||
-npx tsc -p ts/ --sourceMap
|
||||
-rm -r data/static/ts
|
||||
-rm -r data/static/typings
|
||||
cp -r ts data/static/
|
||||
|
||||
swagger:
|
||||
@@ -60,8 +53,5 @@ copy:
|
||||
install:
|
||||
cp -r build $(DESTDIR)/jfa-go
|
||||
|
||||
all: configuration sass mail version typescript swagger compile copy
|
||||
headless: configuration sass-headless mail-headless version typescript swagger compile copy
|
||||
|
||||
|
||||
|
||||
all: configuration sass email version typescript swagger compile copy
|
||||
debug: configuration sass email version ts-debug swagger compile copy
|
||||
|
||||
10
README.md
10
README.md
@@ -37,7 +37,7 @@ I chose to rewrite the python [jellyfin-accounts](https://github.com/hrfee/jelly
|
||||
|
||||
Available on the AUR as [jfa-go](https://aur.archlinux.org/packages/jfa-go/) or [jfa-go-git](https://aur.archlinux.org/packages/jfa-go-git/).
|
||||
|
||||
For other platforms, grab an archive from the release section for your platform, and extract `jfa-go` and `data` to the same directory.
|
||||
For other platforms, grab an archive from the release section for your platform (or nightly builds [here](https://builds.hrfee.pw/view/hrfee/jfa-go)), and extract `jfa-go` and `data` to the same directory.
|
||||
* For linux users, you can place them inside `/opt/jfa-go` and then run
|
||||
`sudo ln -s /opt/jfa-go/jfa-go /usr/bin/jfa-go` to place it in your PATH.
|
||||
|
||||
@@ -55,9 +55,9 @@ docker create \
|
||||
```
|
||||
|
||||
#### Build from source
|
||||
A Dockerfile is provided that creates an image built from source, but it's only suitable for those who will run jfa-go in docker.
|
||||
If you're using docker, a Dockerfile is provided that builds from source.
|
||||
|
||||
Full build instructions can be found [here](https://github.com/hrfee/jfa-go/wiki/Build).
|
||||
Otherwise, full build instructions can be found [here](https://github.com/hrfee/jfa-go/wiki/Build).
|
||||
|
||||
#### Usage
|
||||
Simply run `jfa-go` to start the application. A setup wizard will start on `localhost:8056` (or your own specified address). Upon completion, refresh the page.
|
||||
@@ -82,8 +82,8 @@ Usage of ./jfa-go:
|
||||
|
||||
If you're switching from jellyfin-accounts, copy your existing `~/.jf-accounts` to:
|
||||
|
||||
* `XDG_CONFIG_DIR/jfa-go` (usually ~/.config) on \*nix systems,
|
||||
* `XDG_CONFIG_DIR/jfa-go` (usually ~/.config/jfa-go) on \*nix systems,
|
||||
* `%AppData%/jfa-go` on Windows,
|
||||
* `~/Library/Application Support/jfa-go` on macOS.
|
||||
|
||||
(*or specify config/data path with `-config/-data` respectively.*)
|
||||
(or specify config/data path with `-config/-data` respectively.)
|
||||
|
||||
492
api.go
492
api.go
@@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -24,16 +26,6 @@ func respond(code int, message string, gc *gin.Context) {
|
||||
gc.Abort()
|
||||
}
|
||||
|
||||
type stringResponse struct {
|
||||
Response string `json:"response" example:"message"`
|
||||
Error string `json:"error" example:"errorDescription"`
|
||||
}
|
||||
|
||||
type boolResponse struct {
|
||||
Success bool `json:"success" example:"false"`
|
||||
Error bool `json:"error" example:"true"`
|
||||
}
|
||||
|
||||
func respondBool(code int, val bool, gc *gin.Context) {
|
||||
resp := boolResponse{}
|
||||
if !val {
|
||||
@@ -118,31 +110,33 @@ func (app *appContext) checkInvites() {
|
||||
changed := false
|
||||
for code, data := range app.storage.invites {
|
||||
expiry := data.ValidTill
|
||||
if current_time.After(expiry) {
|
||||
app.debug.Printf("Housekeeping: Deleting old invite %s", code)
|
||||
notify := data.Notify
|
||||
if app.config.Section("notifications").Key("enabled").MustBool(false) && len(notify) != 0 {
|
||||
app.debug.Printf("%s: Expiry notification", code)
|
||||
for address, settings := range notify {
|
||||
if settings["notify-expiry"] {
|
||||
go func() {
|
||||
msg, err := app.email.constructExpiry(code, data, app)
|
||||
if err != nil {
|
||||
app.err.Printf("%s: Failed to construct expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else if err := app.email.send(address, msg); err != nil {
|
||||
app.err.Printf("%s: Failed to send expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else {
|
||||
app.info.Printf("Sent expiry notification to %s", address)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
delete(app.storage.invites, code)
|
||||
if !current_time.After(expiry) {
|
||||
continue
|
||||
}
|
||||
app.debug.Printf("Housekeeping: Deleting old invite %s", code)
|
||||
notify := data.Notify
|
||||
if app.config.Section("notifications").Key("enabled").MustBool(false) && len(notify) != 0 {
|
||||
app.debug.Printf("%s: Expiry notification", code)
|
||||
for address, settings := range notify {
|
||||
if !settings["notify-expiry"] {
|
||||
continue
|
||||
}
|
||||
go func() {
|
||||
msg, err := app.email.constructExpiry(code, data, app)
|
||||
if err != nil {
|
||||
app.err.Printf("%s: Failed to construct expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else if err := app.email.send(address, msg); err != nil {
|
||||
app.err.Printf("%s: Failed to send expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else {
|
||||
app.info.Printf("Sent expiry notification to %s", address)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
delete(app.storage.invites, code)
|
||||
}
|
||||
if changed {
|
||||
app.storage.storeInvites()
|
||||
@@ -153,84 +147,104 @@ func (app *appContext) checkInvite(code string, used bool, username string) bool
|
||||
current_time := time.Now()
|
||||
app.storage.loadInvites()
|
||||
changed := false
|
||||
if inv, match := app.storage.invites[code]; match {
|
||||
expiry := inv.ValidTill
|
||||
if current_time.After(expiry) {
|
||||
app.debug.Printf("Housekeeping: Deleting old invite %s", code)
|
||||
notify := inv.Notify
|
||||
if app.config.Section("notifications").Key("enabled").MustBool(false) && len(notify) != 0 {
|
||||
app.debug.Printf("%s: Expiry notification", code)
|
||||
for address, settings := range notify {
|
||||
if settings["notify-expiry"] {
|
||||
go func() {
|
||||
msg, err := app.email.constructExpiry(code, inv, app)
|
||||
if err != nil {
|
||||
app.err.Printf("%s: Failed to construct expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else if err := app.email.send(address, msg); err != nil {
|
||||
app.err.Printf("%s: Failed to send expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else {
|
||||
app.info.Printf("Sent expiry notification to %s", address)
|
||||
}
|
||||
}()
|
||||
}
|
||||
inv, match := app.storage.invites[code]
|
||||
if !match {
|
||||
return false
|
||||
}
|
||||
expiry := inv.ValidTill
|
||||
if current_time.After(expiry) {
|
||||
app.debug.Printf("Housekeeping: Deleting old invite %s", code)
|
||||
notify := inv.Notify
|
||||
if app.config.Section("notifications").Key("enabled").MustBool(false) && len(notify) != 0 {
|
||||
app.debug.Printf("%s: Expiry notification", code)
|
||||
for address, settings := range notify {
|
||||
if settings["notify-expiry"] {
|
||||
go func() {
|
||||
msg, err := app.email.constructExpiry(code, inv, app)
|
||||
if err != nil {
|
||||
app.err.Printf("%s: Failed to construct expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else if err := app.email.send(address, msg); err != nil {
|
||||
app.err.Printf("%s: Failed to send expiry notification", code)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
} else {
|
||||
app.info.Printf("Sent expiry notification to %s", address)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
match = false
|
||||
}
|
||||
changed = true
|
||||
match = false
|
||||
delete(app.storage.invites, code)
|
||||
} else if used {
|
||||
changed = true
|
||||
del := false
|
||||
newInv := inv
|
||||
if newInv.RemainingUses == 1 {
|
||||
del = true
|
||||
delete(app.storage.invites, code)
|
||||
} else if used {
|
||||
changed = true
|
||||
del := false
|
||||
newInv := inv
|
||||
if newInv.RemainingUses == 1 {
|
||||
del = true
|
||||
delete(app.storage.invites, code)
|
||||
} else if newInv.RemainingUses != 0 {
|
||||
// 0 means infinite i guess?
|
||||
newInv.RemainingUses -= 1
|
||||
}
|
||||
newInv.UsedBy = append(newInv.UsedBy, []string{username, app.formatDatetime(current_time)})
|
||||
if !del {
|
||||
app.storage.invites[code] = newInv
|
||||
}
|
||||
} else if newInv.RemainingUses != 0 {
|
||||
// 0 means infinite i guess?
|
||||
newInv.RemainingUses -= 1
|
||||
}
|
||||
if changed {
|
||||
app.storage.storeInvites()
|
||||
newInv.UsedBy = append(newInv.UsedBy, []string{username, app.formatDatetime(current_time)})
|
||||
if !del {
|
||||
app.storage.invites[code] = newInv
|
||||
}
|
||||
return match
|
||||
}
|
||||
return false
|
||||
if changed {
|
||||
app.storage.storeInvites()
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
func (app *appContext) getOmbiUser(jfID string) (map[string]interface{}, int, error) {
|
||||
ombiUsers, code, err := app.ombi.GetUsers()
|
||||
if err != nil || code != 200 {
|
||||
return nil, code, err
|
||||
}
|
||||
jfUser, code, err := app.jf.UserByID(jfID, false)
|
||||
if err != nil || code != 200 {
|
||||
return nil, code, err
|
||||
}
|
||||
username := jfUser["Name"].(string)
|
||||
email := ""
|
||||
if e, ok := app.storage.emails[jfID]; ok {
|
||||
email = e.(string)
|
||||
}
|
||||
for _, ombiUser := range ombiUsers {
|
||||
ombiAddr := ""
|
||||
if a, ok := ombiUser["emailAddress"]; ok && a != nil {
|
||||
ombiAddr = a.(string)
|
||||
}
|
||||
if ombiUser["userName"].(string) == username || (ombiAddr == email && email != "") {
|
||||
return ombiUser, code, err
|
||||
}
|
||||
}
|
||||
return nil, 400, fmt.Errorf("Couldn't find user")
|
||||
}
|
||||
|
||||
// Routes from now on!
|
||||
|
||||
type newUserDTO struct {
|
||||
Username string `json:"username" example:"jeff" binding:"required"` // User's username
|
||||
Password string `json:"password" example:"guest" binding:"required"` // User's password
|
||||
Email string `json:"email" example:"jeff@jellyf.in"` // User's email address
|
||||
Code string `json:"code" example:"abc0933jncjkcjj"` // Invite code (required on /newUser)
|
||||
}
|
||||
|
||||
// @Summary Creates a new Jellyfin user without an invite.
|
||||
// @Produce json
|
||||
// @Param newUserDTO body newUserDTO true "New user request object"
|
||||
// @Success 200
|
||||
// @Router /users [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Users
|
||||
func (app *appContext) NewUserAdmin(gc *gin.Context) {
|
||||
var req newUserDTO
|
||||
gc.BindJSON(&req)
|
||||
existingUser, _, _ := app.jf.userByName(req.Username, false)
|
||||
existingUser, _, _ := app.jf.UserByName(req.Username, false)
|
||||
if existingUser != nil {
|
||||
msg := fmt.Sprintf("User already exists named %s", req.Username)
|
||||
app.info.Printf("%s New user failed: %s", req.Username, msg)
|
||||
respond(401, msg, gc)
|
||||
return
|
||||
}
|
||||
user, status, err := app.jf.newUser(req.Username, req.Password)
|
||||
user, status, err := app.jf.NewUser(req.Username, req.Password)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("%s New user failed: Jellyfin responded with %d", req.Username, status)
|
||||
respond(401, "Unknown error", gc)
|
||||
@@ -241,15 +255,15 @@ func (app *appContext) NewUserAdmin(gc *gin.Context) {
|
||||
id = user["Id"].(string)
|
||||
}
|
||||
if len(app.storage.policy) != 0 {
|
||||
status, err = app.jf.setPolicy(id, app.storage.policy)
|
||||
status, err = app.jf.SetPolicy(id, app.storage.policy)
|
||||
if !(status == 200 || status == 204) {
|
||||
app.err.Printf("%s: Failed to set user policy: Code %d", req.Username, status)
|
||||
}
|
||||
}
|
||||
if len(app.storage.configuration) != 0 && len(app.storage.displayprefs) != 0 {
|
||||
status, err = app.jf.setConfiguration(id, app.storage.configuration)
|
||||
status, err = app.jf.SetConfiguration(id, app.storage.configuration)
|
||||
if (status == 200 || status == 204) && err == nil {
|
||||
status, err = app.jf.setDisplayPreferences(id, app.storage.displayprefs)
|
||||
status, err = app.jf.SetDisplayPreferences(id, app.storage.displayprefs)
|
||||
} else {
|
||||
app.err.Printf("%s: Failed to set configuration template: Code %d", req.Username, status)
|
||||
}
|
||||
@@ -261,7 +275,7 @@ func (app *appContext) NewUserAdmin(gc *gin.Context) {
|
||||
if app.config.Section("ombi").Key("enabled").MustBool(false) {
|
||||
app.storage.loadOmbiTemplate()
|
||||
if len(app.storage.ombi_template) != 0 {
|
||||
errors, code, err := app.ombi.newUser(req.Username, req.Password, req.Email, app.storage.ombi_template)
|
||||
errors, code, err := app.ombi.NewUser(req.Username, req.Password, req.Email, app.storage.ombi_template)
|
||||
if err != nil || code != 200 {
|
||||
app.info.Printf("Failed to create Ombi user (%d): %s", code, err)
|
||||
app.debug.Printf("Errors reported by Ombi: %s", strings.Join(errors, ", "))
|
||||
@@ -270,7 +284,7 @@ func (app *appContext) NewUserAdmin(gc *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
app.jf.cacheExpiry = time.Now()
|
||||
app.jf.CacheExpiry = time.Now()
|
||||
}
|
||||
|
||||
// @Summary Creates a new Jellyfin user via invite code
|
||||
@@ -303,14 +317,14 @@ func (app *appContext) NewUser(gc *gin.Context) {
|
||||
gc.Abort()
|
||||
return
|
||||
}
|
||||
existingUser, _, _ := app.jf.userByName(req.Username, false)
|
||||
existingUser, _, _ := app.jf.UserByName(req.Username, false)
|
||||
if existingUser != nil {
|
||||
msg := fmt.Sprintf("User already exists named %s", req.Username)
|
||||
app.info.Printf("%s New user failed: %s", req.Code, msg)
|
||||
respond(401, msg, gc)
|
||||
return
|
||||
}
|
||||
user, status, err := app.jf.newUser(req.Username, req.Password)
|
||||
user, status, err := app.jf.NewUser(req.Username, req.Password)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("%s New user failed: Jellyfin responded with %d", req.Code, status)
|
||||
respond(401, "Unknown error", gc)
|
||||
@@ -349,29 +363,30 @@ func (app *appContext) NewUser(gc *gin.Context) {
|
||||
}
|
||||
if len(profile.Policy) != 0 {
|
||||
app.debug.Printf("Applying policy from profile \"%s\"", invite.Profile)
|
||||
status, err = app.jf.setPolicy(id, profile.Policy)
|
||||
status, err = app.jf.SetPolicy(id, profile.Policy)
|
||||
if !(status == 200 || status == 204) {
|
||||
app.err.Printf("%s: Failed to set user policy: Code %d", req.Code, status)
|
||||
}
|
||||
}
|
||||
if len(profile.Configuration) != 0 && len(profile.Displayprefs) != 0 {
|
||||
app.debug.Printf("Applying homescreen from profile \"%s\"", invite.Profile)
|
||||
status, err = app.jf.setConfiguration(id, profile.Configuration)
|
||||
status, err = app.jf.SetConfiguration(id, profile.Configuration)
|
||||
if (status == 200 || status == 204) && err == nil {
|
||||
status, err = app.jf.setDisplayPreferences(id, profile.Displayprefs)
|
||||
status, err = app.jf.SetDisplayPreferences(id, profile.Displayprefs)
|
||||
} else {
|
||||
app.err.Printf("%s: Failed to set configuration template: Code %d", req.Code, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
if app.config.Section("password_resets").Key("enabled").MustBool(false) {
|
||||
// if app.config.Section("password_resets").Key("enabled").MustBool(false) {
|
||||
if req.Email != "" {
|
||||
app.storage.emails[id] = req.Email
|
||||
app.storage.storeEmails()
|
||||
}
|
||||
if app.config.Section("ombi").Key("enabled").MustBool(false) {
|
||||
app.storage.loadOmbiTemplate()
|
||||
if len(app.storage.ombi_template) != 0 {
|
||||
errors, code, err := app.ombi.newUser(req.Username, req.Password, req.Email, app.storage.ombi_template)
|
||||
errors, code, err := app.ombi.NewUser(req.Username, req.Password, req.Email, app.storage.ombi_template)
|
||||
if err != nil || code != 200 {
|
||||
app.info.Printf("Failed to create Ombi user (%d): %s", code, err)
|
||||
app.debug.Printf("Errors reported by Ombi: %s", strings.Join(errors, ", "))
|
||||
@@ -389,12 +404,6 @@ func (app *appContext) NewUser(gc *gin.Context) {
|
||||
gc.JSON(code, validation)
|
||||
}
|
||||
|
||||
type deleteUserDTO struct {
|
||||
Users []string `json:"users" binding:"required"` // List of usernames to delete
|
||||
Notify bool `json:"notify"` // Whether to notify users of deletion
|
||||
Reason string `json:"reason"` // Account deletion reason (for notification)
|
||||
}
|
||||
|
||||
// @Summary Delete a list of users, optionally notifying them why.
|
||||
// @Produce json
|
||||
// @Param deleteUserDTO body deleteUserDTO true "User deletion request object"
|
||||
@@ -402,16 +411,34 @@ type deleteUserDTO struct {
|
||||
// @Failure 400 {object} stringResponse
|
||||
// @Failure 500 {object} errorListDTO "List of errors"
|
||||
// @Router /users [delete]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Users
|
||||
func (app *appContext) DeleteUser(gc *gin.Context) {
|
||||
var req deleteUserDTO
|
||||
gc.BindJSON(&req)
|
||||
errors := map[string]string{}
|
||||
ombiEnabled := app.config.Section("ombi").Key("enabled").MustBool(false)
|
||||
for _, userID := range req.Users {
|
||||
status, err := app.jf.deleteUser(userID)
|
||||
if ombiEnabled {
|
||||
ombiUser, code, err := app.getOmbiUser(userID)
|
||||
if code == 200 && err == nil {
|
||||
if id, ok := ombiUser["id"]; ok {
|
||||
status, err := app.ombi.DeleteUser(id.(string))
|
||||
if err != nil || status != 200 {
|
||||
app.err.Printf("Failed to delete ombi user: %d %s", status, err)
|
||||
errors[userID] = fmt.Sprintf("Ombi: %d %s, ", status, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
status, err := app.jf.DeleteUser(userID)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
errors[userID] = fmt.Sprintf("%d: %s", status, err)
|
||||
msg := fmt.Sprintf("%d: %s", status, err)
|
||||
if _, ok := errors[userID]; !ok {
|
||||
errors[userID] = msg
|
||||
} else {
|
||||
errors[userID] += msg
|
||||
}
|
||||
}
|
||||
if req.Notify {
|
||||
addr, ok := app.storage.emails[userID]
|
||||
@@ -431,7 +458,7 @@ func (app *appContext) DeleteUser(gc *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
app.jf.cacheExpiry = time.Now()
|
||||
app.jf.CacheExpiry = time.Now()
|
||||
if len(errors) == len(req.Users) {
|
||||
respondBool(500, false, gc)
|
||||
app.err.Printf("Account deletion failed: %s", errors[req.Users[0]])
|
||||
@@ -443,23 +470,12 @@ func (app *appContext) DeleteUser(gc *gin.Context) {
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
type generateInviteDTO struct {
|
||||
Days int `json:"days" example:"1"` // Number of days
|
||||
Hours int `json:"hours" example:"2"` // Number of hours
|
||||
Minutes int `json:"minutes" example:"3"` // Number of minutes
|
||||
Email string `json:"email" example:"jeff@jellyf.in"` // Send invite to this address
|
||||
MultipleUses bool `json:"multiple-uses" example:"true"` // Allow multiple uses
|
||||
NoLimit bool `json:"no-limit" example:"false"` // No invite use limit
|
||||
RemainingUses int `json:"remaining-uses" example:"5"` // Remaining invite uses
|
||||
Profile string `json:"profile" example:"DefaultProfile"` // Name of profile to apply on this invite
|
||||
}
|
||||
|
||||
// @Summary Create a new invite.
|
||||
// @Produce json
|
||||
// @Param generateInviteDTO body generateInviteDTO true "New invite request object"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Router /invites [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Invites
|
||||
func (app *appContext) GenerateInvite(gc *gin.Context) {
|
||||
var req generateInviteDTO
|
||||
@@ -516,18 +532,13 @@ func (app *appContext) GenerateInvite(gc *gin.Context) {
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
type inviteProfileDTO struct {
|
||||
Invite string `json:"invite" example:"slakdaslkdl2342"` // Invite to apply to
|
||||
Profile string `json:"profile" example:"DefaultProfile"` // Profile to use
|
||||
}
|
||||
|
||||
// @Summary Set profile for an invite
|
||||
// @Produce json
|
||||
// @Param inviteProfileDTO body inviteProfileDTO true "Invite profile object"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /invites/profile [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Profiles & Settings
|
||||
func (app *appContext) SetProfile(gc *gin.Context) {
|
||||
var req inviteProfileDTO
|
||||
@@ -546,22 +557,11 @@ func (app *appContext) SetProfile(gc *gin.Context) {
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
type profileDTO struct {
|
||||
Admin bool `json:"admin" example:"false"` // Whether profile has admin rights or not
|
||||
LibraryAccess string `json:"libraries" example:"all"` // Number of libraries profile has access to
|
||||
FromUser string `json:"fromUser" example:"jeff"` // The user the profile is based on
|
||||
}
|
||||
|
||||
type getProfilesDTO struct {
|
||||
Profiles map[string]profileDTO `json:"profiles"`
|
||||
DefaultProfile string `json:"default_profile"`
|
||||
}
|
||||
|
||||
// @Summary Get a list of profiles
|
||||
// @Produce json
|
||||
// @Success 200 {object} getProfilesDTO
|
||||
// @Router /profiles [get]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Profiles & Settings
|
||||
func (app *appContext) GetProfiles(gc *gin.Context) {
|
||||
app.storage.loadProfiles()
|
||||
@@ -580,17 +580,13 @@ func (app *appContext) GetProfiles(gc *gin.Context) {
|
||||
gc.JSON(200, out)
|
||||
}
|
||||
|
||||
type profileChangeDTO struct {
|
||||
Name string `json:"name" example:"DefaultProfile" binding:"required"` // Name of the profile
|
||||
}
|
||||
|
||||
// @Summary Set the default profile to use.
|
||||
// @Produce json
|
||||
// @Param profileChangeDTO body profileChangeDTO true "Default profile object"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /profiles/default [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Profiles & Settings
|
||||
func (app *appContext) SetDefaultProfile(gc *gin.Context) {
|
||||
req := profileChangeDTO{}
|
||||
@@ -613,25 +609,19 @@ func (app *appContext) SetDefaultProfile(gc *gin.Context) {
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
type newProfileDTO struct {
|
||||
Name string `json:"name" example:"DefaultProfile" binding:"required"` // Name of the profile
|
||||
ID string `json:"id" example:"kasdjlaskjd342342" binding:"required"` // ID of user to source settings from
|
||||
Homescreen bool `json:"homescreen" example:"true"` // Whether to store homescreen layout or not
|
||||
}
|
||||
|
||||
// @Summary Create a profile based on a Jellyfin user's settings.
|
||||
// @Produce json
|
||||
// @Param newProfileDTO body newProfileDTO true "New profile object"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /profiles [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Profiles & Settings
|
||||
func (app *appContext) CreateProfile(gc *gin.Context) {
|
||||
fmt.Println("Profile creation requested")
|
||||
app.info.Println("Profile creation requested")
|
||||
var req newProfileDTO
|
||||
gc.BindJSON(&req)
|
||||
user, status, err := app.jf.userById(req.ID, false)
|
||||
user, status, err := app.jf.UserByID(req.ID, false)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get user from Jellyfin: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
@@ -645,7 +635,7 @@ func (app *appContext) CreateProfile(gc *gin.Context) {
|
||||
app.debug.Printf("Creating profile from user \"%s\"", user["Name"].(string))
|
||||
if req.Homescreen {
|
||||
profile.Configuration = user["Configuration"].(map[string]interface{})
|
||||
profile.Displayprefs, status, err = app.jf.getDisplayPreferences(req.ID)
|
||||
profile.Displayprefs, status, err = app.jf.GetDisplayPreferences(req.ID)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get DisplayPrefs: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
@@ -665,7 +655,7 @@ func (app *appContext) CreateProfile(gc *gin.Context) {
|
||||
// @Param profileChangeDTO body profileChangeDTO true "Delete profile object"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Router /profiles [delete]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Profiles & Settings
|
||||
func (app *appContext) DeleteProfile(gc *gin.Context) {
|
||||
req := profileChangeDTO{}
|
||||
@@ -678,40 +668,20 @@ func (app *appContext) DeleteProfile(gc *gin.Context) {
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
type inviteDTO struct {
|
||||
Code string `json:"code" example:"sajdlj23423j23"` // Invite code
|
||||
Days int `json:"days" example:"1"` // Number of days till expiry
|
||||
Hours int `json:"hours" example:"2"` // Number of hours till expiry
|
||||
Minutes int `json:"minutes" example:"3"` // Number of minutes till expiry
|
||||
Created string `json:"created" example:"01/01/20 12:00"` // Date of creation
|
||||
Profile string `json:"profile" example:"DefaultProfile"` // Profile used on this invite
|
||||
UsedBy [][]string `json:"used-by,omitempty"` // Users who have used this invite
|
||||
NoLimit bool `json:"no-limit,omitempty"` // If true, invite can be used any number of times
|
||||
RemainingUses int `json:"remaining-uses,omitempty"` // Remaining number of uses (if applicable)
|
||||
Email string `json:"email,omitempty"` // Email the invite was sent to (if applicable)
|
||||
NotifyExpiry bool `json:"notify-expiry,omitempty"` // Whether to notify the requesting user of expiry or not
|
||||
NotifyCreation bool `json:"notify-creation,omitempty"` // Whether to notify the requesting user of account creation or not
|
||||
}
|
||||
|
||||
type getInvitesDTO struct {
|
||||
Profiles []string `json:"profiles"` // List of profiles (name only)
|
||||
Invites []inviteDTO `json:"invites"` // List of invites
|
||||
}
|
||||
|
||||
// @Summary Get invites.
|
||||
// @Produce json
|
||||
// @Success 200 {object} getInvitesDTO
|
||||
// @Router /invites [get]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Invites
|
||||
func (app *appContext) GetInvites(gc *gin.Context) {
|
||||
app.debug.Println("Invites requested")
|
||||
current_time := time.Now()
|
||||
currentTime := time.Now()
|
||||
app.storage.loadInvites()
|
||||
app.checkInvites()
|
||||
var invites []inviteDTO
|
||||
for code, inv := range app.storage.invites {
|
||||
_, _, days, hours, minutes, _ := timeDiff(inv.ValidTill, current_time)
|
||||
_, _, days, hours, minutes, _ := timeDiff(inv.ValidTill, currentTime)
|
||||
invite := inviteDTO{
|
||||
Code: code,
|
||||
Days: days,
|
||||
@@ -772,14 +742,6 @@ func (app *appContext) GetInvites(gc *gin.Context) {
|
||||
gc.JSON(200, resp)
|
||||
}
|
||||
|
||||
// fake DTO, if i actually used this the code would be a lot longer
|
||||
type setNotifyValues map[string]struct {
|
||||
NotifyExpiry bool `json:"notify-expiry,omitempty"` // Whether to notify the requesting user of expiry or not
|
||||
NotifyCreation bool `json:"notify-creation,omitempty"` // Whether to notify the requesting user of account creation or not
|
||||
}
|
||||
|
||||
type setNotifyDTO map[string]setNotifyValues
|
||||
|
||||
// @Summary Set notification preferences for an invite.
|
||||
// @Produce json
|
||||
// @Param setNotifyDTO body setNotifyDTO true "Map of invite codes to notification settings objects"
|
||||
@@ -787,7 +749,7 @@ type setNotifyDTO map[string]setNotifyValues
|
||||
// @Failure 400 {object} stringResponse
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /invites/notify [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Other
|
||||
func (app *appContext) SetNotify(gc *gin.Context) {
|
||||
var req map[string]map[string]bool
|
||||
@@ -843,17 +805,13 @@ func (app *appContext) SetNotify(gc *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
type deleteInviteDTO struct {
|
||||
Code string `json:"code" example:"skjadajd43234s"` // Code of invite to delete
|
||||
}
|
||||
|
||||
// @Summary Delete an invite.
|
||||
// @Produce json
|
||||
// @Param deleteInviteDTO body deleteInviteDTO true "Delete invite object"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Failure 400 {object} stringResponse
|
||||
// @Router /invites [delete]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Invites
|
||||
func (app *appContext) DeleteInvite(gc *gin.Context) {
|
||||
var req deleteInviteDTO
|
||||
@@ -884,30 +842,18 @@ func parseDt(date string) time.Time {
|
||||
return parsed.Parsed
|
||||
}
|
||||
|
||||
type respUser struct {
|
||||
ID string `json:"id" example:"fdgsdfg45534fa"` // userID of user
|
||||
Name string `json:"name" example:"jeff"` // Username of user
|
||||
Email string `json:"email,omitempty" example:"jeff@jellyf.in"` // Email address of user (if available)
|
||||
LastActive string `json:"last_active"` // Time of last activity on Jellyfin
|
||||
Admin bool `json:"admin" example:"false"` // Whether or not the user is Administrator
|
||||
}
|
||||
|
||||
type getUsersDTO struct {
|
||||
UserList []respUser `json:"users"`
|
||||
}
|
||||
|
||||
// @Summary Get a list of Jellyfin users.
|
||||
// @Produce json
|
||||
// @Success 200 {object} getUsersDTO
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /users [get]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Users
|
||||
func (app *appContext) GetUsers(gc *gin.Context) {
|
||||
app.debug.Println("Users requested")
|
||||
var resp getUsersDTO
|
||||
resp.UserList = []respUser{}
|
||||
users, status, err := app.jf.getUsers(false)
|
||||
users, status, err := app.jf.GetUsers(false)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get users from Jellyfin: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
@@ -933,25 +879,16 @@ func (app *appContext) GetUsers(gc *gin.Context) {
|
||||
gc.JSON(200, resp)
|
||||
}
|
||||
|
||||
type ombiUser struct {
|
||||
Name string `json:"name,omitempty" example:"jeff"` // Name of Ombi user
|
||||
ID string `json:"id" example:"djgkjdg7dkjfsj8"` // userID of Ombi user
|
||||
}
|
||||
|
||||
type ombiUsersDTO struct {
|
||||
Users []ombiUser `json:"users"`
|
||||
}
|
||||
|
||||
// @Summary Get a list of Ombi users.
|
||||
// @Produce json
|
||||
// @Success 200 {object} ombiUsersDTO
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /ombi/users [get]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Ombi
|
||||
func (app *appContext) OmbiUsers(gc *gin.Context) {
|
||||
app.debug.Println("Ombi users requested")
|
||||
users, status, err := app.ombi.getUsers()
|
||||
users, status, err := app.ombi.GetUsers()
|
||||
if err != nil || status != 200 {
|
||||
app.err.Printf("Failed to get users from Ombi: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
@@ -974,48 +911,56 @@ func (app *appContext) OmbiUsers(gc *gin.Context) {
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /ombi/defaults [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Ombi
|
||||
func (app *appContext) SetOmbiDefaults(gc *gin.Context) {
|
||||
var req ombiUser
|
||||
gc.BindJSON(&req)
|
||||
template, code, err := app.ombi.templateByID(req.ID)
|
||||
template, code, err := app.ombi.TemplateByID(req.ID)
|
||||
if err != nil || code != 200 || len(template) == 0 {
|
||||
app.err.Printf("Couldn't get user from Ombi: %d %s", code, err)
|
||||
respond(500, "Couldn't get user", gc)
|
||||
return
|
||||
}
|
||||
app.storage.ombi_template = template
|
||||
fmt.Println(app.storage.ombi_path)
|
||||
app.storage.storeOmbiTemplate()
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
type modifyEmailsDTO map[string]string
|
||||
|
||||
// @Summary Modify user's email addresses.
|
||||
// @Produce json
|
||||
// @Param modifyEmailsDTO body modifyEmailsDTO true "Map of userIDs to email addresses"
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Failure 500 {object} stringResponse
|
||||
// @Router /users/emails [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Users
|
||||
func (app *appContext) ModifyEmails(gc *gin.Context) {
|
||||
var req modifyEmailsDTO
|
||||
gc.BindJSON(&req)
|
||||
fmt.Println(req)
|
||||
app.debug.Println("Email modification requested")
|
||||
users, status, err := app.jf.getUsers(false)
|
||||
users, status, err := app.jf.GetUsers(false)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get users from Jellyfin: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
respond(500, "Couldn't get users", gc)
|
||||
return
|
||||
}
|
||||
ombiEnabled := app.config.Section("ombi").Key("enabled").MustBool(false)
|
||||
for _, jfUser := range users {
|
||||
if address, ok := req[jfUser["Id"].(string)]; ok {
|
||||
id := jfUser["Id"].(string)
|
||||
if address, ok := req[id]; ok {
|
||||
app.storage.emails[jfUser["Id"].(string)] = address
|
||||
if ombiEnabled {
|
||||
ombiUser, code, err := app.getOmbiUser(id)
|
||||
if code == 200 && err == nil {
|
||||
ombiUser["emailAddress"] = address
|
||||
code, err = app.ombi.ModifyUser(ombiUser)
|
||||
if code != 200 || err != nil {
|
||||
app.err.Printf("%s: Failed to change ombi email address: %d %s", ombiUser["userName"].(string), code, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
app.storage.storeEmails()
|
||||
@@ -1023,59 +968,13 @@ func (app *appContext) ModifyEmails(gc *gin.Context) {
|
||||
respondBool(200, true, gc)
|
||||
}
|
||||
|
||||
/*func (app *appContext) SetDefaults(gc *gin.Context) {
|
||||
var req defaultsReq
|
||||
gc.BindJSON(&req)
|
||||
userID := req.ID
|
||||
user, status, err := app.jf.userById(userID, false)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get user from Jellyfin: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
respond(500, "Couldn't get user", gc)
|
||||
return
|
||||
}
|
||||
app.info.Printf("Getting user defaults from \"%s\"", user["Name"].(string))
|
||||
policy := user["Policy"].(map[string]interface{})
|
||||
app.storage.policy = policy
|
||||
app.storage.storePolicy()
|
||||
app.debug.Println("User policy template stored")
|
||||
if req.Homescreen {
|
||||
configuration := user["Configuration"].(map[string]interface{})
|
||||
var displayprefs map[string]interface{}
|
||||
displayprefs, status, err = app.jf.getDisplayPreferences(userID)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get DisplayPrefs: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
respond(500, "Couldn't get displayprefs", gc)
|
||||
return
|
||||
}
|
||||
app.storage.configuration = configuration
|
||||
app.storage.displayprefs = displayprefs
|
||||
app.storage.storeConfiguration()
|
||||
app.debug.Println("Configuration template stored")
|
||||
app.storage.storeDisplayprefs()
|
||||
app.debug.Println("DisplayPrefs template stored")
|
||||
}
|
||||
gc.JSON(200, map[string]bool{"success": true})
|
||||
}*/
|
||||
|
||||
type userSettingsDTO struct {
|
||||
From string `json:"from"` // Whether to apply from "user" or "profile"
|
||||
Profile string `json:"profile"` // Name of profile (if from = "profile")
|
||||
ApplyTo []string `json:"apply_to"` // Users to apply settings to
|
||||
ID string `json:"id"` // ID of user (if from = "user")
|
||||
Homescreen bool `json:"homescreen"` // Whether to apply homescreen layout or not
|
||||
}
|
||||
|
||||
type errorListDTO map[string]map[string]string
|
||||
|
||||
// @Summary Apply settings to a list of users, either from a profile or from another user.
|
||||
// @Produce json
|
||||
// @Param userSettingsDTO body userSettingsDTO true "Parameters for applying settings"
|
||||
// @Success 200 {object} errorListDTO
|
||||
// @Failure 500 {object} errorListDTO "Lists of errors that occured while applying settings"
|
||||
// @Router /users/settings [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Profiles & Settings
|
||||
func (app *appContext) ApplySettings(gc *gin.Context) {
|
||||
app.info.Println("User settings change requested")
|
||||
@@ -1102,7 +1001,7 @@ func (app *appContext) ApplySettings(gc *gin.Context) {
|
||||
policy = app.storage.profiles[req.Profile].Policy
|
||||
} else if req.From == "user" {
|
||||
applyingFrom = "user"
|
||||
user, status, err := app.jf.userById(req.ID, false)
|
||||
user, status, err := app.jf.UserByID(req.ID, false)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get user from Jellyfin: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
@@ -1112,7 +1011,7 @@ func (app *appContext) ApplySettings(gc *gin.Context) {
|
||||
applyingFrom = "\"" + user["Name"].(string) + "\""
|
||||
policy = user["Policy"].(map[string]interface{})
|
||||
if req.Homescreen {
|
||||
displayprefs, status, err = app.jf.getDisplayPreferences(req.ID)
|
||||
displayprefs, status, err = app.jf.GetDisplayPreferences(req.ID)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get DisplayPrefs: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
@@ -1128,17 +1027,17 @@ func (app *appContext) ApplySettings(gc *gin.Context) {
|
||||
"homescreen": map[string]string{},
|
||||
}
|
||||
for _, id := range req.ApplyTo {
|
||||
status, err := app.jf.setPolicy(id, policy)
|
||||
status, err := app.jf.SetPolicy(id, policy)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
errors["policy"][id] = fmt.Sprintf("%d: %s", status, err)
|
||||
}
|
||||
if req.Homescreen {
|
||||
status, err = app.jf.setConfiguration(id, configuration)
|
||||
status, err = app.jf.SetConfiguration(id, configuration)
|
||||
errorString := ""
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
errorString += fmt.Sprintf("Configuration %d: %s ", status, err)
|
||||
} else {
|
||||
status, err = app.jf.setDisplayPreferences(id, displayprefs)
|
||||
status, err = app.jf.SetDisplayPreferences(id, displayprefs)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
errorString += fmt.Sprintf("Displayprefs %d: %s ", status, err)
|
||||
}
|
||||
@@ -1159,11 +1058,27 @@ func (app *appContext) ApplySettings(gc *gin.Context) {
|
||||
// @Produce json
|
||||
// @Success 200 {object} configDTO "Uses the same format as config-base.json"
|
||||
// @Router /config [get]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Configuration
|
||||
func (app *appContext) GetConfig(gc *gin.Context) {
|
||||
app.info.Println("Config requested")
|
||||
resp := map[string]interface{}{}
|
||||
langPath := filepath.Join(app.local_path, "lang", "form")
|
||||
app.lang.langFiles, _ = ioutil.ReadDir(langPath)
|
||||
app.lang.langOptions = make([]string, len(app.lang.langFiles))
|
||||
chosenLang := app.config.Section("ui").Key("language").MustString("en-us") + ".json"
|
||||
for i, f := range app.lang.langFiles {
|
||||
if f.Name() == chosenLang {
|
||||
app.lang.chosenIndex = i
|
||||
}
|
||||
var langFile map[string]interface{}
|
||||
file, _ := ioutil.ReadFile(filepath.Join(langPath, f.Name()))
|
||||
json.Unmarshal(file, &langFile)
|
||||
|
||||
if meta, ok := langFile["meta"]; ok {
|
||||
app.lang.langOptions[i] = meta.(map[string]interface{})["name"].(string)
|
||||
}
|
||||
}
|
||||
for section, settings := range app.configBase {
|
||||
if section == "order" {
|
||||
resp[section] = settings.([]interface{})
|
||||
@@ -1183,6 +1098,9 @@ func (app *appContext) GetConfig(gc *gin.Context) {
|
||||
}
|
||||
} else if dataType == "bool" {
|
||||
resp[section].(map[string]interface{})[key].(map[string]interface{})["value"] = configKey.MustBool(false)
|
||||
} else if dataType == "select" && key == "language" {
|
||||
resp[section].(map[string]interface{})[key].(map[string]interface{})["options"] = app.lang.langOptions
|
||||
resp[section].(map[string]interface{})[key].(map[string]interface{})["value"] = app.lang.langOptions[app.lang.chosenIndex]
|
||||
} else {
|
||||
resp[section].(map[string]interface{})[key].(map[string]interface{})["value"] = configKey.String()
|
||||
}
|
||||
@@ -1191,17 +1109,16 @@ func (app *appContext) GetConfig(gc *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// resp["jellyfin"].(map[string]interface{})["language"].(map[string]interface{})["options"].([]string)
|
||||
gc.JSON(200, resp)
|
||||
}
|
||||
|
||||
type configDTO map[string]interface{}
|
||||
|
||||
// @Summary Modify app config.
|
||||
// @Produce json
|
||||
// @Param appConfig body configDTO true "Config split into sections as in config.ini, all values as strings."
|
||||
// @Success 200 {object} boolResponse
|
||||
// @Router /config [post]
|
||||
// @Security ApiKeyBlankPassword
|
||||
// @Security Bearer
|
||||
// @tags Configuration
|
||||
func (app *appContext) ModifyConfig(gc *gin.Context) {
|
||||
app.info.Println("Config modification requested")
|
||||
@@ -1215,7 +1132,16 @@ func (app *appContext) ModifyConfig(gc *gin.Context) {
|
||||
tempConfig.NewSection(section)
|
||||
}
|
||||
for setting, value := range settings.(map[string]interface{}) {
|
||||
tempConfig.Section(section).Key(setting).SetValue(value.(string))
|
||||
if section == "ui" && setting == "language" {
|
||||
for i, lang := range app.lang.langOptions {
|
||||
if value.(string) == lang {
|
||||
tempConfig.Section(section).Key(setting).SetValue(strings.Replace(app.lang.langFiles[i].Name(), ".json", "", 1))
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tempConfig.Section(section).Key(setting).SetValue(value.(string))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
238
auth.go
238
auth.go
@@ -46,14 +46,12 @@ func CreateToken(userId, jfId string) (string, string, error) {
|
||||
// Check header for token
|
||||
func (app *appContext) authenticate(gc *gin.Context) {
|
||||
header := strings.SplitN(gc.Request.Header.Get("Authorization"), " ", 2)
|
||||
if header[0] != "Basic" {
|
||||
app.debug.Println("Invalid authentication header")
|
||||
if header[0] != "Bearer" {
|
||||
app.debug.Println("Invalid authorization header")
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
auth, _ := base64.StdEncoding.DecodeString(header[1])
|
||||
creds := strings.SplitN(string(auth), ":", 2)
|
||||
token, err := jwt.Parse(creds[0], checkToken)
|
||||
token, err := jwt.Parse(string(header[1]), checkToken)
|
||||
if err != nil {
|
||||
app.debug.Printf("Auth denied: %s", err)
|
||||
respond(401, "Unauthorized", gc)
|
||||
@@ -103,146 +101,128 @@ type getTokenDTO struct {
|
||||
Token string `json:"token" example:"kjsdklsfdkljfsjsdfklsdfkldsfjdfskjsdfjklsdf"` // API token for use with everything else.
|
||||
}
|
||||
|
||||
// getToken checks the header for a username and password, as well as checking the refresh cookie.
|
||||
|
||||
// @Summary Grabs an API token using username & password, or via a refresh cookie.
|
||||
// @description Click the lock icon next to this, login with your normal jfa-go credentials. Click 'try it out', then 'execute' and an API Key will be returned, copy it (not including quotes). On any of the other routes, click the lock icon and use the token as your -Username-. The password can be anything.
|
||||
// @Summary Grabs an API token using username & password.
|
||||
// @description Click the lock icon next to this, login with your normal jfa-go credentials. Click 'try it out', then 'execute' and an API Key will be returned, copy it (not including quotes). On any of the other routes, click the lock icon and set the API key as "Bearer `your api key`".
|
||||
// @Produce json
|
||||
// @Success 200 {object} getTokenDTO
|
||||
// @Failure 401 {object} stringResponse
|
||||
// @Router /getToken [get]
|
||||
// @Router /token/login [get]
|
||||
// @tags Auth
|
||||
// @Security getTokenAuth
|
||||
func (app *appContext) getToken(gc *gin.Context) {
|
||||
func (app *appContext) getTokenLogin(gc *gin.Context) {
|
||||
app.info.Println("Token requested (login attempt)")
|
||||
header := strings.SplitN(gc.Request.Header.Get("Authorization"), " ", 2)
|
||||
auth, _ := base64.StdEncoding.DecodeString(header[1])
|
||||
creds := strings.SplitN(string(auth), ":", 2)
|
||||
// check cookie first
|
||||
var userID, jfID string
|
||||
valid := false
|
||||
noLogin := false
|
||||
checkLogin := func() {
|
||||
if creds[0] == "" || creds[1] == "" {
|
||||
app.debug.Println("Auth denied: blank username/password")
|
||||
respond(401, "Unauthorized", gc)
|
||||
if creds[0] == "" || creds[1] == "" {
|
||||
app.debug.Println("Auth denied: blank username/password")
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
match := false
|
||||
for _, user := range app.users {
|
||||
if user.Username == creds[0] && user.Password == creds[1] {
|
||||
match = true
|
||||
app.debug.Println("Found existing user")
|
||||
userID = user.UserID
|
||||
break
|
||||
}
|
||||
}
|
||||
if !app.jellyfinLogin && !match {
|
||||
app.info.Println("Auth denied: Invalid username/password")
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
if !match {
|
||||
var status int
|
||||
var err error
|
||||
var user map[string]interface{}
|
||||
user, status, err = app.authJf.Authenticate(creds[0], creds[1])
|
||||
if status != 200 || err != nil {
|
||||
if status == 401 || status == 400 {
|
||||
app.info.Println("Auth denied: Invalid username/password (Jellyfin)")
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
app.err.Printf("Auth failed: Couldn't authenticate with Jellyfin (%d/%s)", status, err)
|
||||
respond(500, "Jellyfin error", gc)
|
||||
return
|
||||
}
|
||||
match := false
|
||||
for _, user := range app.users {
|
||||
if user.Username == creds[0] && user.Password == creds[1] {
|
||||
match = true
|
||||
app.debug.Println("Found existing user")
|
||||
userID = user.UserID
|
||||
break
|
||||
}
|
||||
}
|
||||
if !app.jellyfinLogin && !match {
|
||||
app.info.Println("Auth denied: Invalid username/password")
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
if !match {
|
||||
var status int
|
||||
var err error
|
||||
var user map[string]interface{}
|
||||
user, status, err = app.authJf.authenticate(creds[0], creds[1])
|
||||
if status != 200 || err != nil {
|
||||
if status == 401 || status == 400 {
|
||||
app.info.Println("Auth denied: Invalid username/password (Jellyfin)")
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
app.err.Printf("Auth failed: Couldn't authenticate with Jellyfin (%d/%s)", status, err)
|
||||
respond(500, "Jellyfin error", gc)
|
||||
jfID = user["Id"].(string)
|
||||
if app.config.Section("ui").Key("admin_only").MustBool(true) {
|
||||
if !user["Policy"].(map[string]interface{})["IsAdministrator"].(bool) {
|
||||
app.debug.Printf("Auth denied: Users \"%s\" isn't admin", creds[0])
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
jfID = user["Id"].(string)
|
||||
if app.config.Section("ui").Key("admin_only").MustBool(true) {
|
||||
if !user["Policy"].(map[string]interface{})["IsAdministrator"].(bool) {
|
||||
app.debug.Printf("Auth denied: Users \"%s\" isn't admin", creds[0])
|
||||
respond(401, "Unauthorized", gc)
|
||||
return
|
||||
}
|
||||
}
|
||||
// New users are only added when using jellyfinLogin.
|
||||
userID = shortuuid.New()
|
||||
newUser := User{
|
||||
UserID: userID,
|
||||
}
|
||||
app.debug.Printf("Token generated for user \"%s\"", creds[0])
|
||||
app.users = append(app.users, newUser)
|
||||
}
|
||||
valid = true
|
||||
}
|
||||
checkCookie := func() {
|
||||
cookie, err := gc.Cookie("refresh")
|
||||
if err == nil && cookie != "" {
|
||||
for _, token := range app.invalidTokens {
|
||||
if cookie == token {
|
||||
if creds[0] == "" || creds[1] == "" {
|
||||
app.debug.Println("getToken denied: Invalid refresh token and no username/password provided")
|
||||
respond(401, "Unauthorized", gc)
|
||||
noLogin = true
|
||||
return
|
||||
}
|
||||
app.debug.Println("getToken: Invalid token but username/password provided")
|
||||
return
|
||||
}
|
||||
}
|
||||
token, err := jwt.Parse(cookie, checkToken)
|
||||
if err != nil {
|
||||
if creds[0] == "" || creds[1] == "" {
|
||||
app.debug.Println("getToken denied: Invalid refresh token and no username/password provided")
|
||||
respond(401, "Unauthorized", gc)
|
||||
noLogin = true
|
||||
return
|
||||
}
|
||||
app.debug.Println("getToken: Invalid token but username/password provided")
|
||||
return
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
expiryUnix, err := strconv.ParseInt(claims["exp"].(string), 10, 64)
|
||||
if err != nil {
|
||||
if creds[0] == "" || creds[1] == "" {
|
||||
app.debug.Printf("getToken denied: Invalid token (%s) and no username/password provided", err)
|
||||
respond(401, "Unauthorized", gc)
|
||||
noLogin = true
|
||||
return
|
||||
}
|
||||
app.debug.Printf("getToken: Invalid token (%s) but username/password provided", err)
|
||||
return
|
||||
}
|
||||
expiry := time.Unix(expiryUnix, 0)
|
||||
if !(ok && token.Valid && claims["type"].(string) == "refresh" && expiry.After(time.Now())) {
|
||||
if creds[0] == "" || creds[1] == "" {
|
||||
app.debug.Printf("getToken denied: Invalid token (%s) and no username/password provided", err)
|
||||
respond(401, "Unauthorized", gc)
|
||||
noLogin = true
|
||||
return
|
||||
}
|
||||
app.debug.Printf("getToken: Invalid token (%s) but username/password provided", err)
|
||||
return
|
||||
}
|
||||
userID = claims["id"].(string)
|
||||
jfID = claims["jfid"].(string)
|
||||
valid = true
|
||||
// New users are only added when using jellyfinLogin.
|
||||
userID = shortuuid.New()
|
||||
newUser := User{
|
||||
UserID: userID,
|
||||
}
|
||||
app.debug.Printf("Token generated for user \"%s\"", creds[0])
|
||||
app.users = append(app.users, newUser)
|
||||
}
|
||||
checkCookie()
|
||||
if !valid && !noLogin {
|
||||
checkLogin()
|
||||
}
|
||||
if valid {
|
||||
token, refresh, err := CreateToken(userID, jfID)
|
||||
if err != nil {
|
||||
app.err.Printf("getToken failed: Couldn't generate token (%s)", err)
|
||||
respond(500, "Couldn't generate token", gc)
|
||||
return
|
||||
}
|
||||
gc.SetCookie("refresh", refresh, (3600 * 24), "/", gc.Request.URL.Hostname(), true, true)
|
||||
gc.JSON(200, getTokenDTO{token})
|
||||
} else {
|
||||
gc.AbortWithStatus(401)
|
||||
token, refresh, err := CreateToken(userID, jfID)
|
||||
if err != nil {
|
||||
app.err.Printf("getToken failed: Couldn't generate token (%s)", err)
|
||||
respond(500, "Couldn't generate token", gc)
|
||||
return
|
||||
}
|
||||
gc.SetCookie("refresh", refresh, (3600 * 24), "/", gc.Request.URL.Hostname(), true, true)
|
||||
gc.JSON(200, getTokenDTO{token})
|
||||
}
|
||||
|
||||
// @Summary Grabs an API token using a refresh token from cookies.
|
||||
// @Produce json
|
||||
// @Success 200 {object} getTokenDTO
|
||||
// @Failure 401 {object} stringResponse
|
||||
// @Router /token/refresh [get]
|
||||
// @tags Auth
|
||||
func (app *appContext) getTokenRefresh(gc *gin.Context) {
|
||||
app.debug.Println("Token requested (refresh token)")
|
||||
cookie, err := gc.Cookie("refresh")
|
||||
if err != nil || cookie == "" {
|
||||
app.debug.Printf("getTokenRefresh denied: Couldn't get token: %s", err)
|
||||
respond(400, "Couldn't get token", gc)
|
||||
return
|
||||
}
|
||||
for _, token := range app.invalidTokens {
|
||||
if cookie == token {
|
||||
app.debug.Println("getTokenRefresh: Invalid token")
|
||||
respond(401, "Invalid token", gc)
|
||||
return
|
||||
}
|
||||
}
|
||||
token, err := jwt.Parse(cookie, checkToken)
|
||||
if err != nil {
|
||||
app.debug.Println("getTokenRefresh: Invalid token")
|
||||
respond(400, "Invalid token", gc)
|
||||
return
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
expiryUnix, err := strconv.ParseInt(claims["exp"].(string), 10, 64)
|
||||
if err != nil {
|
||||
app.debug.Printf("getTokenRefresh: Invalid token expiry: %s", err)
|
||||
respond(401, "Invalid token", gc)
|
||||
return
|
||||
}
|
||||
expiry := time.Unix(expiryUnix, 0)
|
||||
if !(ok && token.Valid && claims["type"].(string) == "refresh" && expiry.After(time.Now())) {
|
||||
app.debug.Printf("getTokenRefresh: Invalid token: %s", err)
|
||||
respond(401, "Invalid token", gc)
|
||||
return
|
||||
}
|
||||
userID := claims["id"].(string)
|
||||
jfID := claims["jfid"].(string)
|
||||
jwt, refresh, err := CreateToken(userID, jfID)
|
||||
if err != nil {
|
||||
app.err.Printf("getTokenRefresh failed: Couldn't generate token (%s)", err)
|
||||
respond(500, "Couldn't generate token", gc)
|
||||
return
|
||||
}
|
||||
gc.SetCookie("refresh", refresh, (3600 * 24), "/", gc.Request.URL.Hostname(), true, true)
|
||||
gc.JSON(200, getTokenDTO{jwt})
|
||||
}
|
||||
|
||||
23
common/common.go
Normal file
23
common/common.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
// TimeoutHandler recovers from an http timeout.
|
||||
type TimeoutHandler func()
|
||||
|
||||
// NewTimeoutHandler returns a new Timeout handler.
|
||||
func NewTimeoutHandler(name, addr string, noFail bool) TimeoutHandler {
|
||||
return func() {
|
||||
if r := recover(); r != nil {
|
||||
out := fmt.Sprintf("Failed to authenticate with %s @ %s: Timed out", name, addr)
|
||||
if noFail {
|
||||
log.Print(out)
|
||||
} else {
|
||||
log.Fatalf(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
3
common/go.mod
Normal file
3
common/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module github.com/hrfee/jfa-go/common
|
||||
|
||||
go 1.15
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
@@ -46,7 +47,9 @@ func (app *appContext) loadConfig() error {
|
||||
// if key.MustString("") == "" && key.Name() != "custom_css" {
|
||||
// key.SetValue(filepath.Join(app.data_path, (key.Name() + ".json")))
|
||||
// }
|
||||
key.SetValue(key.MustString(filepath.Join(app.data_path, (key.Name() + ".json"))))
|
||||
if key.Name() != "html_templates" {
|
||||
key.SetValue(key.MustString(filepath.Join(app.data_path, (key.Name() + ".json"))))
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"user_configuration", "user_displayprefs", "user_profiles", "ombi_template"} {
|
||||
// if app.config.Section("files").Key(key).MustString("") == "" {
|
||||
@@ -72,6 +75,10 @@ func (app *appContext) loadConfig() error {
|
||||
app.config.Section("deletion").Key("email_html").SetValue(app.config.Section("deletion").Key("email_html").MustString(filepath.Join(app.local_path, "deleted.html")))
|
||||
app.config.Section("deletion").Key("email_text").SetValue(app.config.Section("deletion").Key("email_text").MustString(filepath.Join(app.local_path, "deleted.txt")))
|
||||
|
||||
app.config.Section("jellyfin").Key("version").SetValue(VERSION)
|
||||
app.config.Section("jellyfin").Key("device").SetValue("jfa-go")
|
||||
app.config.Section("jellyfin").Key("device_id").SetValue(fmt.Sprintf("jfa-go-%s-%s", VERSION, COMMIT))
|
||||
|
||||
app.email = NewEmailer(app)
|
||||
|
||||
return nil
|
||||
|
||||
@@ -41,28 +41,15 @@
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "jfa-go",
|
||||
"description": "This and below settings will show on the Jellyfin dashboard when the program connects. You may as well leave them alone."
|
||||
"description": "The name of the client that will show up in the Jellyfin dashboard."
|
||||
},
|
||||
"version": {
|
||||
"name": "Version Number",
|
||||
"required": true,
|
||||
"cache_timeout": {
|
||||
"name": "User cache timeout (minutes)",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "{version}"
|
||||
},
|
||||
"device": {
|
||||
"name": "Device Name",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "jfa-go"
|
||||
},
|
||||
"device_id": {
|
||||
"name": "Device ID",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "jfa-go-{version}"
|
||||
"type": "number",
|
||||
"value": 30,
|
||||
"description": "Timeout of user cache in minutes. Set to 0 to disable."
|
||||
}
|
||||
},
|
||||
"ui": {
|
||||
@@ -70,6 +57,17 @@
|
||||
"name": "General",
|
||||
"description": "Settings related to the UI and program functionality."
|
||||
},
|
||||
"language": {
|
||||
"name": "Language",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "select",
|
||||
"options": [
|
||||
"en-us"
|
||||
],
|
||||
"value": "en-US",
|
||||
"description": "UI Language. Currently only implemented for account creation form. Submit a PR on github if you'd like to translate."
|
||||
},
|
||||
"theme": {
|
||||
"name": "Default Look",
|
||||
"required": false,
|
||||
@@ -180,7 +178,7 @@
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": false,
|
||||
"description": "Use Bootstrap 5 (currently in alpha). This also removes the need for jQuery, so the page should load faster."
|
||||
"description": "Use the Bootstrap 5 Alpha. Looks better and removes the need for jQuery, so the page should load faster."
|
||||
}
|
||||
},
|
||||
"password_validation": {
|
||||
@@ -476,6 +474,14 @@
|
||||
"name": "SMTP (Email)",
|
||||
"description": "SMTP Server connection settings."
|
||||
},
|
||||
"username": {
|
||||
"name": "Username",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Username for SMTP. Leave blank to user send from address as username."
|
||||
},
|
||||
"encryption": {
|
||||
"name": "Encryption Method",
|
||||
"required": false,
|
||||
@@ -514,7 +520,7 @@
|
||||
"ombi": {
|
||||
"meta": {
|
||||
"name": "Ombi Integration",
|
||||
"description": "Connect to Ombi to automatically create a new user's account. You'll need to create an Ombi user template."
|
||||
"description": "Connect to Ombi to automatically create both Ombi and Jellyfin accounts for new users. You'll need to create a user template for this to work. Once enabled, refresh to see an option in settings for this."
|
||||
},
|
||||
"enabled": {
|
||||
"name": "Enabled",
|
||||
@@ -603,28 +609,28 @@
|
||||
"description": "Location of stored Ombi user template."
|
||||
},
|
||||
"user_template": {
|
||||
"name": "User Template",
|
||||
"name": "User Template (Deprecated)",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Deprecated. Location of stored user policy template (json)."
|
||||
"description": "Deprecated in favor of User Profiles. Location of stored user policy template (json)."
|
||||
},
|
||||
"user_configuration": {
|
||||
"name": "userConfiguration",
|
||||
"name": "userConfiguration (Deprecated)",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Deprecated. Location of stored user configuration template (used for setting homescreen layout) (json)"
|
||||
"description": "Deprecated in favor of User Profiles. Location of stored user configuration template (used for setting homescreen layout) (json)"
|
||||
},
|
||||
"user_displayprefs": {
|
||||
"name": "displayPreferences",
|
||||
"name": "displayPreferences (Deprecated)",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Deprecated. Location of stored displayPreferences template (also used for homescreen layout) (json)"
|
||||
"description": "Deprecated in favor of User Profiles. Location of stored displayPreferences template (also used for homescreen layout) (json)"
|
||||
},
|
||||
"user_profiles": {
|
||||
"name": "User Profiles",
|
||||
@@ -641,6 +647,14 @@
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Location of custom bootstrap CSS."
|
||||
},
|
||||
"html_templates": {
|
||||
"name": "Custom HTML Template Directory",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to directory containing custom versions of web ui pages. See wiki for more info."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,8 @@ import json
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-i", "--input", help="input config base from jf-accounts")
|
||||
parser.add_argument("-o", "--output", help="output ini")
|
||||
parser.add_argument("--version", help="version to include in file")
|
||||
|
||||
|
||||
def generate_ini(base_file, ini_file, version):
|
||||
def generate_ini(base_file, ini_file):
|
||||
"""
|
||||
Generates .ini file from config-base file.
|
||||
"""
|
||||
@@ -32,20 +27,16 @@ def generate_ini(base_file, ini_file, version):
|
||||
value = str(value)
|
||||
ini.set(section, entry, value)
|
||||
|
||||
ini["jellyfin"]["version"] = version
|
||||
ini["jellyfin"]["device_id"] = ini["jellyfin"]["device_id"].replace(
|
||||
"{version}", version
|
||||
)
|
||||
|
||||
with open(Path(ini_file), "w") as config_file:
|
||||
ini.write(config_file)
|
||||
return True
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("-i", "--input", help="input config base from jf-accounts")
|
||||
parser.add_argument("-o", "--output", help="output ini")
|
||||
|
||||
version = "git"
|
||||
if args.version is not None:
|
||||
version = args.version
|
||||
args = parser.parse_args()
|
||||
|
||||
print(generate_ini(base_file=args.input, ini_file=args.output, version=version))
|
||||
print(generate_ini(base_file=args.input, ini_file=args.output))
|
||||
|
||||
@@ -1,753 +0,0 @@
|
||||
{
|
||||
"order": [
|
||||
"jellyfin",
|
||||
"ui",
|
||||
"password_validation",
|
||||
"email",
|
||||
"password_resets",
|
||||
"invite_emails",
|
||||
"notifications",
|
||||
"mailgun",
|
||||
"smtp",
|
||||
"ombi",
|
||||
"deletion",
|
||||
"files"
|
||||
],
|
||||
"jellyfin": {
|
||||
"order": [
|
||||
"username",
|
||||
"password",
|
||||
"server",
|
||||
"public_server",
|
||||
"client",
|
||||
"version",
|
||||
"device",
|
||||
"device_id"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Jellyfin",
|
||||
"description": "Settings for connecting to Jellyfin"
|
||||
},
|
||||
"username": {
|
||||
"name": "Jellyfin Username",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "username",
|
||||
"description": "It is recommended to create a limited admin account for this program."
|
||||
},
|
||||
"password": {
|
||||
"name": "Jellyfin Password",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "password",
|
||||
"value": "password"
|
||||
},
|
||||
"server": {
|
||||
"name": "Server address",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "http://jellyfin.local:8096",
|
||||
"description": "Jellyfin server address. Can be public, or local for security purposes."
|
||||
},
|
||||
"public_server": {
|
||||
"name": "Public address",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "https://jellyf.in:443",
|
||||
"description": "Publicly accessible Jellyfin address for invite form. Leave blank to reuse the above address."
|
||||
},
|
||||
"client": {
|
||||
"name": "Client Name",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "jfa-go",
|
||||
"description": "This and below settings will show on the Jellyfin dashboard when the program connects. You may as well leave them alone."
|
||||
},
|
||||
"version": {
|
||||
"name": "Version Number",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "{version}"
|
||||
},
|
||||
"device": {
|
||||
"name": "Device Name",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "jfa-go"
|
||||
},
|
||||
"device_id": {
|
||||
"name": "Device ID",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "jfa-go-{version}"
|
||||
}
|
||||
},
|
||||
"ui": {
|
||||
"order": [
|
||||
"theme",
|
||||
"host",
|
||||
"port",
|
||||
"jellyfin_login",
|
||||
"admin_only",
|
||||
"username",
|
||||
"password",
|
||||
"email",
|
||||
"debug",
|
||||
"contact_message",
|
||||
"help_message",
|
||||
"success_message",
|
||||
"bs5"
|
||||
],
|
||||
"meta": {
|
||||
"name": "General",
|
||||
"description": "Settings related to the UI and program functionality."
|
||||
},
|
||||
"theme": {
|
||||
"name": "Default Look",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "select",
|
||||
"options": [
|
||||
"Bootstrap (Light)",
|
||||
"Jellyfin (Dark)",
|
||||
"Custom CSS"
|
||||
],
|
||||
"value": "Jellyfin (Dark)",
|
||||
"description": "Default appearance for all users."
|
||||
},
|
||||
"host": {
|
||||
"name": "Address",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "0.0.0.0",
|
||||
"description": "Set 0.0.0.0 to run on localhost"
|
||||
},
|
||||
"port": {
|
||||
"name": "Port",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"type": "number",
|
||||
"value": 8056
|
||||
},
|
||||
"jellyfin_login": {
|
||||
"name": "Use Jellyfin for authentication",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": true,
|
||||
"description": "Enable this to use Jellyfin users instead of the below username and pw."
|
||||
},
|
||||
"admin_only": {
|
||||
"name": "Allow admin users only",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"depends_true": "jellyfin_login",
|
||||
"type": "bool",
|
||||
"value": true,
|
||||
"description": "Allows only admin users on Jellyfin to access the admin page."
|
||||
},
|
||||
"username": {
|
||||
"name": "Web Username",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"depends_false": "jellyfin_login",
|
||||
"type": "text",
|
||||
"value": "your username",
|
||||
"description": "Username for admin page (Leave blank if using jellyfin_login)"
|
||||
},
|
||||
"password": {
|
||||
"name": "Web Password",
|
||||
"required": true,
|
||||
"requires_restart": true,
|
||||
"depends_false": "jellyfin_login",
|
||||
"type": "password",
|
||||
"value": "your password",
|
||||
"description": "Password for admin page (Leave blank if using jellyfin_login)"
|
||||
},
|
||||
"email": {
|
||||
"name": "Admin email address",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_false": "jellyfin_login",
|
||||
"type": "text",
|
||||
"value": "example@example.com",
|
||||
"description": "Address to send notifications to (Leave blank if using jellyfin_login)"
|
||||
},
|
||||
"debug": {
|
||||
"name": "Debug logging",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": false,
|
||||
"description": "Enables debug logging and exposes pprof as a route (Don't use in production!)"
|
||||
},
|
||||
"contact_message": {
|
||||
"name": "Contact message",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "Need help? contact me.",
|
||||
"description": "Displayed at bottom of all pages except admin"
|
||||
},
|
||||
"help_message": {
|
||||
"name": "Help message",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "Enter your details to create an account.",
|
||||
"description": "Displayed at top of invite form."
|
||||
},
|
||||
"success_message": {
|
||||
"name": "Success message",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "Your account has been created. Click below to continue to Jellyfin.",
|
||||
"description": "Displayed when a user creates an account"
|
||||
},
|
||||
"bs5": {
|
||||
"name": "Use Bootstrap 5",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": false,
|
||||
"description": "Use Bootstrap 5 (currently in alpha). This also removes the need for jQuery, so the page should load faster."
|
||||
}
|
||||
},
|
||||
"password_validation": {
|
||||
"order": [
|
||||
"enabled",
|
||||
"min_length",
|
||||
"upper",
|
||||
"lower",
|
||||
"number",
|
||||
"special"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Password Validation",
|
||||
"description": "Password validation (minimum length, etc.)"
|
||||
},
|
||||
"enabled": {
|
||||
"name": "Enabled",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
"min_length": {
|
||||
"name": "Minimum Length",
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "8"
|
||||
},
|
||||
"upper": {
|
||||
"name": "Minimum uppercase characters",
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "1"
|
||||
},
|
||||
"lower": {
|
||||
"name": "Minimum lowercase characters",
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "0"
|
||||
},
|
||||
"number": {
|
||||
"name": "Minimum number count",
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "1"
|
||||
},
|
||||
"special": {
|
||||
"name": "Minimum number of special characters",
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "0"
|
||||
}
|
||||
},
|
||||
"email": {
|
||||
"order": [
|
||||
"no_username",
|
||||
"use_24h",
|
||||
"date_format",
|
||||
"message",
|
||||
"method",
|
||||
"address",
|
||||
"from"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Email",
|
||||
"description": "General email settings. Ignore if not using email features."
|
||||
},
|
||||
"no_username": {
|
||||
"name": "Use email addresses as username",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "method",
|
||||
"type": "bool",
|
||||
"value": false,
|
||||
"description": "Use email address from invite form as username on Jellyfin."
|
||||
},
|
||||
"use_24h": {
|
||||
"name": "Use 24h time",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "method",
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
"date_format": {
|
||||
"name": "Date format",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "method",
|
||||
"type": "text",
|
||||
"value": "%d/%m/%y",
|
||||
"description": "Date format used in emails. Follows datetime.strftime format."
|
||||
},
|
||||
"message": {
|
||||
"name": "Help message",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "method",
|
||||
"type": "text",
|
||||
"value": "Need help? contact me.",
|
||||
"description": "Message displayed at bottom of emails."
|
||||
},
|
||||
"method": {
|
||||
"name": "Email method",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "select",
|
||||
"options": [
|
||||
"smtp",
|
||||
"mailgun"
|
||||
],
|
||||
"value": "smtp",
|
||||
"description": "Method of sending email to use."
|
||||
},
|
||||
"address": {
|
||||
"name": "Sent from (address)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "method",
|
||||
"type": "email",
|
||||
"value": "jellyfin@jellyf.in",
|
||||
"description": "Address to send emails from"
|
||||
},
|
||||
"from": {
|
||||
"name": "Sent from (name)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "method",
|
||||
"type": "text",
|
||||
"value": "Jellyfin",
|
||||
"description": "The name of the sender"
|
||||
}
|
||||
},
|
||||
"password_resets": {
|
||||
"order": [
|
||||
"enabled",
|
||||
"watch_directory",
|
||||
"email_html",
|
||||
"email_text",
|
||||
"subject"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Password Resets",
|
||||
"description": "Settings for the password reset handler."
|
||||
},
|
||||
"enabled": {
|
||||
"name": "Enabled",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": true,
|
||||
"description": "Enable to store provided email addresses, monitor Jellyfin directory for pw-resets, and send reset pins"
|
||||
},
|
||||
"watch_directory": {
|
||||
"name": "Jellyfin directory",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "/path/to/jellyfin",
|
||||
"description": "Path to the folder Jellyfin puts password-reset files."
|
||||
},
|
||||
"email_html": {
|
||||
"name": "Custom email (HTML)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to custom email html"
|
||||
},
|
||||
"email_text": {
|
||||
"name": "Custom email (plaintext)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to custom email in plain text"
|
||||
},
|
||||
"subject": {
|
||||
"name": "Email subject",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "Password Reset - Jellyfin",
|
||||
"description": "Subject of password reset emails."
|
||||
}
|
||||
},
|
||||
"invite_emails": {
|
||||
"order": [
|
||||
"enabled",
|
||||
"email_html",
|
||||
"email_text",
|
||||
"subject",
|
||||
"url_base"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Invite emails",
|
||||
"description": "Settings for sending invites directly to users."
|
||||
},
|
||||
"enabled": {
|
||||
"name": "Enabled",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "bool",
|
||||
"value": true
|
||||
},
|
||||
"email_html": {
|
||||
"name": "Custom email (HTML)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to custom email HTML"
|
||||
},
|
||||
"email_text": {
|
||||
"name": "Custom email (plaintext)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to custom email in plain text"
|
||||
},
|
||||
"subject": {
|
||||
"name": "Email subject",
|
||||
"required": true,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "Invite - Jellyfin",
|
||||
"description": "Subject of invite emails."
|
||||
},
|
||||
"url_base": {
|
||||
"name": "URL Base",
|
||||
"required": true,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "http://accounts.jellyf.in:8056/invite",
|
||||
"description": "Base URL for jfa-go. This is necessary because using a reverse proxy means the program has no way of knowing the URL itself."
|
||||
}
|
||||
},
|
||||
"notifications": {
|
||||
"order": [
|
||||
"enabled",
|
||||
"expiry_html",
|
||||
"expiry_text",
|
||||
"created_html",
|
||||
"created_text"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Notifications",
|
||||
"description": "Notification related settings."
|
||||
},
|
||||
"enabled": {
|
||||
"name": "Enabled",
|
||||
"required": "false",
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": true,
|
||||
"description": "Enabling adds optional toggles to invites to notify on expiry and user creation."
|
||||
},
|
||||
"expiry_html": {
|
||||
"name": "Expiry email (HTML)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to expiry notification email HTML."
|
||||
},
|
||||
"expiry_text": {
|
||||
"name": "Expiry email (Plaintext)",
|
||||
"required": false,
|
||||
"requires_restart": "false",
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to expiry notification email in plaintext."
|
||||
},
|
||||
"created_html": {
|
||||
"name": "User created email (HTML)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to user creation notification email HTML."
|
||||
},
|
||||
"created_text": {
|
||||
"name": "User created email (Plaintext)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"depends_true": "enabled",
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to user creation notification email in plaintext."
|
||||
}
|
||||
},
|
||||
"mailgun": {
|
||||
"order": [
|
||||
"api_url",
|
||||
"api_key"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Mailgun (Email)",
|
||||
"description": "Mailgun API connection settings"
|
||||
},
|
||||
"api_url": {
|
||||
"name": "API URL",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "https://api.mailgun.net..."
|
||||
},
|
||||
"api_key": {
|
||||
"name": "API Key",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "your api key"
|
||||
}
|
||||
},
|
||||
"smtp": {
|
||||
"order": [
|
||||
"encryption",
|
||||
"server",
|
||||
"port",
|
||||
"password"
|
||||
],
|
||||
"meta": {
|
||||
"name": "SMTP (Email)",
|
||||
"description": "SMTP Server connection settings."
|
||||
},
|
||||
"encryption": {
|
||||
"name": "Encryption Method",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "select",
|
||||
"options": [
|
||||
"ssl_tls",
|
||||
"starttls"
|
||||
],
|
||||
"value": "starttls",
|
||||
"description": "Your email provider should provide different ports for each encryption method. Generally 465 for ssl_tls, 587 for starttls."
|
||||
},
|
||||
"server": {
|
||||
"name": "Server address",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "smtp.jellyf.in",
|
||||
"description": "SMTP Server address."
|
||||
},
|
||||
"port": {
|
||||
"name": "Port",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "number",
|
||||
"value": 465
|
||||
},
|
||||
"password": {
|
||||
"name": "Password",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "password",
|
||||
"value": "smtp password"
|
||||
}
|
||||
},
|
||||
"ombi": {
|
||||
"order": [
|
||||
"enabled",
|
||||
"server",
|
||||
"api_key"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Ombi Integration",
|
||||
"description": "Connect to Ombi to automatically create a new user's account. You'll need to create an Ombi user template."
|
||||
},
|
||||
"enabled": {
|
||||
"name": "Enabled",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "bool",
|
||||
"value": false,
|
||||
"description": "Enable to create an Ombi account for new Jellyfin users"
|
||||
},
|
||||
"server": {
|
||||
"name": "URL",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "localhost:5000",
|
||||
"depends_true": "enabled",
|
||||
"description": "Ombi server URL, including http(s)://."
|
||||
},
|
||||
"api_key": {
|
||||
"name": "API Key",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"depends_true": "enabled",
|
||||
"description": "API Key. Get this from the first tab in Ombi settings."
|
||||
}
|
||||
},
|
||||
"deletion": {
|
||||
"order": [
|
||||
"subject",
|
||||
"email_html",
|
||||
"email_text"
|
||||
],
|
||||
"meta": {
|
||||
"name": "Account Deletion",
|
||||
"description": "Subject/email files for account deletion emails."
|
||||
},
|
||||
"subject": {
|
||||
"name": "Email subject",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "Your account was deleted - Jellyfin",
|
||||
"description": "Subject of account deletion emails."
|
||||
},
|
||||
"email_html": {
|
||||
"name": "Custom email (HTML)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to custom email html"
|
||||
},
|
||||
"email_text": {
|
||||
"name": "Custom email (plaintext)",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Path to custom email in plain text"
|
||||
}
|
||||
},
|
||||
"files": {
|
||||
"order": [
|
||||
"invites",
|
||||
"emails",
|
||||
"ombi_template",
|
||||
"user_template",
|
||||
"user_configuration",
|
||||
"user_displayprefs",
|
||||
"user_profiles",
|
||||
"custom_css"
|
||||
],
|
||||
"meta": {
|
||||
"name": "File Storage",
|
||||
"description": "Optional settings for changing storage locations."
|
||||
},
|
||||
"invites": {
|
||||
"name": "Invite Storage",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Location of stored invites (json)."
|
||||
},
|
||||
"emails": {
|
||||
"name": "Email Addresses",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Location of stored email addresses (json)."
|
||||
},
|
||||
"ombi_template": {
|
||||
"name": "Ombi user template",
|
||||
"required": false,
|
||||
"requires_restart": false,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Location of stored Ombi user template."
|
||||
},
|
||||
"user_template": {
|
||||
"name": "User Template",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Deprecated. Location of stored user policy template (json)."
|
||||
},
|
||||
"user_configuration": {
|
||||
"name": "userConfiguration",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Deprecated. Location of stored user configuration template (used for setting homescreen layout) (json)"
|
||||
},
|
||||
"user_displayprefs": {
|
||||
"name": "displayPreferences",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Deprecated. Location of stored displayPreferences template (also used for homescreen layout) (json)"
|
||||
},
|
||||
"user_profiles": {
|
||||
"name": "User Profiles",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Location of stored user profiles (encompasses template and configuration and displayprefs) (json)"
|
||||
},
|
||||
"custom_css": {
|
||||
"name": "Custom CSS",
|
||||
"required": false,
|
||||
"requires_restart": true,
|
||||
"type": "text",
|
||||
"value": "",
|
||||
"description": "Location of custom bootstrap CSS."
|
||||
}
|
||||
}
|
||||
}
|
||||
41
data/lang/form/en-us.json
Normal file
41
data/lang/form/en-us.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"meta": {
|
||||
"name": "English (US)"
|
||||
},
|
||||
"strings": {
|
||||
"pageTitle": "Create Jellyfin Account",
|
||||
"createAccountHeader": "Create Account",
|
||||
"accountDetails": "Details",
|
||||
"emailAddress": "Email",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"reEnterPassword": "Re-enter Password",
|
||||
"reEnterPasswordInvalid": "Passwords are not the same.",
|
||||
"createAccountButton": "Create Account",
|
||||
"passwordRequirementsHeader": "Password Requirements",
|
||||
"successHeader": "Success!",
|
||||
"successContinueButton": "Continue",
|
||||
"validationStrings": {
|
||||
"length": {
|
||||
"singular": "Must have at least {n} character",
|
||||
"plural": "Must have a least {n} characters"
|
||||
},
|
||||
"uppercase": {
|
||||
"singular": "Must have at least {n} uppercase character",
|
||||
"plural": "Must have at least {n} uppercase characters"
|
||||
},
|
||||
"lowercase": {
|
||||
"singular": "Must have at least {n} lowercase character",
|
||||
"plural": "Must have at least {n} lowercase characters"
|
||||
},
|
||||
"number": {
|
||||
"singular": "Must have at least {n} number",
|
||||
"plural": "Must have at least {n} numbers"
|
||||
},
|
||||
"special": {
|
||||
"singular": "Must have at least {n} special character",
|
||||
"plural": "Must have at least {n} special characters"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
42
data/lang/form/fr-fr.json
Normal file
42
data/lang/form/fr-fr.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"meta": {
|
||||
"name": "Francais (FR)",
|
||||
"author": "https://github.com/Killianbe"
|
||||
},
|
||||
"strings": {
|
||||
"pageTitle": "Créer un compte Jellyfin",
|
||||
"createAccountHeader": "Création du compte",
|
||||
"accountDetails": "Détails",
|
||||
"emailAddress": "Email",
|
||||
"username": "Pseudo",
|
||||
"password": "Mot de passe",
|
||||
"reEnterPassword": "Confirmez mot de passe",
|
||||
"reEnterPasswordInvalid": "Les mots de passe ne correspondent pas.",
|
||||
"createAccountButton": "Créer le compte",
|
||||
"passwordRequirementsHeader": "Mot de passe requis",
|
||||
"successHeader": "Succes!",
|
||||
"successContinueButton": "Continuer",
|
||||
"validationStrings": {
|
||||
"length": {
|
||||
"singular": "Doit avoir au moins {n} caractère",
|
||||
"plural": "Doit avoir au moins {n} caractères"
|
||||
},
|
||||
"uppercase": {
|
||||
"singular": "Doit avoir au moins {n} caractère majuscule",
|
||||
"plural": "Must have at least {n} caractères majuscules"
|
||||
},
|
||||
"lowercase": {
|
||||
"singular": "Doit avoir au moins {n} caractère minuscule",
|
||||
"plural": "Doit avoir au moins {n} caractères minuscules"
|
||||
},
|
||||
"number": {
|
||||
"singular": "Doit avoir au moins {n} nombre",
|
||||
"plural": "Doit avoir au moins {n} nombres"
|
||||
},
|
||||
"special": {
|
||||
"singular": "Doit avoir au moins {n} caractère spécial",
|
||||
"plural": "Doit avoir au moins {n} caractères spéciaux"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,11 @@
|
||||
return "";
|
||||
}
|
||||
{{ if .bs5 }}
|
||||
var bsVersion = 5;
|
||||
window.bsVersion = 5;
|
||||
{{ else }}
|
||||
var bsVersion = 4;
|
||||
window.bsVersion = 4;
|
||||
{{ end }}
|
||||
var cssFile = "{{ .cssFile }}";
|
||||
window.cssFile = "{{ .cssFile }}";
|
||||
var css = document.createElement('link');
|
||||
css.setAttribute('rel', 'stylesheet');
|
||||
css.setAttribute('type', 'text/css');
|
||||
@@ -93,8 +93,10 @@
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="usersTitle">Users</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<button type="button" class="{{ if .bs5 }}btn-{{ end }}close" data-dismiss="modal" aria-label="Close">
|
||||
{{ if not .bs5 }}
|
||||
<span aria-hidden="true">×</span>
|
||||
{{ end }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -112,8 +114,10 @@
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="defaultsTitle"></h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<button type="button" class="{{ if .bs5 }}btn-{{ end }}close" data-dismiss="modal" aria-label="Close">
|
||||
{{ if not .bs5 }}
|
||||
<span aria-hidden="true">×</span>
|
||||
{{ end }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -156,8 +160,10 @@
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="ombiTitle">Ombi user defaults</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<button type="button" class="{{ if .bs5 }}btn-{{ end }}close" data-dismiss="modal" aria-label="Close">
|
||||
{{ if not .bs5 }}
|
||||
<span aria-hidden="true">×</span>
|
||||
{{ end }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -206,15 +212,17 @@
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">About</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<button type="button" class="{{ if .bs5 }}btn-{{ end }}close" data-dismiss="modal" aria-label="Close">
|
||||
{{ if not .bs5 }}
|
||||
<span aria-hidden="true">×</span>
|
||||
{{ end }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<img src="banner.svg" alt="jfa-go banner">
|
||||
<p><a href="https://github.com/hrfee/jfa-go"><i class="fa fa-github"></i> jfa-go</a></p>
|
||||
<p>Version <i>{{ .version }}</i></p>
|
||||
<p>Commit <i>{{ .commit }}</i></p>
|
||||
<p>Version <i class="text-monospace">{{ .version }}</i></p>
|
||||
<p>Commit <i class="text-monospace">{{ .commit }}</i></p>
|
||||
<p><a href="https://github.com/hrfee/jfa-go/blob/main/LICENSE">Available under the MIT License.</a></p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -225,8 +233,10 @@
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="deleteModalTitle"></h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<button type="button" class="{{ if .bs5 }}btn-{{ end }}close" data-dismiss="modal" aria-label="Close">
|
||||
{{ if not .bs5 }}
|
||||
<span aria-hidden="true">×</span>
|
||||
{{ end }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -251,8 +261,10 @@
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Create a user</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<button type="button" class="{{ if .bs5 }}btn-{{ end }}close" data-dismiss="modal" aria-label="Close">
|
||||
{{ if not .bs5 }}
|
||||
<span aria-hidden="true">×</span>
|
||||
{{ end }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -397,7 +409,6 @@
|
||||
<th scope="col">Username</th>
|
||||
<th scope="col">Email Address</th>
|
||||
<th scope="col">Last Active</th>
|
||||
<th scope="col">Admin?</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="accountsList">
|
||||
@@ -426,7 +437,7 @@
|
||||
User Profiles <i class="fa fa-user settingIcon"></i>
|
||||
</button>
|
||||
{{ if .ombiEnabled }}
|
||||
<button type="button" class="list-group-item list-group-item-action static" id="openOmbiDefaults">
|
||||
<button type="button" class="list-group-item list-group-item-action static" id="openOmbiDefaults" onclick="window.openOmbiDefaults()">
|
||||
Ombi User Defaults <i class="fa fa-chain-broken settingIcon"></i>
|
||||
</button>
|
||||
{{ end }}
|
||||
@@ -465,27 +476,19 @@
|
||||
<p>{{ .contactMessage }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<script src="serialize.js"></script>
|
||||
<script>
|
||||
var availableProfiles = [];
|
||||
<script>
|
||||
window.bs5 = {{ .bs5 }};
|
||||
window.availableProfiles = [];
|
||||
{{ if .notifications }}
|
||||
var notifications_enabled = true;
|
||||
window.notifications_enabled = true;
|
||||
{{ else }}
|
||||
var notifications_enabled = false;
|
||||
window.notifications_enabled = false;
|
||||
{{ end }}
|
||||
</script>
|
||||
{{ if .bs5 }}
|
||||
<script src="bs5.js"></script>
|
||||
{{ else }}
|
||||
<script src="bs4.js"></script>
|
||||
{{ end }}
|
||||
<script src="animation.js"></script>
|
||||
<script src="accounts.js"></script>
|
||||
<script src="invites.js"></script>
|
||||
<script src="admin.js"></script>
|
||||
<script src="settings.js"></script>
|
||||
<script src="admin.js" type="module"></script>
|
||||
<script src="invites.js" type="module"></script>
|
||||
{{ if .ombiEnabled }}
|
||||
<script src="ombi.js"></script>
|
||||
<script src="ombi.js" type="module"></script>
|
||||
{{ end }}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
9
data/templates/form-base.html
Normal file
9
data/templates/form-base.html
Normal file
@@ -0,0 +1,9 @@
|
||||
{{ define "form-base" }}
|
||||
<script>
|
||||
window.bs5 = {{ .settings.bs5 }};
|
||||
window.usernameEnabled = {{ .settings.username }};
|
||||
window.validationStrings = JSON.parse({{ .lang.validationStrings }});
|
||||
window.invalidPassword = "{{ .lang.reEnterPasswordInvalid }}";
|
||||
</script>
|
||||
<script src="form.js" type="module"></script>
|
||||
{{ end }}
|
||||
1
data/templates/form-loader.html
Normal file
1
data/templates/form-loader.html
Normal file
@@ -0,0 +1 @@
|
||||
{{ template "form.html" . }}
|
||||
@@ -14,11 +14,11 @@
|
||||
|
||||
<!-- Bootstrap CSS -->
|
||||
<link rel="stylesheet" type="text/css" href="{{ .cssFile }}">
|
||||
{{ if not .bs5 }}
|
||||
{{ if not .settings.bs5 }}
|
||||
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
|
||||
{{ end }}
|
||||
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
|
||||
{{ if .bs5 }}
|
||||
{{ if .settings.bs5 }}
|
||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
|
||||
{{ else }}
|
||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
|
||||
@@ -41,27 +41,27 @@
|
||||
margin-bottom: 5%;
|
||||
}
|
||||
</style>
|
||||
<title>Create Jellyfin Account</title>
|
||||
<title>{{ .lang.pageTitle }}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="modal fade" id="successBox" tabindex="-1" role="dialog" aria-labelledby="successBox" aria-hidden="true" data-backdrop="static">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="successTitle">Success!</h5>
|
||||
<h5 class="modal-title" id="successHeader">{{ .lang.successHeader }}</h5>
|
||||
</div>
|
||||
<div class="modal-body" id="successBody">
|
||||
<p>{{ .successMessage }}</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="{{ .jfLink }}" class="btn btn-primary">Continue</a>
|
||||
<a href="{{ .jfLink }}" class="btn btn-primary">{{ .lang.successContinueButton }}</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pageContainer">
|
||||
<h1>
|
||||
Create Account
|
||||
{{ .lang.createAccountHeader }}
|
||||
</h1>
|
||||
<p>{{ .helpMessage }}</p>
|
||||
<p class="contactBox">{{ .contactMessage }}</p>
|
||||
@@ -69,26 +69,30 @@
|
||||
<div class="row" id="cardContainer">
|
||||
<div class="col-sm">
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">Details</div>
|
||||
<div class="card-header">{{ .lang.accountDetails }}</div>
|
||||
<div class="card-body">
|
||||
<form action="#" method="POST" id="accountForm">
|
||||
<div class="form-group">
|
||||
<label for="inputEmail">Email</label>
|
||||
<input type="email" class="form-control" id="{{ if .username }}inputEmail{{ else }}inputUsername{{ end }}" name="{{ if .username }}email{{ else }}username{{ end }}" placeholder="Email" value="{{ .email }}" required>
|
||||
<label for="inputEmail">{{ .lang.emailAddress }}</label>
|
||||
<input type="email" class="form-control" id="{{ if .settings.username }}inputEmail{{ else }}inputUsername{{ end }}" name="{{ if .settings.username }}email{{ else }}username{{ end }}" placeholder="{{ .lang.emailAddress }}" value="{{ .email }}" required>
|
||||
</div>
|
||||
{{ if .username }}
|
||||
{{ if .settings.username }}
|
||||
<div class="form-group">
|
||||
<label for="inputUsername">Username</label>
|
||||
<input type="username" class="form-control" id="inputUsername" name="username" placeholder="Username" required>
|
||||
<label for="inputUsername">{{ .lang.username }}</label>
|
||||
<input type="username" class="form-control" id="inputUsername" name="username" placeholder="{{ .lang.username }}" required>
|
||||
</div>
|
||||
{{ end }}
|
||||
<div class="form-group">
|
||||
<label for="inputPassword">Password</label>
|
||||
<input type="password" class="form-control" id="inputPassword" name="password" placeholder="Password" required>
|
||||
<label for="inputPassword">{{ .lang.password }}</label>
|
||||
<input type="password" class="form-control" id="inputPassword" name="password" placeholder="{{ .lang.password }}" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="inputPassword">{{ .lang.reEnterPassword }}</label>
|
||||
<input type="password" class="form-control" id="reInputPassword" onkeyup="window.checkPassword()" placeholder="{{ .lang.password }}" required>
|
||||
</div>
|
||||
<div class="btn-group" role="group" aria-label="Button & Error" id="errorBox" style="margin-top: 1rem;">
|
||||
<button type="submit" class="btn btn-outline-primary" id="submitButton">
|
||||
<span id="createAccount">Create Account</span>
|
||||
<span id="createAccount">{{ .lang.createAccountButton }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -98,12 +102,12 @@
|
||||
{{ if .validate }}
|
||||
<div class="col-sm" id="requirementBox">
|
||||
<div class="card mb-3 requirementBox">
|
||||
<div class="card-header">Password Requirements</div>
|
||||
<div class="card-header">{{ .lang.passwordRequirementsHeader }}</div>
|
||||
<div class="card-body">
|
||||
<ul class="list-group">
|
||||
{{ range $key, $value := .requirements }}
|
||||
<li id="{{ $key }}" class="list-group-item list-group-item-danger">
|
||||
<div> {{ $value }}</div>
|
||||
<li id="{{ $key }}" min="{{ $value }}" class="list-group-item list-group-item-danger">
|
||||
<div></div>
|
||||
</li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
@@ -114,109 +118,10 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="serialize.js"></script>
|
||||
<script>
|
||||
{{ if .bs5 }}
|
||||
var bsVersion = 5;
|
||||
{{ else }}
|
||||
var bsVersion = 4;
|
||||
{{ end }}
|
||||
if (bsVersion == 5) {
|
||||
var successBox = new bootstrap.Modal(document.getElementById('successBox'));
|
||||
} else if (bsVersion == 4) {
|
||||
var successBox = {
|
||||
show : function() {
|
||||
return $('#successBox').modal('show');
|
||||
},
|
||||
hide : function() {
|
||||
return $('#successBox').modal('hide');
|
||||
}
|
||||
};
|
||||
};
|
||||
var code = window.location.href.split('/').pop();
|
||||
function toggleSpinner () {
|
||||
var submitButton = document.getElementById('submitButton');
|
||||
var oldSpan = document.getElementById('createAccount');
|
||||
var newSpan = document.createElement('span');
|
||||
newSpan.id = 'createAccount';
|
||||
if (document.getElementById('createAccountSpinner')) {
|
||||
newSpan.appendChild(document.createTextNode('Create Account'));
|
||||
submitButton.disabled = false;
|
||||
} else {
|
||||
var spinner = document.createElement('span');
|
||||
spinner.id = 'createAccountSpinner';
|
||||
spinner.classList.add('spinner-border', 'spinner-border-sm');
|
||||
spinner.setAttribute('role', 'status');
|
||||
spinner.setAttribute('aria-hidden', 'true');
|
||||
var text = document.createTextNode(' Creating...');
|
||||
newSpan.appendChild(spinner);
|
||||
newSpan.appendChild(text);
|
||||
submitButton.disabled = true;
|
||||
}
|
||||
submitButton.replaceChild(newSpan, oldSpan);
|
||||
};
|
||||
document.getElementById('accountForm').onsubmit = function() {
|
||||
if (document.getElementById('errorMessage')) {
|
||||
document.getElementById('errorMessage').remove();
|
||||
}
|
||||
toggleSpinner();
|
||||
var send = serializeForm('accountForm');
|
||||
send['code'] = code;
|
||||
{{ if not .username }}
|
||||
send['email'] = send['username'];
|
||||
{{ end }}
|
||||
send = JSON.stringify(send);
|
||||
var req = new XMLHttpRequest();
|
||||
req.open("POST", "/newUser", true);
|
||||
req.responseType = 'json';
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = function() {
|
||||
if (this.readyState == 4) {
|
||||
toggleSpinner();
|
||||
var data = this.response;
|
||||
if ('error' in data || data['success'] == false) {
|
||||
if (typeof(data['error']) != 'undefined') {
|
||||
var errorMessage = data['error'];
|
||||
} else {
|
||||
var errorMessage = 'Unknown Error';
|
||||
}
|
||||
var text = document.createTextNode(errorMessage);
|
||||
var error = document.createElement('button');
|
||||
error.classList.add('btn', 'btn-outline-danger');
|
||||
error.setAttribute('disabled', '');
|
||||
error.appendChild(text);
|
||||
error.id = 'errorMessage';
|
||||
document.getElementById('errorBox').appendChild(error);
|
||||
} else {
|
||||
var valid = true
|
||||
for (var key in data) {
|
||||
if (data.hasOwnProperty(key)) {
|
||||
var criterion = document.getElementById(key);
|
||||
if (criterion) {
|
||||
if (data[key] == false) {
|
||||
valid = false;
|
||||
if (criterion.classList.contains('list-group-item-success')) {
|
||||
criterion.classList.remove('list-group-item-success');
|
||||
criterion.classList.add('list-group-item-danger');
|
||||
};
|
||||
} else {
|
||||
if (criterion.classList.contains('list-group-item-danger')) {
|
||||
criterion.classList.remove('list-group-item-danger');
|
||||
criterion.classList.add('list-group-item-success');
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
if (valid == true) {
|
||||
successBox.show();
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
req.send(send);
|
||||
return false;
|
||||
};
|
||||
window.validationStrings = {{ .lang.validationStrings }};
|
||||
</script>
|
||||
{{ template "form-base" . }}
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
module github.com/hrfee/jfa-go/docs
|
||||
|
||||
go 1.15
|
||||
|
||||
require (
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
|
||||
github.com/swaggo/swag v1.6.7
|
||||
)
|
||||
|
||||
27
email.go
27
email.go
@@ -41,10 +41,10 @@ func (mg *Mailgun) send(address, fromName, fromAddr string, email *Email) error
|
||||
|
||||
// SMTP supports SSL/TLS and STARTTLS; implements emailClient.
|
||||
type SMTP struct {
|
||||
sslTLS bool
|
||||
host, server string
|
||||
port int
|
||||
auth smtp.Auth
|
||||
sslTLS bool
|
||||
server string
|
||||
port int
|
||||
auth smtp.Auth
|
||||
}
|
||||
|
||||
func (sm *SMTP) send(address, fromName, fromAddr string, email *Email) error {
|
||||
@@ -54,12 +54,14 @@ func (sm *SMTP) send(address, fromName, fromAddr string, email *Email) error {
|
||||
e.To = []string{address}
|
||||
e.Text = []byte(email.text)
|
||||
e.HTML = []byte(email.html)
|
||||
server := fmt.Sprintf("%s:%d", sm.server, sm.port)
|
||||
tlsConfig := &tls.Config{
|
||||
InsecureSkipVerify: false,
|
||||
ServerName: sm.host,
|
||||
ServerName: sm.server,
|
||||
}
|
||||
server := fmt.Sprintf("%s:%d", sm.server, sm.port)
|
||||
var err error
|
||||
fmt.Println(server)
|
||||
// err = e.Send(server, sm.auth)
|
||||
if sm.sslTLS {
|
||||
err = e.SendWithTLS(server, sm.auth, tlsConfig)
|
||||
} else {
|
||||
@@ -113,7 +115,13 @@ func NewEmailer(app *appContext) *Emailer {
|
||||
if app.config.Section("smtp").Key("encryption").String() == "ssl_tls" {
|
||||
sslTls = true
|
||||
}
|
||||
emailer.NewSMTP(app.config.Section("smtp").Key("server").String(), app.config.Section("smtp").Key("port").MustInt(465), app.config.Section("smtp").Key("password").String(), app.host, sslTls)
|
||||
username := ""
|
||||
if u := app.config.Section("smtp").Key("username").MustString(""); u != "" {
|
||||
username = u
|
||||
} else {
|
||||
username = emailer.fromAddr
|
||||
}
|
||||
emailer.NewSMTP(app.config.Section("smtp").Key("server").String(), app.config.Section("smtp").Key("port").MustInt(465), username, app.config.Section("smtp").Key("password").String(), sslTls)
|
||||
} else if method == "mailgun" {
|
||||
emailer.NewMailgun(app.config.Section("mailgun").Key("api_url").String(), app.config.Section("mailgun").Key("api_key").String())
|
||||
}
|
||||
@@ -135,11 +143,10 @@ func (emailer *Emailer) NewMailgun(url, key string) {
|
||||
}
|
||||
|
||||
// NewSMTP returns an SMTP emailClient.
|
||||
func (emailer *Emailer) NewSMTP(server string, port int, password, host string, sslTLS bool) {
|
||||
func (emailer *Emailer) NewSMTP(server string, port int, username, password string, sslTLS bool) {
|
||||
emailer.sender = &SMTP{
|
||||
auth: smtp.PlainAuth("", emailer.fromAddr, password, host),
|
||||
auth: smtp.PlainAuth("", username, password, server),
|
||||
server: server,
|
||||
host: host,
|
||||
port: port,
|
||||
sslTLS: sslTLS,
|
||||
}
|
||||
|
||||
5
esbuild.sh
Executable file
5
esbuild.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/bash
|
||||
# set +e
|
||||
# npx tsc -p ts/
|
||||
# set -e
|
||||
npx esbuild ts/* --outdir=data/static --minify
|
||||
46
go.mod
46
go.mod
@@ -4,38 +4,52 @@ go 1.14
|
||||
|
||||
replace github.com/hrfee/jfa-go/docs => ./docs
|
||||
|
||||
replace github.com/hrfee/jfa-go/jfapi => ./jfapi
|
||||
|
||||
replace github.com/hrfee/jfa-go/common => ./common
|
||||
|
||||
replace github.com/hrfee/jfa-go/ombi => ./ombi
|
||||
|
||||
require (
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/fsnotify/fsnotify v1.4.9
|
||||
github.com/gin-contrib/pprof v1.3.0
|
||||
github.com/gin-contrib/static v0.0.0-20200815103939-31fb0c56a3d1
|
||||
github.com/gin-contrib/static v0.0.0-20200916080430-d45d9a37d28e
|
||||
github.com/gin-gonic/gin v1.6.3
|
||||
github.com/go-chi/chi v4.1.2+incompatible // indirect
|
||||
github.com/go-openapi/spec v0.19.9 // indirect
|
||||
github.com/go-openapi/swag v0.19.9 // indirect
|
||||
github.com/go-playground/validator/v10 v10.3.0 // indirect
|
||||
github.com/golang/protobuf v1.4.2 // indirect
|
||||
github.com/hrfee/jfa-go/docs v0.0.0-00010101000000-000000000000
|
||||
github.com/jordan-wright/email v0.0.0-20200602115436-fd8a7622303e
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/spec v0.19.13 // indirect
|
||||
github.com/go-playground/validator/v10 v10.4.1 // indirect
|
||||
github.com/golang/protobuf v1.4.3
|
||||
github.com/google/uuid v1.1.2 // indirect
|
||||
github.com/hrfee/jfa-go/common v0.0.0-20201112212552-b6f3cd7c1f71
|
||||
github.com/hrfee/jfa-go/docs v0.0.0-20201112212552-b6f3cd7c1f71
|
||||
github.com/hrfee/jfa-go/jfapi v0.0.0-20201112212552-b6f3cd7c1f71
|
||||
github.com/hrfee/jfa-go/ombi v0.0.0-20201112212552-b6f3cd7c1f71
|
||||
github.com/jordan-wright/email v4.0.1-0.20200917010138-e1c00e156980+incompatible
|
||||
github.com/json-iterator/go v1.1.10 // indirect
|
||||
github.com/knz/strtime v0.0.0-20200318182718-be999391ffa9
|
||||
github.com/knz/strtime v0.0.0-20200924090105-187c67f2bf5e
|
||||
github.com/lithammer/shortuuid/v3 v3.0.4
|
||||
github.com/logrusorgru/aurora/v3 v3.0.0
|
||||
github.com/mailgun/mailgun-go/v4 v4.1.3
|
||||
github.com/mailgun/mailgun-go/v4 v4.3.0
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.1 // indirect
|
||||
github.com/pdrum/swagger-automation v0.0.0-20190629163613-c8c7c80ba858
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14
|
||||
github.com/swaggo/gin-swagger v1.2.0
|
||||
github.com/swaggo/swag v1.6.7 // indirect
|
||||
github.com/urfave/cli/v2 v2.2.0 // indirect
|
||||
golang.org/x/net v0.0.0-20200923182212-328152dc79b1 // indirect
|
||||
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed // indirect
|
||||
golang.org/x/tools v0.0.0-20200924182824-0f1c53950d78 // indirect
|
||||
github.com/swaggo/gin-swagger v1.3.0
|
||||
github.com/swaggo/swag v1.6.9 // indirect
|
||||
github.com/ugorji/go v1.2.0 // indirect
|
||||
github.com/urfave/cli/v2 v2.3.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9 // indirect
|
||||
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b // indirect
|
||||
golang.org/x/sys v0.0.0-20201113233024-12cec1faf1ba // indirect
|
||||
golang.org/x/text v0.3.4 // indirect
|
||||
golang.org/x/tools v0.0.0-20201114224030-61ea331ec02b // indirect
|
||||
google.golang.org/protobuf v1.25.0 // indirect
|
||||
gopkg.in/ini.v1 v1.60.0
|
||||
gopkg.in/ini.v1 v1.62.0
|
||||
gopkg.in/yaml.v2 v2.3.0 // indirect
|
||||
)
|
||||
|
||||
100
go.sum
100
go.sum
@@ -41,6 +41,8 @@ github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2 h1:xLG16iua01X7
|
||||
github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2/go.mod h1:VhW/Ch/3FhimwZb8Oj+qJmdMmoB8r7lmJ5auRjm50oQ=
|
||||
github.com/gin-contrib/static v0.0.0-20200815103939-31fb0c56a3d1 h1:plQYoJeO9lI8Ag0xZy7dDF8FMwIOHsQylKjcclknvIc=
|
||||
github.com/gin-contrib/static v0.0.0-20200815103939-31fb0c56a3d1/go.mod h1:VhW/Ch/3FhimwZb8Oj+qJmdMmoB8r7lmJ5auRjm50oQ=
|
||||
github.com/gin-contrib/static v0.0.0-20200916080430-d45d9a37d28e h1:8bZpGwoPxkaivQPrAbWl+7zjjUcbFUnYp7yQcx2r2N0=
|
||||
github.com/gin-contrib/static v0.0.0-20200916080430-d45d9a37d28e/go.mod h1:VhW/Ch/3FhimwZb8Oj+qJmdMmoB8r7lmJ5auRjm50oQ=
|
||||
github.com/gin-gonic/gin v1.3.0/go.mod h1:7cKuhb5qV2ggCFctp2fJQ+ErvciLZrIeoOSOm6mUr7Y=
|
||||
github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM=
|
||||
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
|
||||
@@ -55,6 +57,8 @@ github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwds
|
||||
github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg=
|
||||
github.com/go-openapi/jsonpointer v0.19.3 h1:gihV7YNZK1iK6Tgwwsxo2rJbD1GTbdm72325Bq8FI3w=
|
||||
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
|
||||
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||
github.com/go-openapi/jsonreference v0.17.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I=
|
||||
github.com/go-openapi/jsonreference v0.19.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I=
|
||||
github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc=
|
||||
@@ -67,12 +71,22 @@ github.com/go-openapi/spec v0.19.4 h1:ixzUSnHTd6hCemgtAJgluaTSGYpLNpJY4mA2DIkdOA
|
||||
github.com/go-openapi/spec v0.19.4/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo=
|
||||
github.com/go-openapi/spec v0.19.9 h1:9z9cbFuZJ7AcvOHKIY+f6Aevb4vObNDkTEyoMfO7rAc=
|
||||
github.com/go-openapi/spec v0.19.9/go.mod h1:vqK/dIdLGCosfvYsQV3WfC7N3TiZSnGY2RZKoFK7X28=
|
||||
github.com/go-openapi/spec v0.19.10 h1:pcNevfYytLaOQuTju0wm6OqcqU/E/pRwuSGigrLTI28=
|
||||
github.com/go-openapi/spec v0.19.10/go.mod h1:vqK/dIdLGCosfvYsQV3WfC7N3TiZSnGY2RZKoFK7X28=
|
||||
github.com/go-openapi/spec v0.19.12 h1:OO9WrvhDwtiMY/Opr1j1iFZzirI3JW4/bxNFRcntAr4=
|
||||
github.com/go-openapi/spec v0.19.12/go.mod h1:gwrgJS15eCUgjLpMjBJmbZezCsw88LmgeEip0M63doA=
|
||||
github.com/go-openapi/spec v0.19.13 h1:AcZVcWsrfW7LqyHKVbTZYpFF7jQcMxmAsWrw2p/b9ew=
|
||||
github.com/go-openapi/spec v0.19.13/go.mod h1:gwrgJS15eCUgjLpMjBJmbZezCsw88LmgeEip0M63doA=
|
||||
github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg=
|
||||
github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
|
||||
github.com/go-openapi/swag v0.19.5 h1:lTz6Ys4CmqqCQmZPBlbQENR1/GucA2bzYTE12Pw4tFY=
|
||||
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
|
||||
github.com/go-openapi/swag v0.19.9 h1:1IxuqvBUU3S2Bi4YC7tlP9SJF1gVpCvqN0T2Qof4azE=
|
||||
github.com/go-openapi/swag v0.19.9/go.mod h1:ao+8BpOPyKdpQz3AOJfbeEVpLmWAvlT1IfTe5McPyhY=
|
||||
github.com/go-openapi/swag v0.19.10 h1:A1SWXruroGP15P1sOiegIPbaKio+G9N5TwWTFaVPmAU=
|
||||
github.com/go-openapi/swag v0.19.10/go.mod h1:Uc0gKkdR+ojzsEpjh39QChyu92vPgIr72POcgHMAgSY=
|
||||
github.com/go-openapi/swag v0.19.11 h1:RFTu/dlFySpyVvJDfp/7674JY4SDglYWKztbiIGFpmc=
|
||||
github.com/go-openapi/swag v0.19.11/go.mod h1:Uc0gKkdR+ojzsEpjh39QChyu92vPgIr72POcgHMAgSY=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=
|
||||
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||
@@ -84,6 +98,11 @@ github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1
|
||||
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||
github.com/go-playground/validator/v10 v10.3.0 h1:nZU+7q+yJoFmwvNgv/LnPUkwPal62+b2xXj0AU1Es7o=
|
||||
github.com/go-playground/validator/v10 v10.3.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
|
||||
github.com/go-playground/validator/v10 v10.4.0 h1:72qIR/m8ybvL8L5TIyfgrigqkrw7kVYAvjEvpT85l70=
|
||||
github.com/go-playground/validator/v10 v10.4.0/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
|
||||
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
|
||||
github.com/gofrs/uuid v3.3.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
@@ -99,6 +118,8 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq
|
||||
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||
github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
@@ -107,8 +128,12 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jordan-wright/email v0.0.0-20200602115436-fd8a7622303e h1:OGunVjqY7y4U4laftpEHv+mvZBlr7UGimJXKEGQtg48=
|
||||
github.com/jordan-wright/email v0.0.0-20200602115436-fd8a7622303e/go.mod h1:Fy2gCFfZhay8jplf/Csj6cyH/oshQTkLQYZbKkcV+SY=
|
||||
github.com/jordan-wright/email v4.0.1-0.20200917010138-e1c00e156980+incompatible h1:CL0ooBNfbNyJTJATno+m0h+zM5bW6v7fKlboKUGP/dI=
|
||||
github.com/jordan-wright/email v4.0.1-0.20200917010138-e1c00e156980+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||
@@ -120,6 +145,8 @@ github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr
|
||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/knz/strtime v0.0.0-20200318182718-be999391ffa9 h1:GQE1iatYDRrIidq4Zf/9ZzKWyrTk2sXOYc1JADbkAjQ=
|
||||
github.com/knz/strtime v0.0.0-20200318182718-be999391ffa9/go.mod h1:4ZxfWkxwtc7dBeifERVVWRy9F9rTU9p0yCDgeCtlius=
|
||||
github.com/knz/strtime v0.0.0-20200924090105-187c67f2bf5e h1:ViPE0JEOvtw5I0EGUiFSr2VNKGNU+3oBT+oHbDXHbxk=
|
||||
github.com/knz/strtime v0.0.0-20200924090105-187c67f2bf5e/go.mod h1:4ZxfWkxwtc7dBeifERVVWRy9F9rTU9p0yCDgeCtlius=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA=
|
||||
@@ -142,6 +169,10 @@ github.com/mailgun/mailgun-go v1.1.1 h1:mjMcm4qz+SbjAYbGJ6DKROViKtO5S0YjpuOUxQfd
|
||||
github.com/mailgun/mailgun-go v2.0.0+incompatible h1:0FoRHWwMUctnd8KIR3vtZbqdfjpIMxOZgcSa51s8F8o=
|
||||
github.com/mailgun/mailgun-go/v4 v4.1.3 h1:KLa5EZaOMMeyvY/lfAhWxv9ealB3mtUsMz0O9XmTtP0=
|
||||
github.com/mailgun/mailgun-go/v4 v4.1.3/go.mod h1:R9kHUQBptF4iSEjhriCQizplCDwrnDShy8w/iPiOfaM=
|
||||
github.com/mailgun/mailgun-go/v4 v4.2.0 h1:AAt7TwR98Pog7zAYK61SW7ikykFFmCovtix3vvS2cK4=
|
||||
github.com/mailgun/mailgun-go/v4 v4.2.0/go.mod h1:R9kHUQBptF4iSEjhriCQizplCDwrnDShy8w/iPiOfaM=
|
||||
github.com/mailgun/mailgun-go/v4 v4.3.0 h1:9nAF7LI3k6bfDPbMZQMMl63Q8/vs+dr1FUN8eR1XMhk=
|
||||
github.com/mailgun/mailgun-go/v4 v4.3.0/go.mod h1:fWuBI2iaS/pSSyo6+EBpHjatQO3lV8onwqcRy7joSJI=
|
||||
github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
@@ -179,6 +210,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
@@ -187,31 +220,51 @@ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoH
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14 h1:PyYN9JH5jY9j6av01SpfRMb+1DWg/i3MbGOKPxJ2wjM=
|
||||
github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14/go.mod h1:gxQT6pBGRuIGunNf/+tSOB5OHvguWi8Tbt82WOkf35E=
|
||||
github.com/swaggo/gin-swagger v1.2.0 h1:YskZXEiv51fjOMTsXrOetAjrMDfFaXD79PEoQBOe2W0=
|
||||
github.com/swaggo/gin-swagger v1.2.0/go.mod h1:qlH2+W7zXGZkczuL+r2nEBR2JTT+/lX05Nn6vPhc7OI=
|
||||
github.com/swaggo/gin-swagger v1.3.0 h1:eOmp7r57oUgZPw2dJOjcGNMse9cvXcI4tTqBcnZtPsI=
|
||||
github.com/swaggo/gin-swagger v1.3.0/go.mod h1:oy1BRA6WvgtCp848lhxce7BnWH4C8Bxa0m5SkWx+cS0=
|
||||
github.com/swaggo/swag v1.5.1/go.mod h1:1Bl9F/ZBpVWh22nY0zmYyASPO1lI/zIwRDrpZU+tv8Y=
|
||||
github.com/swaggo/swag v1.6.7 h1:e8GC2xDllJZr3omJkm9YfmK0Y56+rMO3cg0JBKNz09s=
|
||||
github.com/swaggo/swag v1.6.7/go.mod h1:xDhTyuFIujYiN3DKWC/H/83xcfHp+UE/IzWWampG7Zc=
|
||||
github.com/swaggo/swag v1.6.8 h1:z3ZNcpJs/NLMpZcKqXUsBELmmY2Ocy09JXKx5gu3L4M=
|
||||
github.com/swaggo/swag v1.6.8/go.mod h1:a0IpNeMfGidNOcm2TsqODUh9JHdHu3kxDA0UlGbBKjI=
|
||||
github.com/swaggo/swag v1.6.9 h1:BukKRwZjnEcUxQt7Xgfrt9fpav0hiWw9YimdNO9wssw=
|
||||
github.com/swaggo/swag v1.6.9/go.mod h1:a0IpNeMfGidNOcm2TsqODUh9JHdHu3kxDA0UlGbBKjI=
|
||||
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
|
||||
github.com/ugorji/go v1.1.5-pre/go.mod h1:FwP/aQVg39TXzItUBMwnWp9T9gPQnXw4Poh4/oBQZ/0=
|
||||
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go v1.1.9 h1:SObrQTaSuP8WOv2WNCj8gECiNSJIUvk3Q7N26c96Gws=
|
||||
github.com/ugorji/go v1.1.9/go.mod h1:chLrngdsg43geAaeId+nXO57YsDdl5OZqd/QtBiD19g=
|
||||
github.com/ugorji/go v1.1.13/go.mod h1:jxau1n+/wyTGLQoCkjok9r5zFa/FxT6eI5HiHKQszjc=
|
||||
github.com/ugorji/go v1.2.0 h1:6eXlzYLLwZwXroJx9NyqbYcbv/d93twiOzQLDewE6qM=
|
||||
github.com/ugorji/go v1.2.0/go.mod h1:1ny++pKMXhLWrwWV5Nf+CbOuZJhMoaFD+0GMFfd8fEc=
|
||||
github.com/ugorji/go/codec v0.0.0-20181022190402-e5e69e061d4f/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
|
||||
github.com/ugorji/go/codec v1.1.5-pre/go.mod h1:tULtS6Gy1AE1yCENaw4Vb//HLH5njI2tfCQDUqRd8fI=
|
||||
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
|
||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||
github.com/ugorji/go/codec v1.1.9 h1:J/7hhpkQwgypRNvaeh/T5gzJ2gEI/l8S3qyRrdEa1fA=
|
||||
github.com/ugorji/go/codec v1.1.9/go.mod h1:+SWgpdqOgdW5sBaiDfkHilQ1SxQ1hBkq/R+kHfL7Suo=
|
||||
github.com/ugorji/go/codec v1.1.13/go.mod h1:oNVt3Dq+FO91WNQ/9JnHKQP2QJxTzoN7wCBFCq1OeuU=
|
||||
github.com/ugorji/go/codec v1.2.0 h1:As6RccOIlbm9wHuWYMlB30dErcI+4WiKWsYsmPkyrUw=
|
||||
github.com/ugorji/go/codec v1.2.0/go.mod h1:dXvG35r7zTX6QImXOSFhGMmKtX+wJ7VTWzGvYQGIjBs=
|
||||
github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw=
|
||||
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli/v2 v2.1.1 h1:Qt8FeAtxE/vfdrLmR3rxR6JRE0RoVmbXu8+6kZtYU4k=
|
||||
github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
|
||||
github.com/urfave/cli/v2 v2.2.0 h1:JTTnM6wKzdA0Jqodd966MVj4vWbbquZykeX1sKbe2C4=
|
||||
github.com/urfave/cli/v2 v2.2.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
|
||||
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
|
||||
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.0.1 h1:tY9CJiPnMXf1ERmG2EyK7gNUd+c6RKGD0IfU8WdUSz8=
|
||||
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
|
||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
@@ -219,6 +272,10 @@ golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4/go.mod h1:yigFU9vqHzYiE8U
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM=
|
||||
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9 h1:umElSU9WZirRdgu2yFHY0ayQkEnKiOC1TtM3fWXFnoU=
|
||||
golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
@@ -237,15 +294,29 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 h1:k7pJ2yAPLPgbskkFdhRCsA77k2fySZ1zf2zCjvQCiIM=
|
||||
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20200923182212-328152dc79b1 h1:Iu68XRPd67wN4aRGGWwwq6bZo/25jR6uu52l/j2KkUE=
|
||||
golang.org/x/net v0.0.0-20200923182212-328152dc79b1/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20200927032502-5d4f70055728 h1:5wtQIAulKU5AbLQOkjxl32UufnIOqgBX72pS0AV14H0=
|
||||
golang.org/x/net v0.0.0-20200927032502-5d4f70055728/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0 h1:wBouT66WTYFXdxfVdz9sVWARVd/2vfGcmI45D2gj45M=
|
||||
golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201016165138-7b1cca2348c0 h1:5kGOVHlq0euqwzgTC9Vu15p6fV1Wi0ArVi8da2urnVg=
|
||||
golang.org/x/net v0.0.0-20201016165138-7b1cca2348c0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102 h1:42cLlJJdEh+ySyeUUbEQ5bsTiq8voBeTuweGVkY6Puw=
|
||||
golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b h1:uwuIcX0g4Yl1NC5XAz37xsr2lTtcqevgzYNVt49waME=
|
||||
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181228144115-9a3f9b0469bb/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -263,11 +334,19 @@ golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1 h1:sIky/MyNRSHTrdxfsiUSS4WIA
|
||||
golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed h1:J22ig1FUekjjkmZUM7pTKixYm8DvrYsvrBZdunYeIuQ=
|
||||
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200929083018-4d22bbb62b3c h1:/h0vtH0PyU0xAoZJVcRw1k0Ng+U0JAy3QDiFmppIlIE=
|
||||
golang.org/x/sys v0.0.0-20200929083018-4d22bbb62b3c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201113233024-12cec1faf1ba h1:xmhUJGQGbxlod18iJGqVEp9cHIPLl7QiX2aA3to708s=
|
||||
golang.org/x/sys v0.0.0-20201113233024-12cec1faf1ba/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc=
|
||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
@@ -278,10 +357,25 @@ golang.org/x/tools v0.0.0-20190611222205-d73e1c7e250b/go.mod h1:/rFqwRUd4F7ZHNgw
|
||||
golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59 h1:QjA/9ArTfVTLfEhClDCG7SGrZkZixxWpwNCDiwJfh88=
|
||||
golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200820010801-b793a1359eac/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
|
||||
golang.org/x/tools v0.0.0-20200923182640-463111b69878 h1:VUw1+Jf6KJPf82mbTQMia6HCnNMv2BbAipkEZ4KTcqQ=
|
||||
golang.org/x/tools v0.0.0-20200923182640-463111b69878/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
|
||||
golang.org/x/tools v0.0.0-20200924182824-0f1c53950d78 h1:3JUoxVhcskhsIDEc7vg0MUUEpmPPN5TfG+E97z/Fn90=
|
||||
golang.org/x/tools v0.0.0-20200924182824-0f1c53950d78/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
|
||||
golang.org/x/tools v0.0.0-20200929191002-f1e51e6b9437 h1:XSFqH8m531iIGazX5lrUC9j3slbwsZ1GFByqdUrLqmI=
|
||||
golang.org/x/tools v0.0.0-20200929191002-f1e51e6b9437/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
|
||||
golang.org/x/tools v0.0.0-20201008184944-d01b322e6f06 h1:w9ail9jFLaySAm61Zjhciu0LQ5i8YTy2pimlNLx4uuk=
|
||||
golang.org/x/tools v0.0.0-20201008184944-d01b322e6f06/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
|
||||
golang.org/x/tools v0.0.0-20201017001424-6003fad69a88 h1:ZB1XYzdDo7c/O48jzjMkvIjnC120Z9/CwgDWhePjQdQ=
|
||||
golang.org/x/tools v0.0.0-20201017001424-6003fad69a88/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
|
||||
golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9 h1:sEvmEcJVKBNUvgCUClbUQeHOAa9U0I2Ce1BooMvVCY4=
|
||||
golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20201103235415-b653051172e4 h1:Qe0EMgvVYb6tmJhJHljCj3gS96hvSTkGNaIzp/ivq10=
|
||||
golang.org/x/tools v0.0.0-20201103235415-b653051172e4/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20201113202037-1643af1435f3 h1:7R7+wzd5VuLvCNyHZ/MG511kkoP/DBEzkbh8qUsFbY8=
|
||||
golang.org/x/tools v0.0.0-20201113202037-1643af1435f3/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.0.0-20201114224030-61ea331ec02b h1:Ych5r0Z6MLML1fgf5hTg9p5bV56Xqx9xv9hLgMBATWs=
|
||||
golang.org/x/tools v0.0.0-20201114224030-61ea331ec02b/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -314,12 +408,18 @@ gopkg.in/ini.v1 v1.57.0 h1:9unxIsFcTt4I55uWluz+UmL95q4kdJ0buvQ1ZIqVQww=
|
||||
gopkg.in/ini.v1 v1.57.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/ini.v1 v1.60.0 h1:P5ZzC7RJO04094NJYlEnBdFK2wwmnCAy/+7sAzvWs60=
|
||||
gopkg.in/ini.v1 v1.60.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/ini.v1 v1.61.0 h1:LBCdW4FmFYL4s/vDZD1RQYX7oAR6IjujCYgMdbHBR10=
|
||||
gopkg.in/ini.v1 v1.61.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
|
||||
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
||||
7
jfapi/go.mod
Normal file
7
jfapi/go.mod
Normal file
@@ -0,0 +1,7 @@
|
||||
module github.com/hrfee/jfa-go/jfapi
|
||||
|
||||
go 1.15
|
||||
|
||||
replace github.com/hrfee/jfa-go/common => ../common
|
||||
|
||||
require github.com/hrfee/jfa-go/common v0.0.0-00010101000000-000000000000
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package jfapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -7,63 +7,57 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hrfee/jfa-go/common"
|
||||
)
|
||||
|
||||
type ServerInfo struct {
|
||||
type serverInfo struct {
|
||||
LocalAddress string `json:"LocalAddress"`
|
||||
Name string `json:"ServerName"`
|
||||
Version string `json:"Version"`
|
||||
Os string `json:"OperatingSystem"`
|
||||
Id string `json:"Id"`
|
||||
OS string `json:"OperatingSystem"`
|
||||
ID string `json:"Id"`
|
||||
}
|
||||
|
||||
// Jellyfin represents a running Jellyfin instance.
|
||||
type Jellyfin struct {
|
||||
server string
|
||||
client string
|
||||
version string
|
||||
device string
|
||||
deviceId string
|
||||
useragent string
|
||||
auth string
|
||||
header map[string]string
|
||||
serverInfo ServerInfo
|
||||
username string
|
||||
password string
|
||||
authenticated bool
|
||||
accessToken string
|
||||
userId string
|
||||
httpClient *http.Client
|
||||
loginParams map[string]string
|
||||
userCache []map[string]interface{}
|
||||
cacheExpiry time.Time
|
||||
cacheLength int
|
||||
noFail bool
|
||||
Server string
|
||||
client string
|
||||
version string
|
||||
device string
|
||||
deviceID string
|
||||
useragent string
|
||||
auth string
|
||||
header map[string]string
|
||||
ServerInfo serverInfo
|
||||
Username string
|
||||
password string
|
||||
Authenticated bool
|
||||
AccessToken string
|
||||
userID string
|
||||
httpClient *http.Client
|
||||
loginParams map[string]string
|
||||
userCache []map[string]interface{}
|
||||
CacheExpiry time.Time
|
||||
cacheLength int
|
||||
noFail bool
|
||||
timeoutHandler common.TimeoutHandler
|
||||
}
|
||||
|
||||
func timeoutHandler(name, addr string, noFail bool) {
|
||||
if r := recover(); r != nil {
|
||||
out := fmt.Sprintf("Failed to authenticate with %s @ %s: Timed out", name, addr)
|
||||
if noFail {
|
||||
log.Printf(out)
|
||||
} else {
|
||||
log.Fatalf(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newJellyfin(server, client, version, device, deviceId string) (*Jellyfin, error) {
|
||||
// NewJellyfin returns a new Jellyfin object.
|
||||
func NewJellyfin(server, client, version, device, deviceID string, timeoutHandler common.TimeoutHandler, cacheTimeout int) (*Jellyfin, error) {
|
||||
jf := &Jellyfin{}
|
||||
jf.server = server
|
||||
jf.Server = server
|
||||
jf.client = client
|
||||
jf.version = version
|
||||
jf.device = device
|
||||
jf.deviceId = deviceId
|
||||
jf.deviceID = deviceID
|
||||
jf.useragent = fmt.Sprintf("%s/%s", client, version)
|
||||
jf.auth = fmt.Sprintf("MediaBrowser Client=%s, Device=%s, DeviceId=%s, Version=%s", client, device, deviceId, version)
|
||||
jf.timeoutHandler = timeoutHandler
|
||||
jf.auth = fmt.Sprintf("MediaBrowser Client=%s, Device=%s, DeviceId=%s, Version=%s", client, device, deviceID, version)
|
||||
jf.header = map[string]string{
|
||||
"Accept": "application/json",
|
||||
"Content-type": "application/json; charset=UTF-8",
|
||||
@@ -76,21 +70,22 @@ func newJellyfin(server, client, version, device, deviceId string) (*Jellyfin, e
|
||||
jf.httpClient = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
infoUrl := fmt.Sprintf("%s/System/Info/Public", server)
|
||||
req, _ := http.NewRequest("GET", infoUrl, nil)
|
||||
infoURL := fmt.Sprintf("%s/System/Info/Public", server)
|
||||
req, _ := http.NewRequest("GET", infoURL, nil)
|
||||
resp, err := jf.httpClient.Do(req)
|
||||
defer timeoutHandler("Jellyfin", jf.server, jf.noFail)
|
||||
defer jf.timeoutHandler()
|
||||
if err == nil {
|
||||
data, _ := ioutil.ReadAll(resp.Body)
|
||||
json.Unmarshal(data, &jf.serverInfo)
|
||||
json.Unmarshal(data, &jf.ServerInfo)
|
||||
}
|
||||
jf.cacheLength = 30
|
||||
jf.cacheExpiry = time.Now()
|
||||
jf.cacheLength = cacheTimeout
|
||||
jf.CacheExpiry = time.Now()
|
||||
return jf, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) authenticate(username, password string) (map[string]interface{}, int, error) {
|
||||
jf.username = username
|
||||
// Authenticate attempts to authenticate using a username & password
|
||||
func (jf *Jellyfin) Authenticate(username, password string) (map[string]interface{}, int, error) {
|
||||
jf.Username = username
|
||||
jf.password = password
|
||||
jf.loginParams = map[string]string{
|
||||
"Username": username,
|
||||
@@ -105,9 +100,9 @@ func (jf *Jellyfin) authenticate(username, password string) (map[string]interfac
|
||||
return nil, 0, err
|
||||
}
|
||||
// loginParams, _ := json.Marshal(jf.loginParams)
|
||||
url := fmt.Sprintf("%s/Users/authenticatebyname", jf.server)
|
||||
url := fmt.Sprintf("%s/Users/authenticatebyname", jf.Server)
|
||||
req, err := http.NewRequest("POST", url, buffer)
|
||||
defer timeoutHandler("Jellyfin", jf.server, jf.noFail)
|
||||
defer jf.timeoutHandler()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -128,16 +123,16 @@ func (jf *Jellyfin) authenticate(username, password string) (map[string]interfac
|
||||
}
|
||||
var respData map[string]interface{}
|
||||
json.NewDecoder(data).Decode(&respData)
|
||||
jf.accessToken = respData["AccessToken"].(string)
|
||||
jf.AccessToken = respData["AccessToken"].(string)
|
||||
user := respData["User"].(map[string]interface{})
|
||||
jf.userId = respData["User"].(map[string]interface{})["Id"].(string)
|
||||
jf.auth = fmt.Sprintf("MediaBrowser Client=\"%s\", Device=\"%s\", DeviceId=\"%s\", Version=\"%s\", Token=\"%s\"", jf.client, jf.device, jf.deviceId, jf.version, jf.accessToken)
|
||||
jf.userID = respData["User"].(map[string]interface{})["Id"].(string)
|
||||
jf.auth = fmt.Sprintf("MediaBrowser Client=\"%s\", Device=\"%s\", DeviceId=\"%s\", Version=\"%s\", Token=\"%s\"", jf.client, jf.device, jf.deviceID, jf.version, jf.AccessToken)
|
||||
jf.header["X-Emby-Authorization"] = jf.auth
|
||||
jf.authenticated = true
|
||||
jf.Authenticated = true
|
||||
return user, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) _get(url string, params map[string]string) (string, int, error) {
|
||||
func (jf *Jellyfin) get(url string, params map[string]string) (string, int, error) {
|
||||
var req *http.Request
|
||||
if params != nil {
|
||||
jsonParams, _ := json.Marshal(params)
|
||||
@@ -149,13 +144,13 @@ func (jf *Jellyfin) _get(url string, params map[string]string) (string, int, err
|
||||
req.Header.Add(name, value)
|
||||
}
|
||||
resp, err := jf.httpClient.Do(req)
|
||||
defer timeoutHandler("Jellyfin", jf.server, jf.noFail)
|
||||
defer jf.timeoutHandler()
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
if resp.StatusCode == 401 && jf.authenticated {
|
||||
jf.authenticated = false
|
||||
_, _, authErr := jf.authenticate(jf.username, jf.password)
|
||||
if resp.StatusCode == 401 && jf.Authenticated {
|
||||
jf.Authenticated = false
|
||||
_, _, authErr := jf.Authenticate(jf.Username, jf.password)
|
||||
if authErr == nil {
|
||||
v1, v2, v3 := jf._get(url, params)
|
||||
v1, v2, v3 := jf.get(url, params)
|
||||
return v1, v2, v3
|
||||
}
|
||||
}
|
||||
@@ -164,9 +159,6 @@ func (jf *Jellyfin) _get(url string, params map[string]string) (string, int, err
|
||||
defer resp.Body.Close()
|
||||
var data io.Reader
|
||||
encoding := resp.Header.Get("Content-Encoding")
|
||||
if TEST {
|
||||
fmt.Println("response encoding:", encoding)
|
||||
}
|
||||
switch encoding {
|
||||
case "gzip":
|
||||
data, _ = gzip.NewReader(resp.Body)
|
||||
@@ -180,20 +172,20 @@ func (jf *Jellyfin) _get(url string, params map[string]string) (string, int, err
|
||||
return buf.String(), resp.StatusCode, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) _post(url string, data map[string]interface{}, response bool) (string, int, error) {
|
||||
func (jf *Jellyfin) post(url string, data map[string]interface{}, response bool) (string, int, error) {
|
||||
params, _ := json.Marshal(data)
|
||||
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(params))
|
||||
for name, value := range jf.header {
|
||||
req.Header.Add(name, value)
|
||||
}
|
||||
resp, err := jf.httpClient.Do(req)
|
||||
defer timeoutHandler("Jellyfin", jf.server, jf.noFail)
|
||||
defer jf.timeoutHandler()
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
if resp.StatusCode == 401 && jf.authenticated {
|
||||
jf.authenticated = false
|
||||
_, _, authErr := jf.authenticate(jf.username, jf.password)
|
||||
if resp.StatusCode == 401 && jf.Authenticated {
|
||||
jf.Authenticated = false
|
||||
_, _, authErr := jf.Authenticate(jf.Username, jf.password)
|
||||
if authErr == nil {
|
||||
v1, v2, v3 := jf._post(url, data, response)
|
||||
v1, v2, v3 := jf.post(url, data, response)
|
||||
return v1, v2, v3
|
||||
}
|
||||
}
|
||||
@@ -215,45 +207,48 @@ func (jf *Jellyfin) _post(url string, data map[string]interface{}, response bool
|
||||
return "", resp.StatusCode, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) deleteUser(id string) (int, error) {
|
||||
url := fmt.Sprintf("%s/Users/%s", jf.server, id)
|
||||
// DeleteUser deletes the user corresponding to the provided ID.
|
||||
func (jf *Jellyfin) DeleteUser(id string) (int, error) {
|
||||
url := fmt.Sprintf("%s/Users/%s", jf.Server, id)
|
||||
req, _ := http.NewRequest("DELETE", url, nil)
|
||||
for name, value := range jf.header {
|
||||
req.Header.Add(name, value)
|
||||
}
|
||||
resp, err := jf.httpClient.Do(req)
|
||||
defer timeoutHandler("Jellyfin", jf.server, jf.noFail)
|
||||
defer jf.timeoutHandler()
|
||||
return resp.StatusCode, err
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) getUsers(public bool) ([]map[string]interface{}, int, error) {
|
||||
// GetUsers returns all (visible) users on the Jellyfin instance.
|
||||
func (jf *Jellyfin) GetUsers(public bool) ([]map[string]interface{}, int, error) {
|
||||
var result []map[string]interface{}
|
||||
var data string
|
||||
var status int
|
||||
var err error
|
||||
if time.Now().After(jf.cacheExpiry) {
|
||||
if time.Now().After(jf.CacheExpiry) {
|
||||
if public {
|
||||
url := fmt.Sprintf("%s/users/public", jf.server)
|
||||
data, status, err = jf._get(url, nil)
|
||||
url := fmt.Sprintf("%s/users/public", jf.Server)
|
||||
data, status, err = jf.get(url, nil)
|
||||
} else {
|
||||
url := fmt.Sprintf("%s/users", jf.server)
|
||||
data, status, err = jf._get(url, jf.loginParams)
|
||||
url := fmt.Sprintf("%s/users", jf.Server)
|
||||
data, status, err = jf.get(url, jf.loginParams)
|
||||
}
|
||||
if err != nil || status != 200 {
|
||||
return nil, status, err
|
||||
}
|
||||
json.Unmarshal([]byte(data), &result)
|
||||
jf.userCache = result
|
||||
jf.cacheExpiry = time.Now().Add(time.Minute * time.Duration(jf.cacheLength))
|
||||
jf.CacheExpiry = time.Now().Add(time.Minute * time.Duration(jf.cacheLength))
|
||||
return result, status, nil
|
||||
}
|
||||
return jf.userCache, 200, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) userByName(username string, public bool) (map[string]interface{}, int, error) {
|
||||
// UserByName returns the user corresponding to the provided username.
|
||||
func (jf *Jellyfin) UserByName(username string, public bool) (map[string]interface{}, int, error) {
|
||||
var match map[string]interface{}
|
||||
find := func() (map[string]interface{}, int, error) {
|
||||
users, status, err := jf.getUsers(public)
|
||||
users, status, err := jf.GetUsers(public)
|
||||
if err != nil || status != 200 {
|
||||
return nil, status, err
|
||||
}
|
||||
@@ -266,48 +261,49 @@ func (jf *Jellyfin) userByName(username string, public bool) (map[string]interfa
|
||||
}
|
||||
match, status, err := find()
|
||||
if match == nil {
|
||||
jf.cacheExpiry = time.Now()
|
||||
jf.CacheExpiry = time.Now()
|
||||
match, status, err = find()
|
||||
}
|
||||
return match, status, err
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) userById(userId string, public bool) (map[string]interface{}, int, error) {
|
||||
if jf.cacheExpiry.After(time.Now()) {
|
||||
// UserByID returns the user corresponding to the provided ID.
|
||||
func (jf *Jellyfin) UserByID(userID string, public bool) (map[string]interface{}, int, error) {
|
||||
if jf.CacheExpiry.After(time.Now()) {
|
||||
for _, user := range jf.userCache {
|
||||
if user["Id"].(string) == userId {
|
||||
if user["Id"].(string) == userID {
|
||||
return user, 200, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if public {
|
||||
users, status, err := jf.getUsers(public)
|
||||
users, status, err := jf.GetUsers(public)
|
||||
if err != nil || status != 200 {
|
||||
return nil, status, err
|
||||
}
|
||||
for _, user := range users {
|
||||
if user["Id"].(string) == userId {
|
||||
if user["Id"].(string) == userID {
|
||||
return user, status, nil
|
||||
}
|
||||
}
|
||||
return nil, status, err
|
||||
} else {
|
||||
var result map[string]interface{}
|
||||
var data string
|
||||
var status int
|
||||
var err error
|
||||
url := fmt.Sprintf("%s/users/%s", jf.server, userId)
|
||||
data, status, err = jf._get(url, jf.loginParams)
|
||||
if err != nil || status != 200 {
|
||||
return nil, status, err
|
||||
}
|
||||
json.Unmarshal([]byte(data), &result)
|
||||
return result, status, nil
|
||||
}
|
||||
var result map[string]interface{}
|
||||
var data string
|
||||
var status int
|
||||
var err error
|
||||
url := fmt.Sprintf("%s/users/%s", jf.Server, userID)
|
||||
data, status, err = jf.get(url, jf.loginParams)
|
||||
if err != nil || status != 200 {
|
||||
return nil, status, err
|
||||
}
|
||||
json.Unmarshal([]byte(data), &result)
|
||||
return result, status, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) newUser(username, password string) (map[string]interface{}, int, error) {
|
||||
url := fmt.Sprintf("%s/Users/New", jf.server)
|
||||
// NewUser creates a new user with the provided username and password.
|
||||
func (jf *Jellyfin) NewUser(username, password string) (map[string]interface{}, int, error) {
|
||||
url := fmt.Sprintf("%s/Users/New", jf.Server)
|
||||
stringData := map[string]string{
|
||||
"Name": username,
|
||||
"Password": password,
|
||||
@@ -316,7 +312,7 @@ func (jf *Jellyfin) newUser(username, password string) (map[string]interface{},
|
||||
for key, value := range stringData {
|
||||
data[key] = value
|
||||
}
|
||||
response, status, err := jf._post(url, data, true)
|
||||
response, status, err := jf.post(url, data, true)
|
||||
var recv map[string]interface{}
|
||||
json.Unmarshal([]byte(response), &recv)
|
||||
if err != nil || !(status == 200 || status == 204) {
|
||||
@@ -325,24 +321,27 @@ func (jf *Jellyfin) newUser(username, password string) (map[string]interface{},
|
||||
return recv, status, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) setPolicy(userId string, policy map[string]interface{}) (int, error) {
|
||||
url := fmt.Sprintf("%s/Users/%s/Policy", jf.server, userId)
|
||||
_, status, err := jf._post(url, policy, false)
|
||||
// SetPolicy sets the access policy for the user corresponding to the provided ID.
|
||||
func (jf *Jellyfin) SetPolicy(userID string, policy map[string]interface{}) (int, error) {
|
||||
url := fmt.Sprintf("%s/Users/%s/Policy", jf.Server, userID)
|
||||
_, status, err := jf.post(url, policy, false)
|
||||
if err != nil || status != 200 {
|
||||
return status, err
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) setConfiguration(userId string, configuration map[string]interface{}) (int, error) {
|
||||
url := fmt.Sprintf("%s/Users/%s/Configuration", jf.server, userId)
|
||||
_, status, err := jf._post(url, configuration, false)
|
||||
// SetConfiguration sets the configuration (part of homescreen layout) for the user corresponding to the provided ID.
|
||||
func (jf *Jellyfin) SetConfiguration(userID string, configuration map[string]interface{}) (int, error) {
|
||||
url := fmt.Sprintf("%s/Users/%s/Configuration", jf.Server, userID)
|
||||
_, status, err := jf.post(url, configuration, false)
|
||||
return status, err
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) getDisplayPreferences(userId string) (map[string]interface{}, int, error) {
|
||||
url := fmt.Sprintf("%s/DisplayPreferences/usersettings?userId=%s&client=emby", jf.server, userId)
|
||||
data, status, err := jf._get(url, nil)
|
||||
// GetDisplayPreferences gets the displayPreferences (part of homescreen layout) for the user corresponding to the provided ID.
|
||||
func (jf *Jellyfin) GetDisplayPreferences(userID string) (map[string]interface{}, int, error) {
|
||||
url := fmt.Sprintf("%s/DisplayPreferences/usersettings?userId=%s&client=emby", jf.Server, userID)
|
||||
data, status, err := jf.get(url, nil)
|
||||
if err != nil || !(status == 204 || status == 200) {
|
||||
return nil, status, err
|
||||
}
|
||||
@@ -354,9 +353,10 @@ func (jf *Jellyfin) getDisplayPreferences(userId string) (map[string]interface{}
|
||||
return displayprefs, status, nil
|
||||
}
|
||||
|
||||
func (jf *Jellyfin) setDisplayPreferences(userId string, displayprefs map[string]interface{}) (int, error) {
|
||||
url := fmt.Sprintf("%s/DisplayPreferences/usersettings?userId=%s&client=emby", jf.server, userId)
|
||||
_, status, err := jf._post(url, displayprefs, false)
|
||||
// SetDisplayPreferences sets the displayPreferences (part of homescreen layout) for the user corresponding to the provided ID.
|
||||
func (jf *Jellyfin) SetDisplayPreferences(userID string, displayprefs map[string]interface{}) (int, error) {
|
||||
url := fmt.Sprintf("%s/DisplayPreferences/usersettings?userId=%s&client=emby", jf.Server, userID)
|
||||
_, status, err := jf.post(url, displayprefs, false)
|
||||
if err != nil || !(status == 204 || status == 200) {
|
||||
return status, err
|
||||
}
|
||||
@@ -1,15 +1,8 @@
|
||||
import subprocess
|
||||
import shutil
|
||||
import os
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument(
|
||||
"-y", "--yes", help="use assumed node bin directory.", action="store_true"
|
||||
)
|
||||
|
||||
|
||||
def runcmd(cmd):
|
||||
if os.name == "nt":
|
||||
@@ -19,27 +12,11 @@ def runcmd(cmd):
|
||||
|
||||
|
||||
local_path = Path(__file__).resolve().parent
|
||||
out = runcmd("npm bin")
|
||||
|
||||
try:
|
||||
node_bin = Path(out[0].decode("utf-8").rstrip())
|
||||
except:
|
||||
node_bin = Path(out.decode("utf-8").rstrip())
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.yes:
|
||||
print(f'assuming npm bin directory "{node_bin}". Is this correct?')
|
||||
if input("[yY/nN]: ").lower() == "n":
|
||||
node_bin = local_path.parent / "node_modules" / ".bin"
|
||||
print(f'this? "{node_bin}"')
|
||||
if input("[yY/nN]: ").lower() == "n":
|
||||
node_bin = input("input bin directory: ")
|
||||
|
||||
for mjml in [f for f in local_path.iterdir() if f.is_file() and "mjml" in f.suffix]:
|
||||
print(f"Compiling {mjml.name}")
|
||||
fname = mjml.with_suffix(".html")
|
||||
runcmd(f'{str(node_bin / "mjml")} {str(mjml)} -o {str(fname)}')
|
||||
runcmd(f"npx mjml {str(mjml)} -o {str(fname)}")
|
||||
if fname.is_file():
|
||||
print("Done.")
|
||||
|
||||
|
||||
118
main.go
118
main.go
@@ -23,7 +23,10 @@ import (
|
||||
"github.com/gin-contrib/pprof"
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/hrfee/jfa-go/common"
|
||||
_ "github.com/hrfee/jfa-go/docs"
|
||||
"github.com/hrfee/jfa-go/jfapi"
|
||||
"github.com/hrfee/jfa-go/ombi"
|
||||
"github.com/lithammer/shortuuid/v3"
|
||||
"github.com/logrusorgru/aurora/v3"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
@@ -51,9 +54,9 @@ type appContext struct {
|
||||
jellyfinLogin bool
|
||||
users []User
|
||||
invalidTokens []string
|
||||
jf *Jellyfin
|
||||
authJf *Jellyfin
|
||||
ombi *Ombi
|
||||
jf *jfapi.Jellyfin
|
||||
authJf *jfapi.Jellyfin
|
||||
ombi *ombi.Ombi
|
||||
datePattern string
|
||||
timePattern string
|
||||
storage Storage
|
||||
@@ -64,6 +67,34 @@ type appContext struct {
|
||||
port int
|
||||
version string
|
||||
quit chan os.Signal
|
||||
lang Languages
|
||||
}
|
||||
|
||||
type Languages struct {
|
||||
langFiles []os.FileInfo // Language filenames
|
||||
langOptions []string // Language names
|
||||
chosenIndex int
|
||||
}
|
||||
|
||||
func (app *appContext) loadHTML(router *gin.Engine) {
|
||||
customPath := app.config.Section("files").Key("html_templates").MustString("")
|
||||
templatePath := filepath.Join(app.local_path, "templates")
|
||||
htmlFiles, err := ioutil.ReadDir(templatePath)
|
||||
if err != nil {
|
||||
app.err.Fatalf("Couldn't access template directory: \"%s\"", filepath.Join(app.local_path, "templates"))
|
||||
return
|
||||
}
|
||||
loadFiles := make([]string, len(htmlFiles))
|
||||
for i, f := range htmlFiles {
|
||||
if _, err := os.Stat(filepath.Join(customPath, f.Name())); os.IsNotExist(err) {
|
||||
app.debug.Printf("Using default \"%s\"", f.Name())
|
||||
loadFiles[i] = filepath.Join(templatePath, f.Name())
|
||||
} else {
|
||||
app.info.Printf("Using custom \"%s\"", f.Name())
|
||||
loadFiles[i] = filepath.Join(filepath.Join(customPath, f.Name()))
|
||||
}
|
||||
}
|
||||
router.LoadHTMLFiles(loadFiles...)
|
||||
}
|
||||
|
||||
func GenerateSecret(length int) (string, error) {
|
||||
@@ -118,18 +149,18 @@ var (
|
||||
func test(app *appContext) {
|
||||
fmt.Printf("\n\n----\n\n")
|
||||
settings := map[string]interface{}{
|
||||
"server": app.jf.server,
|
||||
"server version": app.jf.serverInfo.Version,
|
||||
"server name": app.jf.serverInfo.Name,
|
||||
"authenticated?": app.jf.authenticated,
|
||||
"access token": app.jf.accessToken,
|
||||
"username": app.jf.username,
|
||||
"server": app.jf.Server,
|
||||
"server version": app.jf.ServerInfo.Version,
|
||||
"server name": app.jf.ServerInfo.Name,
|
||||
"authenticated?": app.jf.Authenticated,
|
||||
"access token": app.jf.AccessToken,
|
||||
"username": app.jf.Username,
|
||||
}
|
||||
for n, v := range settings {
|
||||
fmt.Println(n, ":", v)
|
||||
}
|
||||
users, status, err := app.jf.getUsers(false)
|
||||
fmt.Printf("getUsers: code %d err %s maplength %d\n", status, err, len(users))
|
||||
users, status, err := app.jf.GetUsers(false)
|
||||
fmt.Printf("GetUsers: code %d err %s maplength %d\n", status, err, len(users))
|
||||
fmt.Printf("View output? [y/n]: ")
|
||||
var choice string
|
||||
fmt.Scanln(&choice)
|
||||
@@ -140,8 +171,8 @@ func test(app *appContext) {
|
||||
fmt.Printf("Enter a user to grab: ")
|
||||
var username string
|
||||
fmt.Scanln(&username)
|
||||
user, status, err := app.jf.userByName(username, false)
|
||||
fmt.Printf("userByName (%s): code %d err %s", username, status, err)
|
||||
user, status, err := app.jf.UserByName(username, false)
|
||||
fmt.Printf("UserByName (%s): code %d err %s", username, status, err)
|
||||
out, err := json.MarshalIndent(user, "", " ")
|
||||
fmt.Print(string(out))
|
||||
}
|
||||
@@ -226,7 +257,8 @@ func start(asDaemon, firstCall bool) {
|
||||
var nConfig *os.File
|
||||
nConfig, err := os.Create(app.config_path)
|
||||
if err != nil {
|
||||
app.err.Fatalf("Couldn't open config file for writing: \"%s\"", app.config_path)
|
||||
app.err.Printf("Couldn't open config file for writing: \"%s\"", app.config_path)
|
||||
app.err.Fatalf("Error: %s", err)
|
||||
}
|
||||
defer nConfig.Close()
|
||||
_, err = io.Copy(nConfig, dConfig)
|
||||
@@ -241,6 +273,12 @@ func start(asDaemon, firstCall bool) {
|
||||
if app.loadConfig() != nil {
|
||||
app.err.Fatalf("Failed to load config file \"%s\"", app.config_path)
|
||||
}
|
||||
lang := app.config.Section("ui").Key("language").MustString("en-us")
|
||||
app.storage.lang.FormPath = filepath.Join(app.local_path, "lang", "form", lang+".json")
|
||||
if _, err := os.Stat(app.storage.lang.FormPath); os.IsNotExist(err) {
|
||||
app.storage.lang.FormPath = filepath.Join(app.local_path, "lang", "form", "en-us.json")
|
||||
}
|
||||
app.storage.loadLang()
|
||||
app.version = app.config.Section("jellyfin").Key("version").String()
|
||||
// read from config...
|
||||
debugMode = app.config.Section("ui").Key("debug").MustBool(false)
|
||||
@@ -330,19 +368,14 @@ func start(asDaemon, firstCall bool) {
|
||||
|
||||
app.debug.Println("Loading storage")
|
||||
|
||||
// app.storage.invite_path = filepath.Join(app.data_path, "invites.json")
|
||||
app.storage.invite_path = app.config.Section("files").Key("invites").String()
|
||||
app.storage.loadInvites()
|
||||
// app.storage.emails_path = filepath.Join(app.data_path, "emails.json")
|
||||
app.storage.emails_path = app.config.Section("files").Key("emails").String()
|
||||
app.storage.loadEmails()
|
||||
// app.storage.policy_path = filepath.Join(app.data_path, "user_template.json")
|
||||
app.storage.policy_path = app.config.Section("files").Key("user_template").String()
|
||||
app.storage.loadPolicy()
|
||||
// app.storage.configuration_path = filepath.Join(app.data_path, "user_configuration.json")
|
||||
app.storage.configuration_path = app.config.Section("files").Key("user_configuration").String()
|
||||
app.storage.loadConfiguration()
|
||||
// app.storage.displayprefs_path = filepath.Join(app.data_path, "user_displayprefs.json")
|
||||
app.storage.displayprefs_path = app.config.Section("files").Key("user_displayprefs").String()
|
||||
app.storage.loadDisplayprefs()
|
||||
|
||||
@@ -369,16 +402,18 @@ func start(asDaemon, firstCall bool) {
|
||||
if app.config.Section("ombi").Key("enabled").MustBool(false) {
|
||||
app.storage.ombi_path = app.config.Section("files").Key("ombi_template").String()
|
||||
app.storage.loadOmbiTemplate()
|
||||
app.ombi = newOmbi(
|
||||
app.config.Section("ombi").Key("server").String(),
|
||||
ombiServer := app.config.Section("ombi").Key("server").String()
|
||||
app.ombi = ombi.NewOmbi(
|
||||
ombiServer,
|
||||
app.config.Section("ombi").Key("api_key").String(),
|
||||
true,
|
||||
common.NewTimeoutHandler("Ombi", ombiServer, true),
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
app.configBase_path = filepath.Join(app.local_path, "config-base.json")
|
||||
config_base, _ := ioutil.ReadFile(app.configBase_path)
|
||||
json.Unmarshal(config_base, &app.configBase)
|
||||
configBase, _ := ioutil.ReadFile(app.configBase_path)
|
||||
json.Unmarshal(configBase, &app.configBase)
|
||||
|
||||
themes := map[string]string{
|
||||
"Jellyfin (Dark)": fmt.Sprintf("bs%d-jf.css", app.bsVersion),
|
||||
@@ -407,23 +442,32 @@ func start(asDaemon, firstCall bool) {
|
||||
}
|
||||
|
||||
server := app.config.Section("jellyfin").Key("server").String()
|
||||
app.jf, _ = newJellyfin(server, "jfa-go", app.version, "hrfee-arch", "hrfee-arch")
|
||||
cacheTimeout := int(app.config.Section("jellyfin").Key("cache_timeout").MustUint(30))
|
||||
app.jf, _ = jfapi.NewJellyfin(
|
||||
server,
|
||||
app.config.Section("jellyfin").Key("client").String(),
|
||||
app.config.Section("jellyfin").Key("version").String(),
|
||||
app.config.Section("jellyfin").Key("device").String(),
|
||||
app.config.Section("jellyfin").Key("device_id").String(),
|
||||
common.NewTimeoutHandler("Jellyfin", server, true),
|
||||
cacheTimeout,
|
||||
)
|
||||
var status int
|
||||
_, status, err = app.jf.authenticate(app.config.Section("jellyfin").Key("username").String(), app.config.Section("jellyfin").Key("password").String())
|
||||
_, status, err = app.jf.Authenticate(app.config.Section("jellyfin").Key("username").String(), app.config.Section("jellyfin").Key("password").String())
|
||||
if status != 200 || err != nil {
|
||||
app.err.Fatalf("Failed to authenticate with Jellyfin @ %s: Code %d", server, status)
|
||||
}
|
||||
app.info.Printf("Authenticated with %s", server)
|
||||
app.authJf, _ = newJellyfin(server, "jfa-go", app.version, "auth", "auth")
|
||||
app.authJf, _ = jfapi.NewJellyfin(server, "jfa-go", app.version, "auth", "auth", common.NewTimeoutHandler("Jellyfin", server, true), cacheTimeout)
|
||||
|
||||
app.loadStrftime()
|
||||
|
||||
validatorConf := ValidatorConf{
|
||||
"characters": app.config.Section("password_validation").Key("min_length").MustInt(0),
|
||||
"uppercase characters": app.config.Section("password_validation").Key("upper").MustInt(0),
|
||||
"lowercase characters": app.config.Section("password_validation").Key("lower").MustInt(0),
|
||||
"numbers": app.config.Section("password_validation").Key("number").MustInt(0),
|
||||
"special characters": app.config.Section("password_validation").Key("special").MustInt(0),
|
||||
"length": app.config.Section("password_validation").Key("min_length").MustInt(0),
|
||||
"uppercase": app.config.Section("password_validation").Key("upper").MustInt(0),
|
||||
"lowercase": app.config.Section("password_validation").Key("lower").MustInt(0),
|
||||
"number": app.config.Section("password_validation").Key("number").MustInt(0),
|
||||
"special": app.config.Section("password_validation").Key("special").MustInt(0),
|
||||
}
|
||||
if !app.config.Section("password_validation").Key("enabled").MustBool(false) {
|
||||
for key := range validatorConf {
|
||||
@@ -459,7 +503,7 @@ func start(asDaemon, firstCall bool) {
|
||||
|
||||
router.Use(gin.Recovery())
|
||||
router.Use(static.Serve("/", static.LocalFile(filepath.Join(app.local_path, "static"), false)))
|
||||
router.LoadHTMLGlob(filepath.Join(app.local_path, "templates", "*"))
|
||||
app.loadHTML(router)
|
||||
router.NoRoute(app.NoRouteHandler)
|
||||
if debugMode {
|
||||
app.debug.Println("Loading pprof")
|
||||
@@ -467,7 +511,8 @@ func start(asDaemon, firstCall bool) {
|
||||
}
|
||||
if !firstRun {
|
||||
router.GET("/", app.AdminPage)
|
||||
router.GET("/getToken", app.getToken)
|
||||
router.GET("/token/login", app.getTokenLogin)
|
||||
router.GET("/token/refresh", app.getTokenRefresh)
|
||||
router.POST("/newUser", app.NewUser)
|
||||
router.Use(static.Serve("/invite/", static.LocalFile(filepath.Join(app.local_path, "static"), false)))
|
||||
router.GET("/invite/:invCode", app.InviteProxy)
|
||||
@@ -563,8 +608,9 @@ func flagPassed(name string) (found bool) {
|
||||
// @license.url https://raw.githubusercontent.com/hrfee/jfa-go/main/LICENSE
|
||||
// @BasePath /
|
||||
|
||||
// @securityDefinitions.basic ApiKeyBlankPassword
|
||||
// @name ApiKeyBlankPassword
|
||||
// @securityDefinitions.apikey Bearer
|
||||
// @in header
|
||||
// @name Authorization
|
||||
|
||||
// @securityDefinitions.basic getTokenAuth
|
||||
// @name getTokenAuth
|
||||
|
||||
129
models.go
Normal file
129
models.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package main
|
||||
|
||||
type stringResponse struct {
|
||||
Response string `json:"response" example:"message"`
|
||||
Error string `json:"error" example:"errorDescription"`
|
||||
}
|
||||
|
||||
type boolResponse struct {
|
||||
Success bool `json:"success" example:"false"`
|
||||
Error bool `json:"error" example:"true"`
|
||||
}
|
||||
|
||||
type newUserDTO struct {
|
||||
Username string `json:"username" example:"jeff" binding:"required"` // User's username
|
||||
Password string `json:"password" example:"guest" binding:"required"` // User's password
|
||||
Email string `json:"email" example:"jeff@jellyf.in"` // User's email address
|
||||
Code string `json:"code" example:"abc0933jncjkcjj"` // Invite code (required on /newUser)
|
||||
}
|
||||
|
||||
type deleteUserDTO struct {
|
||||
Users []string `json:"users" binding:"required"` // List of usernames to delete
|
||||
Notify bool `json:"notify"` // Whether to notify users of deletion
|
||||
Reason string `json:"reason"` // Account deletion reason (for notification)
|
||||
}
|
||||
|
||||
type generateInviteDTO struct {
|
||||
Days int `json:"days" example:"1"` // Number of days
|
||||
Hours int `json:"hours" example:"2"` // Number of hours
|
||||
Minutes int `json:"minutes" example:"3"` // Number of minutes
|
||||
Email string `json:"email" example:"jeff@jellyf.in"` // Send invite to this address
|
||||
MultipleUses bool `json:"multiple-uses" example:"true"` // Allow multiple uses
|
||||
NoLimit bool `json:"no-limit" example:"false"` // No invite use limit
|
||||
RemainingUses int `json:"remaining-uses" example:"5"` // Remaining invite uses
|
||||
Profile string `json:"profile" example:"DefaultProfile"` // Name of profile to apply on this invite
|
||||
}
|
||||
|
||||
type inviteProfileDTO struct {
|
||||
Invite string `json:"invite" example:"slakdaslkdl2342"` // Invite to apply to
|
||||
Profile string `json:"profile" example:"DefaultProfile"` // Profile to use
|
||||
}
|
||||
|
||||
type profileDTO struct {
|
||||
Admin bool `json:"admin" example:"false"` // Whether profile has admin rights or not
|
||||
LibraryAccess string `json:"libraries" example:"all"` // Number of libraries profile has access to
|
||||
FromUser string `json:"fromUser" example:"jeff"` // The user the profile is based on
|
||||
}
|
||||
|
||||
type getProfilesDTO struct {
|
||||
Profiles map[string]profileDTO `json:"profiles"`
|
||||
DefaultProfile string `json:"default_profile"`
|
||||
}
|
||||
|
||||
type profileChangeDTO struct {
|
||||
Name string `json:"name" example:"DefaultProfile" binding:"required"` // Name of the profile
|
||||
}
|
||||
|
||||
type newProfileDTO struct {
|
||||
Name string `json:"name" example:"DefaultProfile" binding:"required"` // Name of the profile
|
||||
ID string `json:"id" example:"kasdjlaskjd342342" binding:"required"` // ID of user to source settings from
|
||||
Homescreen bool `json:"homescreen" example:"true"` // Whether to store homescreen layout or not
|
||||
}
|
||||
|
||||
type inviteDTO struct {
|
||||
Code string `json:"code" example:"sajdlj23423j23"` // Invite code
|
||||
Days int `json:"days" example:"1"` // Number of days till expiry
|
||||
Hours int `json:"hours" example:"2"` // Number of hours till expiry
|
||||
Minutes int `json:"minutes" example:"3"` // Number of minutes till expiry
|
||||
Created string `json:"created" example:"01/01/20 12:00"` // Date of creation
|
||||
Profile string `json:"profile" example:"DefaultProfile"` // Profile used on this invite
|
||||
UsedBy [][]string `json:"used-by,omitempty"` // Users who have used this invite
|
||||
NoLimit bool `json:"no-limit,omitempty"` // If true, invite can be used any number of times
|
||||
RemainingUses int `json:"remaining-uses,omitempty"` // Remaining number of uses (if applicable)
|
||||
Email string `json:"email,omitempty"` // Email the invite was sent to (if applicable)
|
||||
NotifyExpiry bool `json:"notify-expiry,omitempty"` // Whether to notify the requesting user of expiry or not
|
||||
NotifyCreation bool `json:"notify-creation,omitempty"` // Whether to notify the requesting user of account creation or not
|
||||
}
|
||||
|
||||
type getInvitesDTO struct {
|
||||
Profiles []string `json:"profiles"` // List of profiles (name only)
|
||||
Invites []inviteDTO `json:"invites"` // List of invites
|
||||
}
|
||||
|
||||
// fake DTO, if i actually used this the code would be a lot longer
|
||||
type setNotifyValues map[string]struct {
|
||||
NotifyExpiry bool `json:"notify-expiry,omitempty"` // Whether to notify the requesting user of expiry or not
|
||||
NotifyCreation bool `json:"notify-creation,omitempty"` // Whether to notify the requesting user of account creation or not
|
||||
}
|
||||
|
||||
type setNotifyDTO map[string]setNotifyValues
|
||||
|
||||
type deleteInviteDTO struct {
|
||||
Code string `json:"code" example:"skjadajd43234s"` // Code of invite to delete
|
||||
}
|
||||
|
||||
type respUser struct {
|
||||
ID string `json:"id" example:"fdgsdfg45534fa"` // userID of user
|
||||
Name string `json:"name" example:"jeff"` // Username of user
|
||||
Email string `json:"email,omitempty" example:"jeff@jellyf.in"` // Email address of user (if available)
|
||||
LastActive string `json:"last_active"` // Time of last activity on Jellyfin
|
||||
Admin bool `json:"admin" example:"false"` // Whether or not the user is Administrator
|
||||
}
|
||||
|
||||
type getUsersDTO struct {
|
||||
UserList []respUser `json:"users"`
|
||||
}
|
||||
|
||||
type ombiUser struct {
|
||||
Name string `json:"name,omitempty" example:"jeff"` // Name of Ombi user
|
||||
ID string `json:"id" example:"djgkjdg7dkjfsj8"` // userID of Ombi user
|
||||
}
|
||||
|
||||
type ombiUsersDTO struct {
|
||||
Users []ombiUser `json:"users"`
|
||||
}
|
||||
|
||||
type modifyEmailsDTO map[string]string
|
||||
|
||||
type userSettingsDTO struct {
|
||||
From string `json:"from"` // Whether to apply from "user" or "profile"
|
||||
Profile string `json:"profile"` // Name of profile (if from = "profile")
|
||||
ApplyTo []string `json:"apply_to"` // Users to apply settings to
|
||||
ID string `json:"id"` // ID of user (if from = "user")
|
||||
Homescreen bool `json:"homescreen"` // Whether to apply homescreen layout or not
|
||||
}
|
||||
|
||||
type errorListDTO map[string]map[string]string
|
||||
|
||||
type configDTO map[string]interface{}
|
||||
|
||||
5
ombi/go.mod
Normal file
5
ombi/go.mod
Normal file
@@ -0,0 +1,5 @@
|
||||
module github.com/hrfee/jfa-go/ombi
|
||||
|
||||
replace github.com/hrfee/jfa-go/common => ../common
|
||||
|
||||
go 1.15
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package ombi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -9,31 +9,40 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hrfee/jfa-go/common"
|
||||
)
|
||||
|
||||
// Ombi represents a running Ombi instance.
|
||||
type Ombi struct {
|
||||
server, key string
|
||||
header map[string]string
|
||||
httpClient *http.Client
|
||||
noFail bool
|
||||
server, key string
|
||||
header map[string]string
|
||||
httpClient *http.Client
|
||||
userCache []map[string]interface{}
|
||||
cacheExpiry time.Time
|
||||
cacheLength int
|
||||
timeoutHandler common.TimeoutHandler
|
||||
}
|
||||
|
||||
func newOmbi(server, key string, noFail bool) *Ombi {
|
||||
// NewOmbi returns an Ombi object.
|
||||
func NewOmbi(server, key string, timeoutHandler common.TimeoutHandler) *Ombi {
|
||||
return &Ombi{
|
||||
server: server,
|
||||
key: key,
|
||||
noFail: noFail,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
},
|
||||
header: map[string]string{
|
||||
"ApiKey": key,
|
||||
},
|
||||
cacheLength: 30,
|
||||
cacheExpiry: time.Now(),
|
||||
timeoutHandler: timeoutHandler,
|
||||
}
|
||||
}
|
||||
|
||||
// does a GET and returns the response as an io.reader.
|
||||
func (ombi *Ombi) _getReader(url string, params map[string]string) (string, int, error) {
|
||||
// does a GET and returns the response as a string.
|
||||
func (ombi *Ombi) getJSON(url string, params map[string]string) (string, int, error) {
|
||||
if ombi.key == "" {
|
||||
return "", 401, fmt.Errorf("No API key provided")
|
||||
}
|
||||
@@ -48,7 +57,7 @@ func (ombi *Ombi) _getReader(url string, params map[string]string) (string, int,
|
||||
req.Header.Add(name, value)
|
||||
}
|
||||
resp, err := ombi.httpClient.Do(req)
|
||||
defer timeoutHandler("Ombi", ombi.server, ombi.noFail)
|
||||
defer ombi.timeoutHandler()
|
||||
if err != nil || resp.StatusCode != 200 {
|
||||
if resp.StatusCode == 401 {
|
||||
return "", 401, fmt.Errorf("Invalid API Key")
|
||||
@@ -72,16 +81,16 @@ func (ombi *Ombi) _getReader(url string, params map[string]string) (string, int,
|
||||
}
|
||||
|
||||
// does a POST and optionally returns response as string. Returns a string instead of an io.reader bcs i couldn't get it working otherwise.
|
||||
func (ombi *Ombi) _post(url string, data map[string]interface{}, response bool) (string, int, error) {
|
||||
func (ombi *Ombi) send(mode string, url string, data map[string]interface{}, response bool) (string, int, error) {
|
||||
responseText := ""
|
||||
params, _ := json.Marshal(data)
|
||||
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(params))
|
||||
req, _ := http.NewRequest(mode, url, bytes.NewBuffer(params))
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
for name, value := range ombi.header {
|
||||
req.Header.Add(name, value)
|
||||
}
|
||||
resp, err := ombi.httpClient.Do(req)
|
||||
defer timeoutHandler("Ombi", ombi.server, ombi.noFail)
|
||||
defer ombi.timeoutHandler()
|
||||
if err != nil || !(resp.StatusCode == 200 || resp.StatusCode == 201) {
|
||||
if resp.StatusCode == 401 {
|
||||
return "", 401, fmt.Errorf("Invalid API Key")
|
||||
@@ -107,18 +116,57 @@ func (ombi *Ombi) _post(url string, data map[string]interface{}, response bool)
|
||||
return responseText, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// gets an ombi user by their ID.
|
||||
func (ombi *Ombi) userByID(id string) (result map[string]interface{}, code int, err error) {
|
||||
resp, code, err := ombi._getReader(fmt.Sprintf("%s/api/v1/Identity/User/%s", ombi.server, id), nil)
|
||||
func (ombi *Ombi) post(url string, data map[string]interface{}, response bool) (string, int, error) {
|
||||
return ombi.send("POST", url, data, response)
|
||||
}
|
||||
|
||||
func (ombi *Ombi) put(url string, data map[string]interface{}, response bool) (string, int, error) {
|
||||
return ombi.send("PUT", url, data, response)
|
||||
}
|
||||
|
||||
// ModifyUser applies the given modified user object to the corresponding user.
|
||||
func (ombi *Ombi) ModifyUser(user map[string]interface{}) (status int, err error) {
|
||||
if _, ok := user["id"]; !ok {
|
||||
err = fmt.Errorf("No ID provided")
|
||||
return
|
||||
}
|
||||
_, status, err = ombi.put(ombi.server+"/api/v1/Identity", user, false)
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteUser deletes the user corresponding to the given ID.
|
||||
func (ombi *Ombi) DeleteUser(id string) (code int, err error) {
|
||||
url := fmt.Sprintf("%s/api/v1/Identity/%s", ombi.server, id)
|
||||
req, _ := http.NewRequest("DELETE", url, nil)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
for name, value := range ombi.header {
|
||||
req.Header.Add(name, value)
|
||||
}
|
||||
resp, err := ombi.httpClient.Do(req)
|
||||
defer ombi.timeoutHandler()
|
||||
return resp.StatusCode, err
|
||||
}
|
||||
|
||||
// UserByID returns the user corresponding to the provided ID.
|
||||
func (ombi *Ombi) UserByID(id string) (result map[string]interface{}, code int, err error) {
|
||||
resp, code, err := ombi.getJSON(fmt.Sprintf("%s/api/v1/Identity/User/%s", ombi.server, id), nil)
|
||||
json.Unmarshal([]byte(resp), &result)
|
||||
return
|
||||
}
|
||||
|
||||
// gets a list of all users.
|
||||
func (ombi *Ombi) getUsers() (result []map[string]interface{}, code int, err error) {
|
||||
resp, code, err := ombi._getReader(fmt.Sprintf("%s/api/v1/Identity/Users", ombi.server), nil)
|
||||
json.Unmarshal([]byte(resp), &result)
|
||||
return
|
||||
// GetUsers returns all users on the Ombi instance.
|
||||
func (ombi *Ombi) GetUsers() ([]map[string]interface{}, int, error) {
|
||||
if time.Now().After(ombi.cacheExpiry) {
|
||||
resp, code, err := ombi.getJSON(fmt.Sprintf("%s/api/v1/Identity/Users", ombi.server), nil)
|
||||
var result []map[string]interface{}
|
||||
json.Unmarshal([]byte(resp), &result)
|
||||
ombi.userCache = result
|
||||
if (code == 200 || code == 204) && err == nil {
|
||||
ombi.cacheExpiry = time.Now().Add(time.Minute * time.Duration(ombi.cacheLength))
|
||||
}
|
||||
return result, code, err
|
||||
}
|
||||
return ombi.userCache, 200, nil
|
||||
}
|
||||
|
||||
// Strip these from a user when saving as a template.
|
||||
@@ -133,9 +181,9 @@ var stripFromOmbi = []string{
|
||||
"userName",
|
||||
}
|
||||
|
||||
// returns a template based on the user corresponding to the provided ID's settings.
|
||||
func (ombi *Ombi) templateByID(id string) (result map[string]interface{}, code int, err error) {
|
||||
result, code, err = ombi.userByID(id)
|
||||
// TemplateByID returns a template based on the user corresponding to the provided ID's settings.
|
||||
func (ombi *Ombi) TemplateByID(id string) (result map[string]interface{}, code int, err error) {
|
||||
result, code, err = ombi.UserByID(id)
|
||||
if err != nil || code != 200 {
|
||||
return
|
||||
}
|
||||
@@ -152,14 +200,14 @@ func (ombi *Ombi) templateByID(id string) (result map[string]interface{}, code i
|
||||
return
|
||||
}
|
||||
|
||||
// creates a new user.
|
||||
func (ombi *Ombi) newUser(username, password, email string, template map[string]interface{}) ([]string, int, error) {
|
||||
// NewUser creates a new user with the given username, password and email address.
|
||||
func (ombi *Ombi) NewUser(username, password, email string, template map[string]interface{}) ([]string, int, error) {
|
||||
url := fmt.Sprintf("%s/api/v1/Identity", ombi.server)
|
||||
user := template
|
||||
user["userName"] = username
|
||||
user["password"] = password
|
||||
user["emailAddress"] = email
|
||||
resp, code, err := ombi._post(url, user, true)
|
||||
resp, code, err := ombi.post(url, user, true)
|
||||
var data map[string]interface{}
|
||||
json.Unmarshal([]byte(resp), &data)
|
||||
if err != nil || code != 200 {
|
||||
17
package-lock.json
generated
17
package-lock.json
generated
@@ -50,9 +50,9 @@
|
||||
"integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ=="
|
||||
},
|
||||
"@types/jquery": {
|
||||
"version": "3.5.1",
|
||||
"resolved": "https://registry.npm.taobao.org/@types/jquery/download/@types/jquery-3.5.1.tgz",
|
||||
"integrity": "sha1-zrsFes9QccQOQ58w6EDFejDUBsM=",
|
||||
"version": "3.5.3",
|
||||
"resolved": "https://registry.npm.taobao.org/@types/jquery/download/@types/jquery-3.5.3.tgz?cache=0&sync_timestamp=1602524936372&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Fjquery%2Fdownload%2F%40types%2Fjquery-3.5.3.tgz",
|
||||
"integrity": "sha1-rcxkfkxnW9nrrn+5gOnKddWO6Mc=",
|
||||
"requires": {
|
||||
"@types/sizzle": "*"
|
||||
}
|
||||
@@ -205,9 +205,9 @@
|
||||
"integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24="
|
||||
},
|
||||
"bootstrap": {
|
||||
"version": "5.0.0-alpha1",
|
||||
"resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-5.0.0-alpha1.tgz",
|
||||
"integrity": "sha512-iwKneP2pLXl8lN0YpnOuOARiNPTzmh/4cw+Un86u4OqrMLuQpyMC7nO07hvivvcg0B/ektJPjuPnS1s+YmRK9A=="
|
||||
"version": "5.0.0-alpha3",
|
||||
"resolved": "https://registry.npm.taobao.org/bootstrap/download/bootstrap-5.0.0-alpha3.tgz?cache=0&sync_timestamp=1605115180548&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fbootstrap%2Fdownload%2Fbootstrap-5.0.0-alpha3.tgz",
|
||||
"integrity": "sha1-9au9OHQDg9a44EEhKu9eoiDn2qo="
|
||||
},
|
||||
"bootstrap4": {
|
||||
"version": "npm:bootstrap@4.5.0",
|
||||
@@ -594,6 +594,11 @@
|
||||
"is-arrayish": "^0.2.1"
|
||||
}
|
||||
},
|
||||
"esbuild": {
|
||||
"version": "0.7.8",
|
||||
"resolved": "https://registry.npm.taobao.org/esbuild/download/esbuild-0.7.8.tgz",
|
||||
"integrity": "sha1-e6wXcYHv4MiTmnsVU2aCr+MtG3M="
|
||||
},
|
||||
"escalade": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.0.2.tgz",
|
||||
|
||||
@@ -17,11 +17,12 @@
|
||||
},
|
||||
"homepage": "https://github.com/hrfee/jellyfin-accounts#readme",
|
||||
"dependencies": {
|
||||
"@types/jquery": "^3.5.1",
|
||||
"@types/jquery": "^3.5.3",
|
||||
"autoprefixer": "^9.8.5",
|
||||
"bootstrap": "^5.0.0-alpha1",
|
||||
"bootstrap": "^5.0.0-alpha3",
|
||||
"bootstrap4": "npm:bootstrap@^4.5.0",
|
||||
"clean-css-cli": "^4.3.0",
|
||||
"esbuild": "^0.7.8",
|
||||
"lodash": "^4.17.19",
|
||||
"mjml": "^4.6.3",
|
||||
"postcss-cli": "^7.1.1",
|
||||
|
||||
@@ -59,7 +59,7 @@ func pwrMonitor(app *appContext, watcher *fsnotify.Watcher) {
|
||||
}
|
||||
app.info.Printf("New password reset for user \"%s\"", pwr.Username)
|
||||
if currentTime := time.Now(); pwr.Expiry.After(currentTime) {
|
||||
user, status, err := app.jf.userByName(pwr.Username, false)
|
||||
user, status, err := app.jf.UserByName(pwr.Username, false)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.err.Printf("Failed to get users from Jellyfin: Code %d", status)
|
||||
app.debug.Printf("Error: %s", err)
|
||||
|
||||
40
pwval.go
40
pwval.go
@@ -1,8 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
@@ -21,11 +19,11 @@ func (vd *Validator) init(criteria ValidatorConf) {
|
||||
|
||||
// This isn't used, its for swagger
|
||||
type PasswordValidation struct {
|
||||
Characters bool `json:"characters,omitempty"` // Number of characters
|
||||
Lowercase bool `json:"lowercase characters,omitempty"` // Number of lowercase characters
|
||||
Uppercase bool `json:"uppercase characters,omitempty"` // Number of uppercase characters
|
||||
Numbers bool `json:"numbers,omitempty"` // Number of numbers
|
||||
Specials bool `json:"special characters,omitempty"` // Number of special characters
|
||||
Characters bool `json:"length,omitempty"` // Number of characters
|
||||
Lowercase bool `json:"lowercase,omitempty"` // Number of lowercase characters
|
||||
Uppercase bool `json:"uppercase,omitempty"` // Number of uppercase characters
|
||||
Numbers bool `json:"number,omitempty"` // Number of numbers
|
||||
Specials bool `json:"special,omitempty"` // Number of special characters
|
||||
}
|
||||
|
||||
func (vd *Validator) validate(password string) map[string]bool {
|
||||
@@ -34,17 +32,17 @@ func (vd *Validator) validate(password string) map[string]bool {
|
||||
count[key] = 0
|
||||
}
|
||||
for _, c := range password {
|
||||
count["characters"] += 1
|
||||
count["length"] += 1
|
||||
if unicode.IsUpper(c) {
|
||||
count["uppercase characters"] += 1
|
||||
count["uppercase"] += 1
|
||||
} else if unicode.IsLower(c) {
|
||||
count["lowercase characters"] += 1
|
||||
count["lowercase"] += 1
|
||||
} else if unicode.IsNumber(c) {
|
||||
count["numbers"] += 1
|
||||
count["number"] += 1
|
||||
} else {
|
||||
for _, s := range vd.specialChars {
|
||||
if c == s {
|
||||
count["special characters"] += 1
|
||||
count["special"] += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,18 +58,12 @@ func (vd *Validator) validate(password string) map[string]bool {
|
||||
return results
|
||||
}
|
||||
|
||||
func (vd *Validator) getCriteria() map[string]string {
|
||||
lines := map[string]string{}
|
||||
for criterion, min := range vd.criteria {
|
||||
if min > 0 {
|
||||
text := fmt.Sprintf("Must have at least %d ", min)
|
||||
if min == 1 {
|
||||
text += strings.TrimSuffix(criterion, "s")
|
||||
} else {
|
||||
text += criterion
|
||||
}
|
||||
lines[criterion] = text
|
||||
func (vd *Validator) getCriteria() ValidatorConf {
|
||||
criteria := ValidatorConf{}
|
||||
for key, num := range vd.criteria {
|
||||
if num != 0 {
|
||||
criteria[key] = num
|
||||
}
|
||||
}
|
||||
return lines
|
||||
return criteria
|
||||
}
|
||||
|
||||
@@ -120,3 +120,7 @@ body.modal-open {
|
||||
.unfocused {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.text-monospace {
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
@@ -142,4 +142,8 @@ $list-group-action-active-bg: $jf-blue-focus;
|
||||
background-color: $jf-blue-hover;
|
||||
}
|
||||
|
||||
.btn-close {
|
||||
filter: invert(80%);
|
||||
}
|
||||
|
||||
@import "../base.scss";
|
||||
|
||||
@@ -3,15 +3,8 @@ import sass
|
||||
import subprocess
|
||||
import shutil
|
||||
import os
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument(
|
||||
"-y", "--yes", help="use assumed node bin directory.", action="store_true"
|
||||
)
|
||||
|
||||
|
||||
def runcmd(cmd):
|
||||
if os.name == "nt":
|
||||
@@ -21,32 +14,22 @@ def runcmd(cmd):
|
||||
|
||||
|
||||
local_path = Path(__file__).resolve().parent
|
||||
out = runcmd("npm bin")
|
||||
|
||||
try:
|
||||
node_bin = Path(out[0].decode("utf-8").rstrip())
|
||||
except:
|
||||
node_bin = Path(out.decode("utf-8").rstrip())
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.yes:
|
||||
print(f'assuming npm bin directory "{node_bin}". Is this correct?')
|
||||
if input("[yY/nN]: ").lower() == "n":
|
||||
node_bin = local_path.parent / "node_modules" / ".bin"
|
||||
print(f'this? "{node_bin}"')
|
||||
if input("[yY/nN]: ").lower() == "n":
|
||||
node_bin = input("input bin directory: ")
|
||||
|
||||
for bsv in [d for d in local_path.iterdir() if "bs" in d.name]:
|
||||
scss = [(bsv / f"{bsv.name}-jf.scss"), (bsv / f"{bsv.name}.scss")]
|
||||
css = [(bsv / f"{bsv.name}-jf.css"), (bsv / f"{bsv.name}.css")]
|
||||
min_css = [(bsv.parents[1] / "data" / "static" / f"{bsv.name}-jf.css"), (bsv.parents[1] / "data" / "static" / f"{bsv.name}.css")]
|
||||
min_css = [
|
||||
(bsv.parents[1] / "data" / "static" / f"{bsv.name}-jf.css"),
|
||||
(bsv.parents[1] / "data" / "static" / f"{bsv.name}.css"),
|
||||
]
|
||||
for i in range(2):
|
||||
with open(css[i], "w") as f:
|
||||
f.write(
|
||||
sass.compile(
|
||||
filename=str(scss[i].resolve()), output_style="expanded", precision=6, omit_source_map_url=True
|
||||
filename=str(scss[i].resolve()),
|
||||
output_style="expanded",
|
||||
precision=6,
|
||||
omit_source_map_url=True,
|
||||
)
|
||||
)
|
||||
if css[i].exists():
|
||||
@@ -55,29 +38,12 @@ for bsv in [d for d in local_path.iterdir() if "bs" in d.name]:
|
||||
cssPath = str(css[i].resolve())
|
||||
if os.name == "nt":
|
||||
cssPath = cssPath.replace("\\", "/")
|
||||
runcmd(
|
||||
f'{str((node_bin / "postcss").resolve())} {cssPath} --replace --use autoprefixer'
|
||||
)
|
||||
runcmd(f"npx postcss {cssPath} --replace --use autoprefixer")
|
||||
print(f"{scss[i].name}: Prefixed.")
|
||||
runcmd(
|
||||
f'{str((node_bin / "cleancss").resolve())} --level 1 --format breakWith=lf --output {str(min_css[i].resolve())} {str(css[i].resolve())}'
|
||||
f"npx cleancss --level 1 --format breakWith=lf --output {str(min_css[i].resolve())} {str(css[i].resolve())}"
|
||||
)
|
||||
if min_css[i].exists():
|
||||
print(f"{scss[i].name}: Minified and copied to {str(min_css[i].resolve())}.")
|
||||
|
||||
# for v in [("bootstrap", "bs5"), ("bootstrap4", "bs4")]:
|
||||
# new_path = str((local_path.parent / "data" / "static" / (v[1] + ".css")).resolve())
|
||||
# shutil.copy(
|
||||
# str(
|
||||
# (
|
||||
# local_path.parent
|
||||
# / "node_modules"
|
||||
# / v[0]
|
||||
# / "dist"
|
||||
# / "css"
|
||||
# / "bootstrap.min.css"
|
||||
# ).resolve()
|
||||
# ),
|
||||
# new_path,
|
||||
# )
|
||||
# print(f"Copied {v[1]} to {new_path}")
|
||||
print(
|
||||
f"{scss[i].name}: Minified and copied to {str(min_css[i].resolve())}."
|
||||
)
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import subprocess
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def runcmd(cmd):
|
||||
if os.name == "nt":
|
||||
return subprocess.check_output(cmd, shell=True)
|
||||
proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
|
||||
return proc.communicate()
|
||||
|
||||
|
||||
print('Installing npm packages')
|
||||
|
||||
root_path = Path(__file__).parents[1]
|
||||
if os.name == 'nt':
|
||||
root_path /= 'node_modules'
|
||||
|
||||
runcmd('npm install')
|
||||
|
||||
if (root_path / 'node_modules' / 'cleancss').exists() or (root_path / 'cleancss').exists():
|
||||
print(f'Installed successfully in {str((root_path / "node_modules").resolve())}.')
|
||||
|
||||
|
||||
7
setup.go
7
setup.go
@@ -2,6 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/hrfee/jfa-go/common"
|
||||
"github.com/hrfee/jfa-go/jfapi"
|
||||
)
|
||||
|
||||
type testReq struct {
|
||||
@@ -13,9 +15,8 @@ type testReq struct {
|
||||
func (app *appContext) TestJF(gc *gin.Context) {
|
||||
var req testReq
|
||||
gc.BindJSON(&req)
|
||||
tempjf, _ := newJellyfin(req.Host, "jfa-go-setup", app.version, "auth", "auth")
|
||||
tempjf.noFail = true
|
||||
_, status, err := tempjf.authenticate(req.Username, req.Password)
|
||||
tempjf, _ := jfapi.NewJellyfin(req.Host, "jfa-go-setup", app.version, "auth", "auth", common.NewTimeoutHandler("authJF", req.Host, true), 30)
|
||||
_, status, err := tempjf.Authenticate(req.Username, req.Password)
|
||||
if !(status == 200 || status == 204) || err != nil {
|
||||
app.info.Printf("Auth failed with code %d (%s)", status, err)
|
||||
gc.JSON(401, map[string]bool{"success": false})
|
||||
|
||||
29
storage.go
29
storage.go
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
@@ -14,6 +15,12 @@ type Storage struct {
|
||||
profiles map[string]Profile
|
||||
defaultProfile string
|
||||
emails, policy, configuration, displayprefs, ombi_template map[string]interface{}
|
||||
lang Lang
|
||||
}
|
||||
|
||||
type Lang struct {
|
||||
FormPath string
|
||||
Form map[string]interface{}
|
||||
}
|
||||
|
||||
// timePattern: %Y-%m-%dT%H:%M:%S.%f
|
||||
@@ -49,6 +56,22 @@ func (st *Storage) storeInvites() error {
|
||||
return storeJSON(st.invite_path, st.invites)
|
||||
}
|
||||
|
||||
func (st *Storage) loadLang() error {
|
||||
err := loadJSON(st.lang.FormPath, &st.lang.Form)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
strings := st.lang.Form["strings"].(map[string]interface{})
|
||||
validationStrings := strings["validationStrings"].(map[string]interface{})
|
||||
vS, err := json.Marshal(validationStrings)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
strings["validationStrings"] = string(vS)
|
||||
st.lang.Form["strings"] = strings
|
||||
return nil
|
||||
}
|
||||
|
||||
func (st *Storage) loadEmails() error {
|
||||
return loadJSON(st.emails_path, &st.emails)
|
||||
}
|
||||
@@ -150,6 +173,9 @@ func loadJSON(path string, obj interface{}) error {
|
||||
file = []byte("{}")
|
||||
}
|
||||
err = json.Unmarshal(file, &obj)
|
||||
if err != nil {
|
||||
log.Printf("ERROR: Failed to read \"%s\": %s", path, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -159,5 +185,8 @@ func storeJSON(path string, obj interface{}) error {
|
||||
return err
|
||||
}
|
||||
err = ioutil.WriteFile(path, data, 0644)
|
||||
if err != nil {
|
||||
log.Printf("ERROR: Failed to write to \"%s\": %s", path, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
130
ts/accounts.ts
130
ts/accounts.ts
@@ -1,25 +1,17 @@
|
||||
const checkCheckboxes = (): void => {
|
||||
const defaultsButton = document.getElementById('accountsTabSetDefaults');
|
||||
const deleteButton = document.getElementById('accountsTabDelete');
|
||||
const checkboxes: NodeListOf<HTMLInputElement> = document.getElementById('accountsList').querySelectorAll('input[type=checkbox]:checked');
|
||||
let checked = checkboxes.length;
|
||||
if (checked == 0) {
|
||||
Unfocus(defaultsButton);
|
||||
Unfocus(deleteButton);
|
||||
} else {
|
||||
Focus(defaultsButton);
|
||||
Focus(deleteButton);
|
||||
if (checked == 1) {
|
||||
deleteButton.textContent = 'Delete User';
|
||||
} else {
|
||||
deleteButton.textContent = 'Delete Users';
|
||||
}
|
||||
}
|
||||
import { checkCheckboxes, populateUsers, populateRadios } from "./modules/accounts.js";
|
||||
import { _post, _get, _delete, rmAttr, addAttr } from "./modules/common.js";
|
||||
import { populateProfiles } from "./modules/settings.js";
|
||||
import { Focus, Unfocus, createEl, storeDefaults } from "./modules/admin.js";
|
||||
|
||||
interface aWindow extends Window {
|
||||
changeEmail(icon: HTMLElement, id: string): void;
|
||||
}
|
||||
|
||||
declare var window: aWindow;
|
||||
|
||||
const validateEmail = (email: string): boolean => /\S+@\S+\.\S+/.test(email);
|
||||
|
||||
function changeEmail(icon: HTMLElement, id: string): void {
|
||||
window.changeEmail = (icon: HTMLElement, id: string): void => {
|
||||
const iconContent = icon.outerHTML;
|
||||
icon.setAttribute('class', '');
|
||||
const entry = icon.nextElementSibling as HTMLInputElement;
|
||||
@@ -79,84 +71,6 @@ function changeEmail(icon: HTMLElement, id: string): void {
|
||||
icon.parentNode.appendChild(cross);
|
||||
};
|
||||
|
||||
var jfUsers: Array<Object>;
|
||||
|
||||
function populateUsers(): void {
|
||||
const acList = document.getElementById('accountsList');
|
||||
acList.innerHTML = `
|
||||
<div class="d-flex align-items-center">
|
||||
<strong>Getting Users...</strong>
|
||||
<div class="spinner-border ml-auto" role="status" aria-hidden="true"></div>
|
||||
</div>
|
||||
`;
|
||||
Unfocus(acList.parentNode.querySelector('thead'));
|
||||
const accountsList = document.createElement('tbody');
|
||||
accountsList.id = 'accountsList';
|
||||
const generateEmail = (id: string, name: string, email: string): string => {
|
||||
let entry: HTMLDivElement = document.createElement('div');
|
||||
entry.id = 'email_' + id;
|
||||
let emailValue: string = email;
|
||||
if (emailValue == undefined) {
|
||||
emailValue = "";
|
||||
}
|
||||
entry.innerHTML = `
|
||||
<i class="fa fa-edit d-inline-block icon-button" style="margin-right: 2%;" onclick="changeEmail(this, '${id}')"></i>
|
||||
<input type="email" class="form-control-plaintext form-control-sm text-muted d-inline-block addressText" id="address_${id}" style="width: auto;" value="${emailValue}" readonly>
|
||||
`;
|
||||
return entry.outerHTML;
|
||||
};
|
||||
const template = (id: string, username: string, email: string, lastActive: string, admin: boolean): string => {
|
||||
let isAdmin = "No";
|
||||
if (admin) {
|
||||
isAdmin = "Yes";
|
||||
}
|
||||
let fci = "form-check-input";
|
||||
if (bsVersion != 5) {
|
||||
fci = "";
|
||||
}
|
||||
return `
|
||||
<td nowrap="nowrap" class="align-middle" scope="row"><input class="${fci}" type="checkbox" value="" id="select_${id}" onclick="checkCheckboxes();"></td>
|
||||
<td nowrap="nowrap" class="align-middle">${username}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${generateEmail(id, name, email)}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${lastActive}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${isAdmin}</td>
|
||||
`;
|
||||
};
|
||||
|
||||
_get("/users", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
jfUsers = this.response['users'];
|
||||
for (const user of jfUsers) {
|
||||
let tr = document.createElement('tr');
|
||||
tr.innerHTML = template(user['id'], user['name'], user['email'], user['last_active'], user['admin']);
|
||||
accountsList.appendChild(tr);
|
||||
}
|
||||
Focus(acList.parentNode.querySelector('thead'));
|
||||
acList.replaceWith(accountsList);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function populateRadios(): void {
|
||||
const radioList = document.getElementById('defaultUserRadios');
|
||||
radioList.textContent = '';
|
||||
let first = true;
|
||||
for (const i in jfUsers) {
|
||||
const user = jfUsers[i];
|
||||
const radio = document.createElement('div');
|
||||
radio.classList.add('form-check');
|
||||
let checked = '';
|
||||
if (first) {
|
||||
checked = 'checked';
|
||||
first = false;
|
||||
}
|
||||
radio.innerHTML = `
|
||||
<input class="form-check-input" type="radio" name="defaultRadios" id="default_${user['id']}" ${checked}>
|
||||
<label class="form-check-label" for="default_${user['id']}">${user['name']}</label>`;
|
||||
radioList.appendChild(radio);
|
||||
}
|
||||
}
|
||||
|
||||
(<HTMLInputElement>document.getElementById('selectAll')).onclick = function (): void {
|
||||
const checkboxes: NodeListOf<HTMLInputElement> = document.getElementById('accountsList').querySelectorAll('input[type=checkbox]');
|
||||
for (let i = 0; i < checkboxes.length; i++) {
|
||||
@@ -217,18 +131,18 @@ function populateRadios(): void {
|
||||
}
|
||||
setTimeout((): void => {
|
||||
Unfocus(deleteButton);
|
||||
deleteModal.hide();
|
||||
window.Modals.delete.hide();
|
||||
}, 4000);
|
||||
} else {
|
||||
Unfocus(deleteButton);
|
||||
deleteModal.hide()
|
||||
window.Modals.delete.hide()
|
||||
}
|
||||
populateUsers();
|
||||
checkCheckboxes();
|
||||
}
|
||||
});
|
||||
};
|
||||
deleteModal.show();
|
||||
window.Modals.delete.show();
|
||||
};
|
||||
|
||||
(<HTMLInputElement>document.getElementById('selectAll')).checked = false;
|
||||
@@ -236,7 +150,7 @@ function populateRadios(): void {
|
||||
(<HTMLButtonElement>document.getElementById('accountsTabSetDefaults')).onclick = function (): void {
|
||||
const checkboxes: NodeListOf<HTMLInputElement> = document.getElementById('accountsList').querySelectorAll('input[type=checkbox]:checked');
|
||||
let userIDs: Array<string> = new Array(checkboxes.length);
|
||||
for (let i = 0; i < checkboxes.length; i++){
|
||||
for (let i = 0; i < checkboxes.length; i++){
|
||||
userIDs[i] = checkboxes[i].id.replace("select_", "");
|
||||
}
|
||||
if (userIDs.length == 0) {
|
||||
@@ -250,9 +164,9 @@ function populateRadios(): void {
|
||||
populateProfiles(true);
|
||||
const profileSelect = document.getElementById('profileSelect') as HTMLSelectElement;
|
||||
profileSelect.textContent = '';
|
||||
for (let i = 0; i < availableProfiles.length; i++) {
|
||||
for (let i = 0; i < window.availableProfiles.length; i++) {
|
||||
profileSelect.innerHTML += `
|
||||
<option value="${availableProfiles[i]}" ${(i == 0) ? "selected" : ""}>${availableProfiles[i]}</option>
|
||||
<option value="${window.availableProfiles[i]}" ${(i == 0) ? "selected" : ""}>${window.availableProfiles[i]}</option>
|
||||
`;
|
||||
}
|
||||
document.getElementById('defaultsTitle').textContent = `Apply settings to ${userIDs.length} ${userString}`;
|
||||
@@ -266,7 +180,7 @@ function populateRadios(): void {
|
||||
Unfocus(document.getElementById('defaultUserRadiosBox'));
|
||||
Unfocus(document.getElementById('newProfileBox'));
|
||||
document.getElementById('storeDefaults').onclick = (): void => storeDefaults(userIDs);
|
||||
userDefaultsModal.show();
|
||||
window.Modals.userDefaults.show();
|
||||
};
|
||||
|
||||
(<HTMLSelectElement>document.getElementById('defaultsSource')).addEventListener('change', function (): void {
|
||||
@@ -311,7 +225,7 @@ function populateRadios(): void {
|
||||
rmAttr(button, 'btn-success');
|
||||
addAttr(button, 'btn-primary');
|
||||
button.textContent = ogText;
|
||||
newUserModal.hide();
|
||||
window.Modals.newUser.hide();
|
||||
}, 1000);
|
||||
populateUsers();
|
||||
} else {
|
||||
@@ -338,11 +252,5 @@ function populateRadios(): void {
|
||||
if (document.getElementById('newUserName') != null) {
|
||||
(<HTMLInputElement>document.getElementById('newUserName')).value = '';
|
||||
}
|
||||
newUserModal.show();
|
||||
window.Modals.newUser.show();
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
179
ts/admin.ts
179
ts/admin.ts
@@ -1,47 +1,19 @@
|
||||
interface Window {
|
||||
token: string;
|
||||
import { serializeForm, rmAttr, addAttr, _get, _post, _delete } from "./modules/common.js";
|
||||
import { Focus, Unfocus } from "./modules/admin.js";
|
||||
import { toggleCSS } from "./modules/animation.js";
|
||||
import { populateUsers, checkCheckboxes } from "./modules/accounts.js";
|
||||
import { generateInvites, addOptions, checkDuration } from "./modules/invites.js";
|
||||
import { showSetting, openSettings } from "./modules/settings.js";
|
||||
import { BS4 } from "./modules/bs4.js";
|
||||
import { BS5 } from "./modules/bs5.js";
|
||||
import "./accounts.js";
|
||||
import "./settings.js";
|
||||
|
||||
interface aWindow extends Window {
|
||||
toClipboard(str: string): void;
|
||||
}
|
||||
|
||||
// Set in admin.html
|
||||
var cssFile: string;
|
||||
|
||||
const _get = (url: string, data: Object, onreadystatechange: () => void): void => {
|
||||
let req = new XMLHttpRequest();
|
||||
req.open("GET", url, true);
|
||||
req.responseType = 'json';
|
||||
req.setRequestHeader("Authorization", "Basic " + btoa(window.token + ":"));
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = onreadystatechange;
|
||||
req.send(JSON.stringify(data));
|
||||
};
|
||||
|
||||
const _post = (url: string, data: Object, onreadystatechange: () => void): void => {
|
||||
let req = new XMLHttpRequest();
|
||||
req.open("POST", url, true);
|
||||
req.setRequestHeader("Authorization", "Basic " + btoa(window.token + ":"));
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = onreadystatechange;
|
||||
req.send(JSON.stringify(data));
|
||||
};
|
||||
|
||||
function _delete(url: string, data: Object, onreadystatechange: () => void): void {
|
||||
let req = new XMLHttpRequest();
|
||||
req.open("DELETE", url, true);
|
||||
req.setRequestHeader("Authorization", "Basic " + btoa(window.token + ":"));
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = onreadystatechange;
|
||||
req.send(JSON.stringify(data));
|
||||
}
|
||||
|
||||
const rmAttr = (el: HTMLElement, attr: string): void => {
|
||||
if (el.classList.contains(attr)) {
|
||||
el.classList.remove(attr);
|
||||
}
|
||||
};
|
||||
const addAttr = (el: HTMLElement, attr: string): void => el.classList.add(attr);
|
||||
|
||||
const Focus = (el: HTMLElement): void => rmAttr(el, 'unfocused');
|
||||
const Unfocus = (el: HTMLElement): void => addAttr(el, 'unfocused');
|
||||
declare var window: aWindow;
|
||||
|
||||
interface TabSwitcher {
|
||||
els: Array<HTMLDivElement>;
|
||||
@@ -74,27 +46,43 @@ const tabs: TabSwitcher = {
|
||||
tabs.focus(1);
|
||||
},
|
||||
settings: (): void => openSettings(document.getElementById('settingsSections'), document.getElementById('settingsContent'), (): void => {
|
||||
triggerTooltips();
|
||||
window.BS.triggerTooltips();
|
||||
showSetting("ui");
|
||||
tabs.focus(2);
|
||||
})
|
||||
};
|
||||
|
||||
// for (let i = 0; i < tabs.els.length; i++) {
|
||||
// tabs.tabButtons[i].onclick = (): void => tabs.focus(i);
|
||||
// }
|
||||
window.bsVersion = window.bs5 ? 5 : 4
|
||||
|
||||
if (window.bs5) {
|
||||
window.BS = new BS5;
|
||||
} else {
|
||||
window.BS = new BS4;
|
||||
window.BS.Compat();
|
||||
}
|
||||
|
||||
window.Modals = {} as BSModals;
|
||||
|
||||
window.Modals.login = window.BS.newModal('login');
|
||||
window.Modals.userDefaults = window.BS.newModal('userDefaults');
|
||||
window.Modals.users = window.BS.newModal('users');
|
||||
window.Modals.restart = window.BS.newModal('restartModal');
|
||||
window.Modals.refresh = window.BS.newModal('refreshModal');
|
||||
window.Modals.about = window.BS.newModal('aboutModal');
|
||||
window.Modals.delete = window.BS.newModal('deleteModal');
|
||||
window.Modals.newUser = window.BS.newModal('newUserModal');
|
||||
|
||||
tabs.tabButtons[0].onclick = tabs.invites;
|
||||
tabs.tabButtons[1].onclick = tabs.accounts;
|
||||
tabs.tabButtons[2].onclick = tabs.settings;
|
||||
|
||||
|
||||
tabs.invites();
|
||||
|
||||
// Predefined colors for the theme button.
|
||||
var buttonColor: string = "custom";
|
||||
if (cssFile.includes("jf")) {
|
||||
if (window.cssFile.includes("jf")) {
|
||||
buttonColor = "rgb(255,255,255)";
|
||||
} else if (cssFile == ("bs" + bsVersion + ".css")) {
|
||||
} else if (window.cssFile == ("bs" + window.bsVersion + ".css")) {
|
||||
buttonColor = "rgb(16,16,16)";
|
||||
}
|
||||
|
||||
@@ -109,20 +97,11 @@ if (buttonColor != "custom") {
|
||||
document.getElementById('headerButtons').appendChild(switchButton);
|
||||
}
|
||||
|
||||
var loginModal = createModal('login');
|
||||
var userDefaultsModal = createModal('userDefaults');
|
||||
var usersModal = createModal('users');
|
||||
var restartModal = createModal('restartModal');
|
||||
var refreshModal = createModal('refreshModal');
|
||||
var aboutModal = createModal('aboutModal');
|
||||
var deleteModal = createModal('deleteModal');
|
||||
var newUserModal = createModal('newUserModal');
|
||||
|
||||
var availableProfiles: Array<string>;
|
||||
|
||||
window["token"] = "";
|
||||
|
||||
function toClipboard(str: string): void {
|
||||
window.toClipboard = (str: string): void => {
|
||||
const el = document.createElement('textarea') as HTMLTextAreaElement;
|
||||
el.value = str;
|
||||
el.readOnly = true;
|
||||
@@ -142,8 +121,15 @@ function toClipboard(str: string): void {
|
||||
function login(username: string, password: string, modal: boolean, button?: HTMLButtonElement, run?: (arg0: number) => void): void {
|
||||
const req = new XMLHttpRequest();
|
||||
req.responseType = 'json';
|
||||
req.open("GET", "/getToken", true);
|
||||
req.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
|
||||
let url = "/token/login";
|
||||
const refresh = (username == "" && password == "");
|
||||
if (refresh) {
|
||||
url = "/token/refresh";
|
||||
}
|
||||
req.open("GET", url, true);
|
||||
if (!refresh) {
|
||||
req.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
|
||||
}
|
||||
req.onreadystatechange = function (): void {
|
||||
if (this.readyState == 4) {
|
||||
if (this.status != 200) {
|
||||
@@ -162,7 +148,7 @@ function login(username: string, password: string, modal: boolean, button?: HTML
|
||||
button.textContent = "Login";
|
||||
}, 4000);
|
||||
} else {
|
||||
loginModal.show();
|
||||
window.Modals.login.show();
|
||||
}
|
||||
} else {
|
||||
const data = this.response;
|
||||
@@ -176,7 +162,7 @@ function login(username: string, password: string, modal: boolean, button?: HTML
|
||||
minutes.value = "30";
|
||||
checkDuration();
|
||||
if (modal) {
|
||||
loginModal.hide();
|
||||
window.Modals.login.hide();
|
||||
}
|
||||
Focus(document.getElementById('logoutButton'));
|
||||
}
|
||||
@@ -188,12 +174,6 @@ function login(username: string, password: string, modal: boolean, button?: HTML
|
||||
req.send();
|
||||
}
|
||||
|
||||
function createEl(html: string): HTMLElement {
|
||||
let div = document.createElement('div') as HTMLDivElement;
|
||||
div.innerHTML = html;
|
||||
return div.firstElementChild as HTMLElement;
|
||||
}
|
||||
|
||||
(document.getElementById('loginForm') as HTMLFormElement).onsubmit = function (): boolean {
|
||||
window.token = "";
|
||||
const details = serializeForm('loginForm');
|
||||
@@ -208,70 +188,11 @@ function createEl(html: string): HTMLElement {
|
||||
return false;
|
||||
};
|
||||
|
||||
function storeDefaults(users: string | Array<string>): void {
|
||||
// not sure if this does anything, but w/e
|
||||
this.disabled = true;
|
||||
this.innerHTML =
|
||||
'<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="margin-right: 0.5rem;"></span>' +
|
||||
'Loading...';
|
||||
const button = document.getElementById('storeDefaults') as HTMLButtonElement;
|
||||
let data = { "homescreen": false };
|
||||
if ((document.getElementById('defaultsSource') as HTMLSelectElement).value == 'profile') {
|
||||
data["from"] = "profile";
|
||||
data["profile"] = (document.getElementById('profileSelect') as HTMLSelectElement).value;
|
||||
} else {
|
||||
const radio = document.querySelector('input[name=defaultRadios]:checked') as HTMLInputElement
|
||||
let id = radio.id.replace("default_", "");
|
||||
data["from"] = "user";
|
||||
data["id"] = id;
|
||||
}
|
||||
if (users != "all") {
|
||||
data["apply_to"] = users;
|
||||
}
|
||||
if ((document.getElementById('storeDefaultHomescreen') as HTMLInputElement).checked) {
|
||||
data["homescreen"] = true;
|
||||
}
|
||||
_post("/users/settings", data, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
if (this.status == 200 || this.status == 204) {
|
||||
button.textContent = "Success";
|
||||
addAttr(button, "btn-success");
|
||||
rmAttr(button, "btn-danger");
|
||||
rmAttr(button, "btn-primary");
|
||||
button.disabled = false;
|
||||
setTimeout((): void => {
|
||||
button.textContent = "Submit";
|
||||
addAttr(button, "btn-primary");
|
||||
rmAttr(button, "btn-success");
|
||||
button.disabled = false;
|
||||
userDefaultsModal.hide();
|
||||
}, 1000);
|
||||
} else {
|
||||
if ("error" in this.response) {
|
||||
button.textContent = this.response["error"];
|
||||
} else if (("policy" in this.response) || ("homescreen" in this.response)) {
|
||||
button.textContent = "Failed (check console)";
|
||||
} else {
|
||||
button.textContent = "Failed";
|
||||
}
|
||||
addAttr(button, "btn-danger");
|
||||
rmAttr(button, "btn-primary");
|
||||
setTimeout((): void => {
|
||||
button.textContent = "Submit";
|
||||
addAttr(button, "btn-primary");
|
||||
rmAttr(button, "btn-danger");
|
||||
button.disabled = false;
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
generateInvites(true);
|
||||
|
||||
login("", "", false, null, (status: number): void => {
|
||||
if (!(status == 200 || status == 204)) {
|
||||
loginModal.show();
|
||||
window.Modals.login.show();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
36
ts/bs4.ts
36
ts/bs4.ts
@@ -1,36 +0,0 @@
|
||||
var bsVersion = 4;
|
||||
|
||||
const send_to_addess_enabled = document.getElementById('send_to_addess_enabled');
|
||||
if (send_to_addess_enabled) {
|
||||
send_to_addess_enabled.classList.remove("form-check-input");
|
||||
}
|
||||
const multiUseEnabled = document.getElementById('multiUseEnabled');
|
||||
if (multiUseEnabled) {
|
||||
multiUseEnabled.classList.remove("form-check-input");
|
||||
}
|
||||
|
||||
function createModal(id: string, find?: boolean): any {
|
||||
$(`#${id}`).on("shown.bs.modal", (): void => document.body.classList.add("modal-open"));
|
||||
return {
|
||||
show: function (): any {
|
||||
const temp = ($(`#${id}`) as any).modal("show");
|
||||
return temp;
|
||||
},
|
||||
hide: function (): any {
|
||||
return ($(`#${id}`) as any).modal("hide");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function triggerTooltips(): void {
|
||||
const checkboxes = [].slice.call(document.getElementById('settingsContent').querySelectorAll('input[type="checkbox"]'));
|
||||
for (const i in checkboxes) {
|
||||
checkboxes[i].click();
|
||||
checkboxes[i].click();
|
||||
}
|
||||
const tooltips = [].slice.call(document.querySelectorAll('a[data-toggle="tooltip"]'));
|
||||
tooltips.map((el: HTMLAnchorElement): any => {
|
||||
return ($(el) as any).tooltip();
|
||||
});
|
||||
}
|
||||
|
||||
34
ts/bs5.ts
34
ts/bs5.ts
@@ -1,34 +0,0 @@
|
||||
declare var bootstrap: any;
|
||||
|
||||
var bsVersion = 5;
|
||||
|
||||
function createModal(id: string, find?: boolean): any {
|
||||
let modal: any;
|
||||
if (find) {
|
||||
modal = bootstrap.Modal.getInstance(document.getElementById(id));
|
||||
} else {
|
||||
modal = new bootstrap.Modal(document.getElementById(id));
|
||||
}
|
||||
document.getElementById(id).addEventListener('shown.bs.modal', (): void => document.body.classList.add("modal-open"));
|
||||
return {
|
||||
modal: modal,
|
||||
show: function (): any {
|
||||
const temp = this.modal.show();
|
||||
return temp;
|
||||
},
|
||||
hide: function (): any { return this.modal.hide(); }
|
||||
};
|
||||
}
|
||||
|
||||
function triggerTooltips(): void {
|
||||
const checkboxes = [].slice.call(document.getElementById('settingsContent').querySelectorAll('input[type="checkbox"]'));
|
||||
for (const i in checkboxes) {
|
||||
checkboxes[i].click();
|
||||
checkboxes[i].click();
|
||||
}
|
||||
const tooltips = [].slice.call(document.querySelectorAll('a[data-toggle="tooltip"]'));
|
||||
tooltips.map((el: HTMLAnchorElement): any => {
|
||||
return new bootstrap.Tooltip(el);
|
||||
});
|
||||
}
|
||||
|
||||
153
ts/form.ts
Normal file
153
ts/form.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import { serializeForm, _post, _get, _delete, addAttr, rmAttr } from "./modules/common.js";
|
||||
import { BS5 } from "./modules/bs5.js";
|
||||
import { BS4 } from "./modules/bs4.js";
|
||||
|
||||
interface formWindow extends Window {
|
||||
usernameEnabled: boolean;
|
||||
validationStrings: pwValStrings;
|
||||
checkPassword(): void;
|
||||
invalidPassword: string;
|
||||
}
|
||||
|
||||
declare var window: formWindow;
|
||||
|
||||
interface pwValString {
|
||||
singular: string;
|
||||
plural: string;
|
||||
}
|
||||
|
||||
interface pwValStrings {
|
||||
length, uppercase, lowercase, number, special: pwValString;
|
||||
}
|
||||
|
||||
var defaultPwValStrings: pwValStrings = {
|
||||
length: {
|
||||
singular: "Must have at least {n} character",
|
||||
plural: "Must have a least {n} characters"
|
||||
},
|
||||
uppercase: {
|
||||
singular: "Must have at least {n} uppercase character",
|
||||
plural: "Must have at least {n} uppercase characters"
|
||||
},
|
||||
lowercase: {
|
||||
singular: "Must have at least {n} lowercase character",
|
||||
plural: "Must have at least {n} lowercase characters"
|
||||
},
|
||||
number: {
|
||||
singular: "Must have at least {n} number",
|
||||
plural: "Must have at least {n} numbers"
|
||||
},
|
||||
special: {
|
||||
singular: "Must have at least {n} special character",
|
||||
plural: "Must have at least {n} special characters"
|
||||
}
|
||||
}
|
||||
|
||||
const toggleSpinner = (ogText?: string): string => {
|
||||
const submitButton = document.getElementById('submitButton') as HTMLButtonElement;
|
||||
if (document.getElementById('createAccountSpinner')) {
|
||||
submitButton.innerHTML = ogText ? ogText : `<span>Create Account</span>`;
|
||||
submitButton.disabled = false;
|
||||
return "";
|
||||
} else {
|
||||
let ogText = submitButton.innerHTML;
|
||||
submitButton.innerHTML = `
|
||||
<span id="createAccountSpinner" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Creating...
|
||||
`;
|
||||
return ogText;
|
||||
}
|
||||
};
|
||||
|
||||
for (let key in window.validationStrings) {
|
||||
if (window.validationStrings[key].singular == "" || !(window.validationStrings[key].plural.includes("{n}"))) {
|
||||
window.validationStrings[key].singular = defaultPwValStrings[key].singular;
|
||||
}
|
||||
if (window.validationStrings[key].plural == "" || !(window.validationStrings[key].plural.includes("{n}"))) {
|
||||
window.validationStrings[key].plural = defaultPwValStrings[key].plural;
|
||||
}
|
||||
let el = document.getElementById(key) as HTMLUListElement;
|
||||
if (el) {
|
||||
const min: number = +el.getAttribute("min");
|
||||
let text = "";
|
||||
if (min == 1) {
|
||||
text = window.validationStrings[key].singular.replace("{n}", "1");
|
||||
} else {
|
||||
text = window.validationStrings[key].plural.replace("{n}", min.toString());
|
||||
}
|
||||
(document.getElementById(key).children[0] as HTMLDivElement).textContent = text;
|
||||
}
|
||||
}
|
||||
|
||||
window.BS = window.bs5 ? new BS5 : new BS4;
|
||||
var successBox: BSModal = window.BS.newModal('successBox');;
|
||||
|
||||
var code = window.location.href.split('/').pop();
|
||||
|
||||
(document.getElementById('accountForm') as HTMLFormElement).addEventListener('submit', (event: any): boolean => {
|
||||
event.preventDefault();
|
||||
const el = document.getElementById('errorMessage');
|
||||
if (el) {
|
||||
el.remove();
|
||||
}
|
||||
const ogText = toggleSpinner();
|
||||
let send: Object = serializeForm('accountForm');
|
||||
send["code"] = code;
|
||||
if (!window.usernameEnabled) {
|
||||
send["email"] = send["username"];
|
||||
}
|
||||
_post("/newUser", send, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
toggleSpinner(ogText);
|
||||
let data: Object = this.response;
|
||||
const errorGiven = ("error" in data)
|
||||
if (errorGiven || data["success"] === false) {
|
||||
let errorMessage = "Unknown Error";
|
||||
if (errorGiven && errorGiven != true) {
|
||||
errorMessage = data["error"];
|
||||
}
|
||||
document.getElementById('errorBox').innerHTML += `
|
||||
<button id="errorMessage" class="btn btn-outline-danger" disabled>${errorMessage}</button>
|
||||
`;
|
||||
} else {
|
||||
let valid = true;
|
||||
for (let key in data) {
|
||||
if (data.hasOwnProperty(key)) {
|
||||
const criterion = document.getElementById(key);
|
||||
if (criterion) {
|
||||
if (data[key] === false) {
|
||||
valid = false;
|
||||
addAttr(criterion, "list-group-item-danger");
|
||||
rmAttr(criterion, "list-group-item-success");
|
||||
} else {
|
||||
addAttr(criterion, "list-group-item-success");
|
||||
rmAttr(criterion, "list-group-item-danger");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (valid) {
|
||||
successBox.show();
|
||||
}
|
||||
}
|
||||
}
|
||||
}, true);
|
||||
return false;
|
||||
});
|
||||
|
||||
window.checkPassword = (): void => {
|
||||
const entry = document.getElementById('inputPassword') as HTMLInputElement;
|
||||
if (entry.value != "") {
|
||||
const reentry = document.getElementById('reInputPassword') as HTMLInputElement;
|
||||
const identical = (entry.value == reentry.value);
|
||||
const submitButton = document.getElementById('submitButton') as HTMLButtonElement;
|
||||
if (identical) {
|
||||
reentry.setCustomValidity('');
|
||||
rmAttr(submitButton, "btn-outline-danger");
|
||||
addAttr(submitButton, "btn-outline-primary");
|
||||
} else {
|
||||
reentry.setCustomValidity(window.invalidPassword);
|
||||
addAttr(submitButton, "btn-outline-danger");
|
||||
rmAttr(submitButton, "btn-outline-primary");
|
||||
}
|
||||
}
|
||||
}
|
||||
311
ts/invites.ts
311
ts/invites.ts
@@ -1,297 +1,11 @@
|
||||
// Actually defined by templating in admin.html, this is just to avoid errors from tsc.
|
||||
var notifications_enabled: any;
|
||||
import { serializeForm, rmAttr, addAttr, _get, _post, _delete } from "./modules/common.js";
|
||||
import { generateInvites, checkDuration } from "./modules/invites.js";
|
||||
|
||||
interface Invite {
|
||||
code?: string;
|
||||
expiresIn?: string;
|
||||
empty: boolean;
|
||||
remainingUses?: string;
|
||||
email?: string;
|
||||
usedBy?: Array<Array<string>>;
|
||||
created?: string;
|
||||
notifyExpiry?: boolean;
|
||||
notifyCreation?: boolean;
|
||||
profile?: string;
|
||||
interface aWindow extends Window {
|
||||
setProfile(el: HTMLElement): void;
|
||||
}
|
||||
|
||||
const emptyInvite = (): Invite => { return { code: "None", empty: true } as Invite; }
|
||||
|
||||
function parseInvite(invite: Object): Invite {
|
||||
let inv: Invite = { code: invite["code"], empty: false, };
|
||||
if (invite["email"]) {
|
||||
inv.email = invite["email"];
|
||||
}
|
||||
let time = ""
|
||||
const f = ["days", "hours", "minutes"];
|
||||
for (const i in f) {
|
||||
if (invite[f[i]] != 0) {
|
||||
time += `${invite[f[i]]}${f[i][0]} `;
|
||||
}
|
||||
}
|
||||
inv.expiresIn = `Expires in ${time.slice(0, -1)}`;
|
||||
if (invite["no-limit"]) {
|
||||
inv.remainingUses = "∞";
|
||||
} else if ("remaining-uses" in invite) {
|
||||
inv.remainingUses = invite["remaining-uses"];
|
||||
}
|
||||
if ("used-by" in invite) {
|
||||
inv.usedBy = invite["used-by"];
|
||||
}
|
||||
if ("created" in invite) {
|
||||
inv.created = invite["created"];
|
||||
}
|
||||
if ("notify-expiry" in invite) {
|
||||
inv.notifyExpiry = invite["notify-expiry"];
|
||||
}
|
||||
if ("notify-creation" in invite) {
|
||||
inv.notifyCreation = invite["notify-creation"];
|
||||
}
|
||||
if ("profile" in invite) {
|
||||
inv.profile = invite["profile"];
|
||||
}
|
||||
return inv;
|
||||
}
|
||||
|
||||
function setNotify(el: HTMLElement): void {
|
||||
let send = {};
|
||||
let code: string;
|
||||
let notifyType: string;
|
||||
if (el.id.includes("Expiry")) {
|
||||
code = el.id.replace("_notifyExpiry", "");
|
||||
notifyType = "notify-expiry";
|
||||
} else if (el.id.includes("Creation")) {
|
||||
code = el.id.replace("_notifyCreation", "");
|
||||
notifyType = "notify-creation";
|
||||
}
|
||||
send[code] = {};
|
||||
send[code][notifyType] = (el as HTMLInputElement).checked;
|
||||
_post("/invites/notify", send, function (): void {
|
||||
if (this.readyState == 4 && this.status != 200) {
|
||||
(el as HTMLInputElement).checked = !(el as HTMLInputElement).checked;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function genUsedBy(usedBy: Array<Array<string>>): string {
|
||||
let uB = "";
|
||||
if (usedBy && usedBy.length != 0) {
|
||||
uB = `
|
||||
<ul class="list-group list-group-flush">
|
||||
<li class="list-group-item py-1">Users created:</li>
|
||||
`;
|
||||
for (const i in usedBy) {
|
||||
uB += `
|
||||
<li class="list-group-item py-1 disabled">
|
||||
<div class="d-flex float-left">${usedBy[i][0]}</div>
|
||||
<div class="d-flex float-right">${usedBy[i][1]}</div>
|
||||
</li>
|
||||
`;
|
||||
}
|
||||
uB += `</ul>`
|
||||
}
|
||||
return uB;
|
||||
}
|
||||
|
||||
function addItem(invite: Invite): void {
|
||||
const links = document.getElementById('invites');
|
||||
const container = document.createElement('div') as HTMLDivElement;
|
||||
container.id = invite.code;
|
||||
const item = document.createElement('div') as HTMLDivElement;
|
||||
item.classList.add('list-group-item', 'd-flex', 'justify-content-between', 'd-inline-block');
|
||||
let link = "";
|
||||
let innerHTML = `<a>None</a>`;
|
||||
if (invite.empty) {
|
||||
item.innerHTML = `
|
||||
<div class="d-flex align-items-center font-monospace" style="width: 40%;">
|
||||
${innerHTML}
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(item);
|
||||
links.appendChild(container);
|
||||
return;
|
||||
}
|
||||
link = window.location.href.split('#')[0] + "invite/" + invite.code;
|
||||
innerHTML = `
|
||||
<div class="d-flex align-items-center font-monospace" style="width: 40%;">
|
||||
<a class="invite-link" href="${link}">${invite.code.replace(/-/g, '-')}</a>
|
||||
<i class="fa fa-clipboard icon-button" onclick="toClipboard('${link}')" style="margin-right: 0.5rem; margin-left: 0.5rem;"></i>
|
||||
`;
|
||||
if (invite.email) {
|
||||
let email = invite.email;
|
||||
if (!invite.email.includes("Failed to send to")) {
|
||||
email = `Sent to ${email}`;
|
||||
}
|
||||
innerHTML += `
|
||||
<span class="text-muted" style="margin-left: 0.4rem; font-style: italic; font-size: 0.8rem;">${email}</span>
|
||||
`;
|
||||
}
|
||||
innerHTML += `
|
||||
</div>
|
||||
<div style="text-align: right;">
|
||||
<span id="${invite.code}_expiry" style="margin-right: 1rem;">${invite.expiresIn}</span>
|
||||
<div style="display: inline-block;">
|
||||
<button class="btn btn-outline-danger" onclick="deleteInvite('${invite.code}')">Delete</button>
|
||||
<i class="fa fa-angle-down collapsed icon-button not-rotated" style="padding: 1rem; margin: -1rem -1rem -1rem 0;" data-toggle="collapse" aria-expanded="false" data-target="#${CSS.escape(invite.code)}_collapse" onclick="rotateButton(this)"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
item.innerHTML = innerHTML;
|
||||
container.appendChild(item);
|
||||
|
||||
let profiles = `
|
||||
<label class="input-group-text" for="profile_${CSS.escape(invite.code)}">Profile: </label>
|
||||
<select class="form-select" id="profile_${CSS.escape(invite.code)}" onchange="setProfile(this)">
|
||||
<option value="NoProfile" selected>No Profile</option>
|
||||
`;
|
||||
for (const i in availableProfiles) {
|
||||
let selected = "";
|
||||
if (availableProfiles[i] == invite.profile) {
|
||||
selected = "selected";
|
||||
}
|
||||
profiles += `<option value="${availableProfiles[i]}" ${selected}>${availableProfiles[i]}</option>`;
|
||||
}
|
||||
profiles += `</select>`;
|
||||
|
||||
let dateCreated: string;
|
||||
if (invite.created) {
|
||||
dateCreated = `<li class="list-group-item py-1">Created: ${invite.created}</li>`;
|
||||
}
|
||||
|
||||
let middle: string;
|
||||
if (notifications_enabled) {
|
||||
middle = `
|
||||
<div class="col" id="${CSS.escape(invite.code)}_notifyButtons">
|
||||
<ul class="list-group list-group-flush">
|
||||
Notify on:
|
||||
<li class="list-group-item py-1 form-check">
|
||||
<input class="form-check-input" type="checkbox" value="" id="${CSS.escape(invite.code)}_notifyExpiry" onclick="setNotify(this)" ${invite.notifyExpiry ? "checked" : ""}>
|
||||
<label class="form-check-label" for="${CSS.escape(invite.code)}_notifyExpiry">Expiry</label>
|
||||
</li>
|
||||
<li class="list-group-item py-1 form-check">
|
||||
<input class="form-check-input" type="checkbox" value="" id="${CSS.escape(invite.code)}_notifyCreation" onclick="setNotify(this)" ${invite.notifyCreation ? "checked" : ""}>
|
||||
<label class="form-check-label" for="${CSS.escape(invite.code)}_notifyCreation">User creation</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
let right: string = genUsedBy(invite.usedBy)
|
||||
|
||||
const dropdown = document.createElement('div') as HTMLDivElement;
|
||||
dropdown.id = `${CSS.escape(invite.code)}_collapse`;
|
||||
dropdown.classList.add("collapse");
|
||||
dropdown.innerHTML = `
|
||||
<div class="container row align-items-start card-body">
|
||||
<div class="col">
|
||||
<ul class="list-group list-group-flush">
|
||||
<li class="input-group py-1">
|
||||
${profiles}
|
||||
</li>
|
||||
${dateCreated}
|
||||
<li class="list-group-item py-1" id="${CSS.escape(invite.code)}_remainingUses">Remaining uses: ${invite.remainingUses}</li>
|
||||
</ul>
|
||||
</div>
|
||||
${middle}
|
||||
<div class="col" id="${CSS.escape(invite.code)}_usersCreated">
|
||||
${right}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
container.appendChild(dropdown);
|
||||
links.appendChild(container);
|
||||
}
|
||||
|
||||
function updateInvite(invite: Invite): void {
|
||||
document.getElementById(invite.code + "_expiry").textContent = invite.expiresIn;
|
||||
const remainingUses: any = document.getElementById(CSS.escape(invite.code) + "_remainingUses");
|
||||
if (remainingUses) {
|
||||
remainingUses.textContent = `Remaining uses: ${invite.remainingUses}`;
|
||||
}
|
||||
document.getElementById(CSS.escape(invite.code) + "_usersCreated").innerHTML = genUsedBy(invite.usedBy);
|
||||
}
|
||||
|
||||
// delete invite from DOM
|
||||
const hideInvite = (code: string): void => document.getElementById(CSS.escape(code)).remove();
|
||||
|
||||
// delete invite from jfa-go
|
||||
const deleteInvite = (code: string): void => _delete("/invites", { "code": code }, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
generateInvites();
|
||||
}
|
||||
});
|
||||
|
||||
function generateInvites(empty?: boolean): void {
|
||||
if (empty) {
|
||||
document.getElementById('invites').textContent = '';
|
||||
addItem(emptyInvite());
|
||||
return;
|
||||
}
|
||||
_get("/invites", null, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
let data = this.response;
|
||||
availableProfiles = data['profiles'];
|
||||
const Profiles = document.getElementById('inviteProfile') as HTMLSelectElement;
|
||||
let innerHTML = "";
|
||||
for (let i = 0; i < availableProfiles.length; i++) {
|
||||
const profile = availableProfiles[i];
|
||||
innerHTML += `
|
||||
<option value="${profile}" ${(i == 0) ? "selected" : ""}>${profile}</option>
|
||||
`;
|
||||
}
|
||||
innerHTML += `
|
||||
<option value="NoProfile" ${(availableProfiles.length == 0) ? "selected" : ""}>No Profile</option>
|
||||
`;
|
||||
Profiles.innerHTML = innerHTML;
|
||||
if (data['invites'] == null || data['invites'].length == 0) {
|
||||
document.getElementById('invites').textContent = '';
|
||||
addItem(emptyInvite());
|
||||
return;
|
||||
}
|
||||
let items = document.getElementById('invites').children;
|
||||
for (const i in data['invites']) {
|
||||
let match = false;
|
||||
const inv = parseInvite(data['invites'][i]);
|
||||
for (const x in items) {
|
||||
if (items[x].id == inv.code) {
|
||||
match = true;
|
||||
updateInvite(inv);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!match) {
|
||||
addItem(inv);
|
||||
}
|
||||
}
|
||||
// second pass to check for expired invites
|
||||
items = document.getElementById('invites').children;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
let exists = false;
|
||||
for (const x in data['invites']) {
|
||||
if (items[i].id == data['invites'][x]['code']) {
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!exists) {
|
||||
hideInvite(items[i].id);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const addOptions = (length: number, el: HTMLSelectElement): void => {
|
||||
for (let v = 0; v <= length; v++) {
|
||||
const opt = document.createElement('option');
|
||||
opt.textContent = ""+v;
|
||||
opt.value = ""+v;
|
||||
el.appendChild(opt);
|
||||
}
|
||||
el.value = "0";
|
||||
};
|
||||
declare var window: aWindow;
|
||||
|
||||
function fixCheckboxes(): void {
|
||||
const send_to_address: Array<HTMLInputElement> = [document.getElementById('send_to_address') as HTMLInputElement, document.getElementById('send_to_address_enabled') as HTMLInputElement];
|
||||
@@ -329,7 +43,6 @@ fixCheckboxes();
|
||||
delete send['send_to_address'];
|
||||
delete send['send_to_address_enabled'];
|
||||
}
|
||||
console.log(send);
|
||||
_post("/invites", send, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
button.textContent = 'Generate';
|
||||
@@ -340,9 +53,9 @@ fixCheckboxes();
|
||||
return false;
|
||||
};
|
||||
|
||||
triggerTooltips();
|
||||
window.BS.triggerTooltips();
|
||||
|
||||
function setProfile(select: HTMLSelectElement): void {
|
||||
window.setProfile= (select: HTMLSelectElement): void => {
|
||||
if (!select.value) {
|
||||
return;
|
||||
}
|
||||
@@ -362,16 +75,6 @@ function setProfile(select: HTMLSelectElement): void {
|
||||
});
|
||||
}
|
||||
|
||||
function checkDuration(): void {
|
||||
const boxVals: Array<number> = [+(document.getElementById("days") as HTMLSelectElement).value, +(document.getElementById("hours") as HTMLSelectElement).value, +(document.getElementById("minutes") as HTMLSelectElement).value];
|
||||
const submit = document.getElementById('generateSubmit') as HTMLButtonElement;
|
||||
if (boxVals.reduce((a: number, b: number): number => a + b) == 0) {
|
||||
submit.disabled = true;
|
||||
} else {
|
||||
submit.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
const nE: Array<string> = ["days", "hours", "minutes"];
|
||||
for (const i in nE) {
|
||||
document.getElementById(nE[i]).addEventListener("change", checkDuration);
|
||||
|
||||
105
ts/modules/accounts.ts
Normal file
105
ts/modules/accounts.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { _get, _post, _delete } from "../modules/common.js";
|
||||
import { Focus, Unfocus } from "../modules/admin.js";
|
||||
|
||||
interface aWindow extends Window {
|
||||
checkCheckboxes: () => void;
|
||||
}
|
||||
|
||||
declare var window: aWindow;
|
||||
|
||||
export const checkCheckboxes = (): void => {
|
||||
const defaultsButton = document.getElementById('accountsTabSetDefaults');
|
||||
const deleteButton = document.getElementById('accountsTabDelete');
|
||||
const checkboxes: NodeListOf<HTMLInputElement> = document.getElementById('accountsList').querySelectorAll('input[type=checkbox]:checked');
|
||||
let checked = checkboxes.length;
|
||||
if (checked == 0) {
|
||||
Unfocus(defaultsButton);
|
||||
Unfocus(deleteButton);
|
||||
} else {
|
||||
Focus(defaultsButton);
|
||||
Focus(deleteButton);
|
||||
if (checked == 1) {
|
||||
deleteButton.textContent = 'Delete User';
|
||||
} else {
|
||||
deleteButton.textContent = 'Delete Users';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.checkCheckboxes = checkCheckboxes;
|
||||
|
||||
export function populateUsers(): void {
|
||||
const acList = document.getElementById('accountsList');
|
||||
acList.innerHTML = `
|
||||
<div class="d-flex align-items-center">
|
||||
<strong>Getting Users...</strong>
|
||||
<div class="spinner-border ml-auto" role="status" aria-hidden="true"></div>
|
||||
</div>
|
||||
`;
|
||||
Unfocus(acList.parentNode.querySelector('thead'));
|
||||
const accountsList = document.createElement('tbody');
|
||||
accountsList.id = 'accountsList';
|
||||
const generateEmail = (id: string, name: string, email: string): string => {
|
||||
let entry: HTMLDivElement = document.createElement('div');
|
||||
entry.id = 'email_' + id;
|
||||
let emailValue: string = email;
|
||||
if (emailValue == undefined) {
|
||||
emailValue = "";
|
||||
}
|
||||
entry.innerHTML = `
|
||||
<i class="fa fa-edit d-inline-block icon-button" style="margin-right: 2%;" onclick="changeEmail(this, '${id}')"></i>
|
||||
<input type="email" class="form-control-plaintext form-control-sm text-muted d-inline-block addressText" id="address_${id}" style="width: auto;" value="${emailValue}" readonly>
|
||||
`;
|
||||
return entry.outerHTML;
|
||||
};
|
||||
const template = (id: string, username: string, email: string, lastActive: string, admin: boolean): string => {
|
||||
let isAdmin = "No";
|
||||
if (admin) {
|
||||
isAdmin = "Yes";
|
||||
}
|
||||
let fci = "form-check-input";
|
||||
if (window.bsVersion != 5) {
|
||||
fci = "";
|
||||
}
|
||||
return `
|
||||
<td nowrap="nowrap" class="align-middle" scope="row"><input class="${fci}" type="checkbox" value="" id="select_${id}" onclick="checkCheckboxes();"></td>
|
||||
<td nowrap="nowrap" class="align-middle">${username}${admin ? '<span style="margin-left: 1rem;" class="badge rounded-pill bg-info text-dark">Admin</span>' : ''}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${generateEmail(id, name, email)}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${lastActive}</td>
|
||||
`;
|
||||
};
|
||||
|
||||
_get("/users", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
window.jfUsers = this.response['users'];
|
||||
for (const user of window.jfUsers) {
|
||||
let tr = document.createElement('tr');
|
||||
tr.innerHTML = template(user['id'], user['name'], user['email'], user['last_active'], user['admin']);
|
||||
accountsList.appendChild(tr);
|
||||
}
|
||||
Focus(acList.parentNode.querySelector('thead'));
|
||||
acList.replaceWith(accountsList);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function populateRadios(): void {
|
||||
const radioList = document.getElementById('defaultUserRadios');
|
||||
radioList.textContent = '';
|
||||
let first = true;
|
||||
for (const i in window.jfUsers) {
|
||||
const user = window.jfUsers[i];
|
||||
const radio = document.createElement('div');
|
||||
radio.classList.add('form-check');
|
||||
let checked = '';
|
||||
if (first) {
|
||||
checked = 'checked';
|
||||
first = false;
|
||||
}
|
||||
radio.innerHTML = `
|
||||
<input class="form-check-input" type="radio" name="defaultRadios" id="default_${user['id']}" ${checked}>
|
||||
<label class="form-check-label" for="default_${user['id']}">${user['name']}</label>`;
|
||||
radioList.appendChild(radio);
|
||||
}
|
||||
}
|
||||
|
||||
68
ts/modules/admin.ts
Normal file
68
ts/modules/admin.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { rmAttr, addAttr, _post, _get, _delete } from "../modules/common.js";
|
||||
|
||||
export const Focus = (el: HTMLElement): void => rmAttr(el, 'unfocused');
|
||||
export const Unfocus = (el: HTMLElement): void => addAttr(el, 'unfocused');
|
||||
|
||||
export function createEl(html: string): HTMLElement {
|
||||
let div = document.createElement('div') as HTMLDivElement;
|
||||
div.innerHTML = html;
|
||||
return div.firstElementChild as HTMLElement;
|
||||
}
|
||||
|
||||
export function storeDefaults(users: string | Array<string>): void {
|
||||
const button = document.getElementById('storeDefaults') as HTMLButtonElement;
|
||||
button.disabled = true;
|
||||
button.innerHTML =
|
||||
'<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="margin-right: 0.5rem;"></span>' +
|
||||
'Loading...';
|
||||
let data = { "homescreen": false };
|
||||
if ((document.getElementById('defaultsSource') as HTMLSelectElement).value == 'profile') {
|
||||
data["from"] = "profile";
|
||||
data["profile"] = (document.getElementById('profileSelect') as HTMLSelectElement).value;
|
||||
} else {
|
||||
const radio = document.querySelector('input[name=defaultRadios]:checked') as HTMLInputElement
|
||||
let id = radio.id.replace("default_", "");
|
||||
data["from"] = "user";
|
||||
data["id"] = id;
|
||||
}
|
||||
if (users != "all") {
|
||||
data["apply_to"] = users;
|
||||
}
|
||||
if ((document.getElementById('storeDefaultHomescreen') as HTMLInputElement).checked) {
|
||||
data["homescreen"] = true;
|
||||
}
|
||||
_post("/users/settings", data, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
if (this.status == 200 || this.status == 204) {
|
||||
button.textContent = "Success";
|
||||
addAttr(button, "btn-success");
|
||||
rmAttr(button, "btn-danger");
|
||||
rmAttr(button, "btn-primary");
|
||||
button.disabled = false;
|
||||
setTimeout((): void => {
|
||||
button.textContent = "Submit";
|
||||
addAttr(button, "btn-primary");
|
||||
rmAttr(button, "btn-success");
|
||||
button.disabled = false;
|
||||
window.Modals.userDefaults.hide();
|
||||
}, 1000);
|
||||
} else {
|
||||
if ("error" in this.response) {
|
||||
button.textContent = this.response["error"];
|
||||
} else if (("policy" in this.response) || ("homescreen" in this.response)) {
|
||||
button.textContent = "Failed (check console)";
|
||||
} else {
|
||||
button.textContent = "Failed";
|
||||
}
|
||||
addAttr(button, "btn-danger");
|
||||
rmAttr(button, "btn-primary");
|
||||
setTimeout((): void => {
|
||||
button.textContent = "Submit";
|
||||
addAttr(button, "btn-primary");
|
||||
rmAttr(button, "btn-danger");
|
||||
button.disabled = false;
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,11 @@
|
||||
import { rmAttr, addAttr } from "../modules/common.js";
|
||||
|
||||
interface aWindow extends Window {
|
||||
rotateButton(el: HTMLElement): void;
|
||||
}
|
||||
|
||||
declare var window: aWindow;
|
||||
|
||||
// Used for animation on theme change
|
||||
const whichTransitionEvent = (): string => {
|
||||
const el = document.createElement('fakeElement');
|
||||
@@ -26,7 +34,7 @@ const _toggleCSS = (): void => {
|
||||
cssEl = 1;
|
||||
remove = true
|
||||
}
|
||||
let href: string = "bs" + bsVersion;
|
||||
let href: string = "bs" + window.bsVersion;
|
||||
if (!els[cssEl].href.includes(href + "-jf")) {
|
||||
href += "-jf";
|
||||
}
|
||||
@@ -41,8 +49,8 @@ const _toggleCSS = (): void => {
|
||||
}
|
||||
|
||||
// Toggles between light and dark themes, but runs animation if window small enough.
|
||||
var buttonWidth = 0;
|
||||
const toggleCSS = (el: HTMLElement): void => {
|
||||
window.buttonWidth = 0;
|
||||
export const toggleCSS = (el: HTMLElement): void => {
|
||||
const switchToColor = window.getComputedStyle(document.body, null).backgroundColor;
|
||||
// Max page width for animation to take place
|
||||
let maxWidth = 1500;
|
||||
@@ -51,7 +59,7 @@ const toggleCSS = (el: HTMLElement): void => {
|
||||
const radius = Math.sqrt(Math.pow(window.innerWidth, 2) + Math.pow(window.innerHeight, 2));
|
||||
const currentRadius = el.getBoundingClientRect().width / 2;
|
||||
const scale = radius / currentRadius;
|
||||
buttonWidth = +window.getComputedStyle(el, null).width;
|
||||
window.buttonWidth = +window.getComputedStyle(el, null).width;
|
||||
document.body.classList.remove('smooth-transition');
|
||||
el.style.transform = `scale(${scale})`;
|
||||
el.style.color = switchToColor;
|
||||
@@ -68,7 +76,7 @@ const toggleCSS = (el: HTMLElement): void => {
|
||||
}
|
||||
};
|
||||
|
||||
const rotateButton = (el: HTMLElement): void => {
|
||||
window.rotateButton = (el: HTMLElement): void => {
|
||||
if (el.classList.contains("rotated")) {
|
||||
rmAttr(el, "rotated")
|
||||
addAttr(el, "not-rotated");
|
||||
45
ts/modules/bs4.ts
Normal file
45
ts/modules/bs4.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
declare var $: any;
|
||||
|
||||
class Modal implements BSModal {
|
||||
el: HTMLDivElement;
|
||||
modal: any;
|
||||
|
||||
constructor(id: string, find?: boolean) {
|
||||
this.el = document.getElementById(id) as HTMLDivElement;
|
||||
this.modal = $(this.el) as any;
|
||||
this.modal.on("shown.b.modal", (): void => document.body.classList.add('modal-open'));
|
||||
};
|
||||
|
||||
show(): void { this.modal.modal("show"); };
|
||||
hide(): void { this.modal.modal("hide"); };
|
||||
}
|
||||
|
||||
export class BS4 implements Bootstrap {
|
||||
triggerTooltips: tooltipTrigger = function (): void {
|
||||
const checkboxes = [].slice.call(document.getElementById('settingsContent').querySelectorAll('input[type="checkbox"]'));
|
||||
for (const i in checkboxes) {
|
||||
checkboxes[i].click();
|
||||
checkboxes[i].click();
|
||||
}
|
||||
const tooltips = [].slice.call(document.querySelectorAll('a[data-toggle="tooltip"]'));
|
||||
tooltips.map((el: HTMLAnchorElement): any => {
|
||||
return ($(el) as any).tooltip();
|
||||
});
|
||||
};
|
||||
|
||||
Compat(): void {
|
||||
console.log('Fixing BS4 Compatability');
|
||||
const send_to_address_enabled = document.getElementById('send_to_address_enabled');
|
||||
if (send_to_address_enabled) {
|
||||
send_to_address_enabled.classList.remove("form-check-input");
|
||||
}
|
||||
const multiUseEnabled = document.getElementById('multiUseEnabled');
|
||||
if (multiUseEnabled) {
|
||||
multiUseEnabled.classList.remove("form-check-input");
|
||||
}
|
||||
}
|
||||
|
||||
newModal: ModalConstructor = function (id: string, find?: boolean): BSModal {
|
||||
return new Modal(id, find);
|
||||
};
|
||||
}
|
||||
37
ts/modules/bs5.ts
Normal file
37
ts/modules/bs5.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
declare var bootstrap: any;
|
||||
|
||||
class Modal implements BSModal {
|
||||
el: HTMLDivElement;
|
||||
modal: any;
|
||||
|
||||
constructor(id: string, find?: boolean) {
|
||||
this.el = document.getElementById(id) as HTMLDivElement;
|
||||
if (find) {
|
||||
this.modal = bootstrap.Modal.getInstance(this.el);
|
||||
} else {
|
||||
this.modal = new bootstrap.Modal(this.el);
|
||||
}
|
||||
this.el.addEventListener('shown.bs.modal', (): void => document.body.classList.add("modal-open"));
|
||||
};
|
||||
|
||||
show(): void { this.modal.show(); };
|
||||
hide(): void { this.modal.hide(); };
|
||||
}
|
||||
|
||||
export class BS5 implements Bootstrap {
|
||||
triggerTooltips: tooltipTrigger = function (): void {
|
||||
const checkboxes = [].slice.call(document.getElementById('settingsContent').querySelectorAll('input[type="checkbox"]'));
|
||||
for (const i in checkboxes) {
|
||||
checkboxes[i].click();
|
||||
checkboxes[i].click();
|
||||
}
|
||||
const tooltips = [].slice.call(document.querySelectorAll('a[data-toggle="tooltip"]'));
|
||||
tooltips.map((el: HTMLAnchorElement): any => {
|
||||
return new bootstrap.Tooltip(el);
|
||||
});
|
||||
};
|
||||
|
||||
newModal: ModalConstructor = function (id: string, find?: boolean): BSModal {
|
||||
return new Modal(id, find);
|
||||
};
|
||||
};
|
||||
77
ts/modules/common.ts
Normal file
77
ts/modules/common.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
declare var window: Window;
|
||||
|
||||
export function serializeForm(id: string): Object {
|
||||
const form = document.getElementById(id) as HTMLFormElement;
|
||||
let formData = {};
|
||||
for (let i = 0; i < form.elements.length; i++) {
|
||||
const el = form.elements[i];
|
||||
if ((el as HTMLInputElement).type == "submit") {
|
||||
continue;
|
||||
}
|
||||
let name = (el as HTMLInputElement).name;
|
||||
if (!name) {
|
||||
name = el.id;
|
||||
}
|
||||
switch ((el as HTMLInputElement).type) {
|
||||
case "checkbox":
|
||||
formData[name] = (el as HTMLInputElement).checked;
|
||||
break;
|
||||
case "text":
|
||||
case "password":
|
||||
case "email":
|
||||
case "number":
|
||||
formData[name] = (el as HTMLInputElement).value;
|
||||
break;
|
||||
case "select-one":
|
||||
case "select":
|
||||
let val: string = (el as HTMLSelectElement).value.toString();
|
||||
if (!isNaN(val as any)) {
|
||||
formData[name] = +val;
|
||||
} else {
|
||||
formData[name] = val;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return formData;
|
||||
}
|
||||
|
||||
export const rmAttr = (el: HTMLElement, attr: string): void => {
|
||||
if (el.classList.contains(attr)) {
|
||||
el.classList.remove(attr);
|
||||
}
|
||||
};
|
||||
|
||||
export const addAttr = (el: HTMLElement, attr: string): void => el.classList.add(attr);
|
||||
|
||||
export const _get = (url: string, data: Object, onreadystatechange: () => void): void => {
|
||||
let req = new XMLHttpRequest();
|
||||
req.open("GET", url, true);
|
||||
req.responseType = 'json';
|
||||
req.setRequestHeader("Authorization", "Bearer " + window.token);
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = onreadystatechange;
|
||||
req.send(JSON.stringify(data));
|
||||
};
|
||||
|
||||
export const _post = (url: string, data: Object, onreadystatechange: () => void, response?: boolean): void => {
|
||||
let req = new XMLHttpRequest();
|
||||
req.open("POST", url, true);
|
||||
if (response) {
|
||||
req.responseType = 'json';
|
||||
}
|
||||
req.setRequestHeader("Authorization", "Bearer " + window.token);
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = onreadystatechange;
|
||||
req.send(JSON.stringify(data));
|
||||
};
|
||||
|
||||
export function _delete(url: string, data: Object, onreadystatechange: () => void): void {
|
||||
let req = new XMLHttpRequest();
|
||||
req.open("DELETE", url, true);
|
||||
req.setRequestHeader("Authorization", "Bearer " + window.token);
|
||||
req.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
|
||||
req.onreadystatechange = onreadystatechange;
|
||||
req.send(JSON.stringify(data));
|
||||
}
|
||||
|
||||
297
ts/modules/invites.ts
Normal file
297
ts/modules/invites.ts
Normal file
@@ -0,0 +1,297 @@
|
||||
import { _get, _post, _delete } from "../modules/common.js";
|
||||
|
||||
interface aWindow extends Window {
|
||||
setNotify(el: HTMLElement): void;
|
||||
deleteInvite(code: string): void;
|
||||
}
|
||||
|
||||
declare var window: aWindow;
|
||||
|
||||
const emptyInvite = (): Invite => { return { code: "None", empty: true } as Invite; }
|
||||
|
||||
function genUsedBy(usedBy: Array<Array<string>>): string {
|
||||
let uB = "";
|
||||
if (usedBy && usedBy.length != 0) {
|
||||
uB = `
|
||||
<ul class="list-group list-group-flush">
|
||||
<li class="list-group-item py-1">Users created:</li>
|
||||
`;
|
||||
for (const i in usedBy) {
|
||||
uB += `
|
||||
<li class="list-group-item py-1 disabled">
|
||||
<div class="d-flex float-left">${usedBy[i][0]}</div>
|
||||
<div class="d-flex float-right">${usedBy[i][1]}</div>
|
||||
</li>
|
||||
`;
|
||||
}
|
||||
uB += `</ul>`
|
||||
}
|
||||
return uB;
|
||||
}
|
||||
|
||||
function addItem(invite: Invite): void {
|
||||
const links = document.getElementById('invites');
|
||||
const container = document.createElement('div') as HTMLDivElement;
|
||||
container.id = invite.code;
|
||||
const item = document.createElement('div') as HTMLDivElement;
|
||||
item.classList.add('list-group-item', 'd-flex', 'justify-content-between', 'd-inline-block');
|
||||
let link = "";
|
||||
let innerHTML = `<a>None</a>`;
|
||||
if (invite.empty) {
|
||||
item.innerHTML = `
|
||||
<div class="d-flex align-items-center font-monospace" style="width: 40%;">
|
||||
${innerHTML}
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(item);
|
||||
links.appendChild(container);
|
||||
return;
|
||||
}
|
||||
link = window.location.href.split('#')[0] + "invite/" + invite.code;
|
||||
innerHTML = `
|
||||
<div class="d-flex align-items-center font-monospace" style="width: 40%;">
|
||||
<a class="invite-link" href="${link}">${invite.code.replace(/-/g, '-')}</a>
|
||||
<i class="fa fa-clipboard icon-button" onclick="window.toClipboard('${link}')" style="margin-right: 0.5rem; margin-left: 0.5rem;"></i>
|
||||
`;
|
||||
if (invite.email) {
|
||||
let email = invite.email;
|
||||
if (!invite.email.includes("Failed to send to")) {
|
||||
email = `Sent to ${email}`;
|
||||
}
|
||||
innerHTML += `
|
||||
<span class="text-muted" style="margin-left: 0.4rem; font-style: italic; font-size: 0.8rem;">${email}</span>
|
||||
`;
|
||||
}
|
||||
innerHTML += `
|
||||
</div>
|
||||
<div style="text-align: right;">
|
||||
<span id="${invite.code}_expiry" style="margin-right: 1rem;">${invite.expiresIn}</span>
|
||||
<div style="display: inline-block;">
|
||||
<button class="btn btn-outline-danger" onclick="deleteInvite('${invite.code}')">Delete</button>
|
||||
<i class="fa fa-angle-down collapsed icon-button not-rotated" style="padding: 1rem; margin: -1rem -1rem -1rem 0;" data-toggle="collapse" aria-expanded="false" data-target="#${CSS.escape(invite.code)}_collapse" onclick="window.rotateButton(this)"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
item.innerHTML = innerHTML;
|
||||
container.appendChild(item);
|
||||
|
||||
let profiles = `
|
||||
<label class="input-group-text" for="profile_${CSS.escape(invite.code)}">Profile: </label>
|
||||
<select class="form-select" id="profile_${CSS.escape(invite.code)}" onchange="window.setProfile(this)">
|
||||
<option value="NoProfile" selected>No Profile</option>
|
||||
`;
|
||||
for (const i in window.availableProfiles) {
|
||||
let selected = "";
|
||||
if (window.availableProfiles[i] == invite.profile) {
|
||||
selected = "selected";
|
||||
}
|
||||
profiles += `<option value="${window.availableProfiles[i]}" ${selected}>${window.availableProfiles[i]}</option>`;
|
||||
}
|
||||
profiles += `</select>`;
|
||||
|
||||
let dateCreated: string;
|
||||
if (invite.created) {
|
||||
dateCreated = `<li class="list-group-item py-1">Created: ${invite.created}</li>`;
|
||||
}
|
||||
|
||||
let middle: string;
|
||||
if (window.notifications_enabled) {
|
||||
middle = `
|
||||
<div class="col" id="${CSS.escape(invite.code)}_notifyButtons">
|
||||
<ul class="list-group list-group-flush">
|
||||
Notify on:
|
||||
<li class="list-group-item py-1 form-check">
|
||||
<input class="form-check-input" type="checkbox" value="" id="${CSS.escape(invite.code)}_notifyExpiry" onclick="setNotify(this)" ${invite.notifyExpiry ? "checked" : ""}>
|
||||
<label class="form-check-label" for="${CSS.escape(invite.code)}_notifyExpiry">Expiry</label>
|
||||
</li>
|
||||
<li class="list-group-item py-1 form-check">
|
||||
<input class="form-check-input" type="checkbox" value="" id="${CSS.escape(invite.code)}_notifyCreation" onclick="setNotify(this)" ${invite.notifyCreation ? "checked" : ""}>
|
||||
<label class="form-check-label" for="${CSS.escape(invite.code)}_notifyCreation">User creation</label>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
let right: string = genUsedBy(invite.usedBy)
|
||||
|
||||
const dropdown = document.createElement('div') as HTMLDivElement;
|
||||
dropdown.id = `${CSS.escape(invite.code)}_collapse`;
|
||||
dropdown.classList.add("collapse");
|
||||
dropdown.innerHTML = `
|
||||
<div class="container row align-items-start card-body">
|
||||
<div class="col">
|
||||
<ul class="list-group list-group-flush">
|
||||
<li class="input-group py-1">
|
||||
${profiles}
|
||||
</li>
|
||||
${dateCreated}
|
||||
<li class="list-group-item py-1" id="${CSS.escape(invite.code)}_remainingUses">Remaining uses: ${invite.remainingUses}</li>
|
||||
</ul>
|
||||
</div>
|
||||
${middle}
|
||||
<div class="col" id="${CSS.escape(invite.code)}_usersCreated">
|
||||
${right}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
container.appendChild(dropdown);
|
||||
links.appendChild(container);
|
||||
}
|
||||
|
||||
function parseInvite(invite: Object): Invite {
|
||||
let inv: Invite = { code: invite["code"], empty: false, };
|
||||
if (invite["email"]) {
|
||||
inv.email = invite["email"];
|
||||
}
|
||||
let time = ""
|
||||
const f = ["days", "hours", "minutes"];
|
||||
for (const i in f) {
|
||||
if (invite[f[i]] != 0) {
|
||||
time += `${invite[f[i]]}${f[i][0]} `;
|
||||
}
|
||||
}
|
||||
inv.expiresIn = `Expires in ${time.slice(0, -1)}`;
|
||||
if (invite["no-limit"]) {
|
||||
inv.remainingUses = "∞";
|
||||
} else if ("remaining-uses" in invite) {
|
||||
inv.remainingUses = invite["remaining-uses"];
|
||||
}
|
||||
if ("used-by" in invite) {
|
||||
inv.usedBy = invite["used-by"];
|
||||
}
|
||||
if ("created" in invite) {
|
||||
inv.created = invite["created"];
|
||||
}
|
||||
if ("notify-expiry" in invite) {
|
||||
inv.notifyExpiry = invite["notify-expiry"];
|
||||
}
|
||||
if ("notify-creation" in invite) {
|
||||
inv.notifyCreation = invite["notify-creation"];
|
||||
}
|
||||
if ("profile" in invite) {
|
||||
inv.profile = invite["profile"];
|
||||
}
|
||||
return inv;
|
||||
}
|
||||
|
||||
window.setNotify = (el: HTMLElement): void => {
|
||||
let send = {};
|
||||
let code: string;
|
||||
let notifyType: string;
|
||||
if (el.id.includes("Expiry")) {
|
||||
code = el.id.replace("_notifyExpiry", "");
|
||||
notifyType = "notify-expiry";
|
||||
} else if (el.id.includes("Creation")) {
|
||||
code = el.id.replace("_notifyCreation", "");
|
||||
notifyType = "notify-creation";
|
||||
}
|
||||
send[code] = {};
|
||||
send[code][notifyType] = (el as HTMLInputElement).checked;
|
||||
_post("/invites/notify", send, function (): void {
|
||||
if (this.readyState == 4 && this.status != 200) {
|
||||
(el as HTMLInputElement).checked = !(el as HTMLInputElement).checked;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateInvite(invite: Invite): void {
|
||||
document.getElementById(invite.code + "_expiry").textContent = invite.expiresIn;
|
||||
const remainingUses: any = document.getElementById(CSS.escape(invite.code) + "_remainingUses");
|
||||
if (remainingUses) {
|
||||
remainingUses.textContent = `Remaining uses: ${invite.remainingUses}`;
|
||||
}
|
||||
document.getElementById(CSS.escape(invite.code) + "_usersCreated").innerHTML = genUsedBy(invite.usedBy);
|
||||
}
|
||||
|
||||
// delete invite from DOM
|
||||
const hideInvite = (code: string): void => document.getElementById(CSS.escape(code)).remove();
|
||||
|
||||
// delete invite from jfa-go
|
||||
window.deleteInvite = (code: string): void => _delete("/invites", { "code": code }, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
generateInvites();
|
||||
}
|
||||
});
|
||||
|
||||
export function generateInvites(empty?: boolean): void {
|
||||
if (empty) {
|
||||
document.getElementById('invites').textContent = '';
|
||||
addItem(emptyInvite());
|
||||
return;
|
||||
}
|
||||
_get("/invites", null, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
let data = this.response;
|
||||
window.availableProfiles = data['profiles'];
|
||||
const Profiles = document.getElementById('inviteProfile') as HTMLSelectElement;
|
||||
let innerHTML = "";
|
||||
for (let i = 0; i < window.availableProfiles.length; i++) {
|
||||
const profile = window.availableProfiles[i];
|
||||
innerHTML += `
|
||||
<option value="${profile}" ${(i == 0) ? "selected" : ""}>${profile}</option>
|
||||
`;
|
||||
}
|
||||
innerHTML += `
|
||||
<option value="NoProfile" ${(window.availableProfiles.length == 0) ? "selected" : ""}>No Profile</option>
|
||||
`;
|
||||
Profiles.innerHTML = innerHTML;
|
||||
if (data['invites'] == null || data['invites'].length == 0) {
|
||||
document.getElementById('invites').textContent = '';
|
||||
addItem(emptyInvite());
|
||||
return;
|
||||
}
|
||||
let items = document.getElementById('invites').children;
|
||||
for (const i in data['invites']) {
|
||||
let match = false;
|
||||
const inv = parseInvite(data['invites'][i]);
|
||||
for (const x in items) {
|
||||
if (items[x].id == inv.code) {
|
||||
match = true;
|
||||
updateInvite(inv);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!match) {
|
||||
addItem(inv);
|
||||
}
|
||||
}
|
||||
// second pass to check for expired invites
|
||||
items = document.getElementById('invites').children;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
let exists = false;
|
||||
for (const x in data['invites']) {
|
||||
if (items[i].id == data['invites'][x]['code']) {
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!exists) {
|
||||
hideInvite(items[i].id);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const addOptions = (length: number, el: HTMLSelectElement): void => {
|
||||
for (let v = 0; v <= length; v++) {
|
||||
const opt = document.createElement('option');
|
||||
opt.textContent = ""+v;
|
||||
opt.value = ""+v;
|
||||
el.appendChild(opt);
|
||||
}
|
||||
el.value = "0";
|
||||
};
|
||||
|
||||
export function checkDuration(): void {
|
||||
const boxVals: Array<number> = [+(document.getElementById("days") as HTMLSelectElement).value, +(document.getElementById("hours") as HTMLSelectElement).value, +(document.getElementById("minutes") as HTMLSelectElement).value];
|
||||
const submit = document.getElementById('generateSubmit') as HTMLButtonElement;
|
||||
if (boxVals.reduce((a: number, b: number): number => a + b) == 0) {
|
||||
submit.disabled = true;
|
||||
} else {
|
||||
submit.disabled = false;
|
||||
}
|
||||
}
|
||||
164
ts/modules/settings.ts
Normal file
164
ts/modules/settings.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { _get, _post, _delete, rmAttr, addAttr } from "../modules/common.js";
|
||||
import { Focus, Unfocus } from "../modules/admin.js";
|
||||
|
||||
interface Profile {
|
||||
Admin: boolean;
|
||||
LibraryAccess: string;
|
||||
FromUser: string;
|
||||
}
|
||||
|
||||
export const populateProfiles = (noTable?: boolean): void => _get("/profiles", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
const profileList = document.getElementById('profileList');
|
||||
profileList.textContent = '';
|
||||
window.availableProfiles = [this.response["default_profile"]];
|
||||
for (let name in this.response["profiles"]) {
|
||||
if (name != window.availableProfiles[0]) {
|
||||
window.availableProfiles.push(name);
|
||||
}
|
||||
const reqProfile = this.response["profiles"][name];
|
||||
if (!noTable && name != "default_profile") {
|
||||
const profile: Profile = {
|
||||
Admin: reqProfile["admin"],
|
||||
LibraryAccess: reqProfile["libraries"],
|
||||
FromUser: reqProfile["fromUser"]
|
||||
};
|
||||
profileList.innerHTML += `
|
||||
<td nowrap="nowrap" class="align-middle"><strong>${name}</strong></td>
|
||||
<td nowrap="nowrap" class="align-middle"><input class="${window.bs5 ? "form-check-input" : ""}" type="radio" name="defaultProfile" onclick="setDefaultProfile('${name}')" ${(name == window.availableProfiles[0]) ? "checked" : ""}></td>
|
||||
<td nowrap="nowrap" class="align-middle">${profile.FromUser}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${profile.Admin ? "Yes" : "No"}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${profile.LibraryAccess}</td>
|
||||
<td nowrap="nowrap" class="align-middle"><button class="btn btn-outline-danger" id="defaultProfile_${name}" onclick="deleteProfile('${name}')">Delete</button></td>
|
||||
`;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const openSettings = (settingsList: HTMLElement, settingsContent: HTMLElement, callback?: () => void): void => _get("/config", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
settingsList.textContent = '';
|
||||
window.config = this.response;
|
||||
for (const i in window.config["order"]) {
|
||||
const section: string = window.config["order"][i]
|
||||
const sectionCollapse = document.createElement('div') as HTMLDivElement;
|
||||
Unfocus(sectionCollapse);
|
||||
sectionCollapse.id = section;
|
||||
|
||||
const title: string = window.config[section]["meta"]["name"];
|
||||
const description: string = window.config[section]["meta"]["description"];
|
||||
const entryListID: string = `${section}_entryList`;
|
||||
// const footerID: string = `${section}_footer`;
|
||||
|
||||
sectionCollapse.innerHTML = `
|
||||
<div class="card card-body">
|
||||
<small class="text-muted">${description}</small>
|
||||
<div class="${entryListID}">
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
for (const x in config[section]["order"]) {
|
||||
const entry: string = config[section]["order"][x];
|
||||
if (entry == "meta") {
|
||||
continue;
|
||||
}
|
||||
let entryName: string = window.config[section][entry]["name"];
|
||||
let required = false;
|
||||
if (window.config[section][entry]["required"]) {
|
||||
entryName += ` <sup class="text-danger">*</sup>`;
|
||||
required = true;
|
||||
}
|
||||
if (window.config[section][entry]["requires_restart"]) {
|
||||
entryName += ` <sup class="text-danger">R</sup>`;
|
||||
}
|
||||
if ("description" in window.config[section][entry]) {
|
||||
entryName +=`
|
||||
<a class="text-muted" href="#" data-toggle="tooltip" data-placement="right" title="${window.config[section][entry]['description']}"><i class="fa fa-question-circle-o"></i></a>
|
||||
`;
|
||||
}
|
||||
const entryValue: boolean | string = window.config[section][entry]["value"];
|
||||
const entryType: string = window.config[section][entry]["type"];
|
||||
const entryGroup = document.createElement('div');
|
||||
if (entryType == "bool") {
|
||||
entryGroup.classList.add("form-check");
|
||||
entryGroup.innerHTML = `
|
||||
<input class="form-check-input" type="checkbox" value="" id="${section}_${entry}" ${(entryValue as boolean) ? 'checked': ''} ${required ? 'required' : ''}>
|
||||
<label class="form-check-label" for="${section}_${entry}">${entryName}</label>
|
||||
`;
|
||||
(entryGroup.querySelector('input[type=checkbox]') as HTMLInputElement).onclick = function (): void {
|
||||
const me = this as HTMLInputElement;
|
||||
for (const y in window.config["order"]) {
|
||||
const sect: string = window.config["order"][y];
|
||||
for (const z in window.config[sect]["order"]) {
|
||||
const ent: string = window.config[sect]["order"][z];
|
||||
if (`${sect}_${window.config[sect][ent]['depends_true']}` == me.id) {
|
||||
(document.getElementById(`${sect}_${ent}`) as HTMLInputElement).disabled = !(me.checked);
|
||||
} else if (`${sect}_${window.config[sect][ent]['depends_false']}` == me.id) {
|
||||
(document.getElementById(`${sect}_${ent}`) as HTMLInputElement).disabled = me.checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
} else if ((entryType == 'text') || (entryType == 'email') || (entryType == 'password') || (entryType == 'number')) {
|
||||
entryGroup.classList.add("form-group");
|
||||
entryGroup.innerHTML = `
|
||||
<label for="${section}_${entry}">${entryName}</label>
|
||||
<input type="${entryType}" class="form-control" id="${section}_${entry}" aria-describedby="${entry}" value="${entryValue}" ${required ? 'required' : ''}>
|
||||
`;
|
||||
} else if (entryType == 'select') {
|
||||
entryGroup.classList.add("form-group");
|
||||
const entryOptions: Array<string> = window.config[section][entry]["options"];
|
||||
let innerGroup = `
|
||||
<label for="${section}_${entry}">${entryName}</label>
|
||||
<select class="form-control" id="${section}_${entry}" ${required ? 'required' : ''}>
|
||||
`;
|
||||
for (const z in entryOptions) {
|
||||
const entryOption = entryOptions[z];
|
||||
let selected: boolean = (entryOption == entryValue);
|
||||
innerGroup += `
|
||||
<option value="${entryOption}" ${selected ? 'selected' : ''}>${entryOption}</option>
|
||||
`;
|
||||
}
|
||||
innerGroup += `</select>`;
|
||||
entryGroup.innerHTML = innerGroup;
|
||||
}
|
||||
sectionCollapse.getElementsByClassName(entryListID)[0].appendChild(entryGroup);
|
||||
}
|
||||
|
||||
settingsList.innerHTML += `
|
||||
<button type="button" class="list-group-item list-group-item-action" id="${section}_button" onclick="showSetting('${section}')">${title}</button>
|
||||
`;
|
||||
settingsContent.appendChild(sectionCollapse);
|
||||
}
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export function showSetting(id: string, runBefore?: () => void): void {
|
||||
const els = document.getElementById('settingsLeft').querySelectorAll("button[type=button]:not(.static)") as NodeListOf<HTMLButtonElement>;
|
||||
for (let i = 0; i < els.length; i++) {
|
||||
const el = els[i];
|
||||
if (el.id != `${id}_button`) {
|
||||
rmAttr(el, "active");
|
||||
}
|
||||
const sectEl = document.getElementById(el.id.replace("_button", ""));
|
||||
if (sectEl.id != id) {
|
||||
Unfocus(sectEl);
|
||||
}
|
||||
}
|
||||
addAttr(document.getElementById(`${id}_button`), "active");
|
||||
const section = document.getElementById(id);
|
||||
if (runBefore) {
|
||||
runBefore();
|
||||
}
|
||||
Focus(section);
|
||||
if (screen.width <= 1100) {
|
||||
// ugly
|
||||
setTimeout((): void => section.scrollIntoView(<ScrollIntoViewOptions>{ block: "center", behavior: "smooth" }), 200);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
const ombiDefaultsModal = createModal('ombiDefaults');
|
||||
import { _get, _post, _delete, rmAttr, addAttr } from "./modules/common.js";
|
||||
|
||||
const ombiDefaultsModal = window.BS.newModal('ombiDefaults');
|
||||
|
||||
(document.getElementById('openOmbiDefaults') as HTMLButtonElement).onclick = function (): void {
|
||||
let button = this as HTMLButtonElement;
|
||||
button.disabled = true;
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
function serializeForm(id: string): Object {
|
||||
const form = document.getElementById(id) as HTMLFormElement;
|
||||
let formData = {};
|
||||
for (let i = 0; i < form.elements.length; i++) {
|
||||
const el = form.elements[i];
|
||||
if ((el as HTMLInputElement).type == "submit") {
|
||||
continue;
|
||||
}
|
||||
let name = (el as HTMLInputElement).name;
|
||||
if (!name) {
|
||||
name = el.id;
|
||||
}
|
||||
switch ((el as HTMLInputElement).type) {
|
||||
case "checkbox":
|
||||
formData[name] = (el as HTMLInputElement).checked;
|
||||
break;
|
||||
case "text":
|
||||
case "password":
|
||||
case "email":
|
||||
case "number":
|
||||
formData[name] = (el as HTMLInputElement).value;
|
||||
break;
|
||||
case "select-one":
|
||||
case "select":
|
||||
let val: string = (el as HTMLSelectElement).value.toString();
|
||||
if (!isNaN(val as any)) {
|
||||
formData[name] = +val;
|
||||
} else {
|
||||
formData[name] = val;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return formData;
|
||||
}
|
||||
228
ts/settings.ts
228
ts/settings.ts
@@ -1,9 +1,28 @@
|
||||
var config: Object = {};
|
||||
var modifiedConfig: Object = {};
|
||||
import { _post, _get, _delete, rmAttr, addAttr } from "./modules/common.js";
|
||||
import { generateInvites } from "./modules/invites.js";
|
||||
import { populateRadios } from "./modules/accounts.js";
|
||||
import { Focus, Unfocus } from "./modules/admin.js";
|
||||
import { showSetting, populateProfiles } from "./modules/settings.js";
|
||||
|
||||
interface aWindow extends Window {
|
||||
setDefaultProfile(name: string): void;
|
||||
deleteProfile(name: string): void;
|
||||
createProfile(): void;
|
||||
showSetting(id: string, runBefore?: () => void): void;
|
||||
config: Object;
|
||||
modifiedConfig: Object;
|
||||
}
|
||||
|
||||
declare var window: aWindow;
|
||||
|
||||
window.config = {};
|
||||
window.modifiedConfig = {};
|
||||
|
||||
window.showSetting = showSetting;
|
||||
|
||||
function sendConfig(restart?: boolean): void {
|
||||
modifiedConfig["restart-program"] = restart;
|
||||
_post("/config", modifiedConfig, function (): void {
|
||||
window.modifiedConfig["restart-program"] = restart;
|
||||
_post("/config", window.modifiedConfig, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
const save = document.getElementById("settingsSave") as HTMLButtonElement
|
||||
if (this.status == 200 || this.status == 204) {
|
||||
@@ -19,159 +38,22 @@ function sendConfig(restart?: boolean): void {
|
||||
save.textContent = "Save";
|
||||
}
|
||||
if (restart) {
|
||||
refreshModal.show();
|
||||
window.Modals.refresh.show();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
(document.getElementById('openAbout') as HTMLButtonElement).onclick = (): void => {
|
||||
aboutModal.show();
|
||||
window.Modals.about.show();
|
||||
};
|
||||
|
||||
const openSettings = (settingsList: HTMLElement, settingsContent: HTMLElement, callback?: () => void): void => _get("/config", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
settingsList.textContent = '';
|
||||
config = this.response;
|
||||
for (const i in config["order"]) {
|
||||
const section: string = config["order"][i]
|
||||
const sectionCollapse = document.createElement('div') as HTMLDivElement;
|
||||
Unfocus(sectionCollapse);
|
||||
sectionCollapse.id = section;
|
||||
|
||||
const title: string = config[section]["meta"]["name"];
|
||||
const description: string = config[section]["meta"]["description"];
|
||||
const entryListID: string = `${section}_entryList`;
|
||||
// const footerID: string = `${section}_footer`;
|
||||
|
||||
sectionCollapse.innerHTML = `
|
||||
<div class="card card-body">
|
||||
<small class="text-muted">${description}</small>
|
||||
<div class="${entryListID}">
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
for (const x in config[section]["order"]) {
|
||||
const entry: string = config[section]["order"][x];
|
||||
if (entry == "meta") {
|
||||
continue;
|
||||
}
|
||||
let entryName: string = config[section][entry]["name"];
|
||||
let required = false;
|
||||
if (config[section][entry]["required"]) {
|
||||
entryName += ` <sup class="text-danger">*</sup>`;
|
||||
required = true;
|
||||
}
|
||||
if (config[section][entry]["requires_restart"]) {
|
||||
entryName += ` <sup class="text-danger">R</sup>`;
|
||||
}
|
||||
if ("description" in config[section][entry]) {
|
||||
entryName +=`
|
||||
<a class="text-muted" href="#" data-toggle="tooltip" data-placement="right" title="${config[section][entry]['description']}"><i class="fa fa-question-circle-o"></i></a>
|
||||
`;
|
||||
}
|
||||
const entryValue: boolean | string = config[section][entry]["value"];
|
||||
const entryType: string = config[section][entry]["type"];
|
||||
const entryGroup = document.createElement('div');
|
||||
if (entryType == "bool") {
|
||||
entryGroup.classList.add("form-check");
|
||||
entryGroup.innerHTML = `
|
||||
<input class="form-check-input" type="checkbox" value="" id="${section}_${entry}" ${(entryValue as boolean) ? 'checked': ''} ${required ? 'required' : ''}>
|
||||
<label class="form-check-label" for="${section}_${entry}">${entryName}</label>
|
||||
`;
|
||||
(entryGroup.querySelector('input[type=checkbox]') as HTMLInputElement).onclick = function (): void {
|
||||
const me = this as HTMLInputElement;
|
||||
for (const y in config["order"]) {
|
||||
const sect: string = config["order"][y];
|
||||
for (const z in config[sect]["order"]) {
|
||||
const ent: string = config[sect]["order"][z];
|
||||
if (`${sect}_${config[sect][ent]['depends_true']}` == me.id) {
|
||||
(document.getElementById(`${sect}_${ent}`) as HTMLInputElement).disabled = !(me.checked);
|
||||
} else if (`${sect}_${config[sect][ent]['depends_false']}` == me.id) {
|
||||
(document.getElementById(`${sect}_${ent}`) as HTMLInputElement).disabled = me.checked;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
} else if ((entryType == 'text') || (entryType == 'email') || (entryType == 'password') || (entryType == 'number')) {
|
||||
entryGroup.classList.add("form-group");
|
||||
entryGroup.innerHTML = `
|
||||
<label for="${section}_${entry}">${entryName}</label>
|
||||
<input type="${entryType}" class="form-control" id="${section}_${entry}" aria-describedby="${entry}" value="${entryValue}" ${required ? 'required' : ''}>
|
||||
`;
|
||||
} else if (entryType == 'select') {
|
||||
entryGroup.classList.add("form-group");
|
||||
const entryOptions: Array<string> = config[section][entry]["options"];
|
||||
let innerGroup = `
|
||||
<label for="${section}_${entry}">${entryName}</label>
|
||||
<select class="form-control" id="${section}_${entry}" ${required ? 'required' : ''}>
|
||||
`;
|
||||
for (const z in entryOptions) {
|
||||
const entryOption = entryOptions[z];
|
||||
let selected: boolean = (entryOption == entryValue);
|
||||
innerGroup += `
|
||||
<option value="${entryOption}" ${selected ? 'selected' : ''}>${entryOption}</option>
|
||||
`;
|
||||
}
|
||||
innerGroup += `</select>`;
|
||||
entryGroup.innerHTML = innerGroup;
|
||||
}
|
||||
sectionCollapse.getElementsByClassName(entryListID)[0].appendChild(entryGroup);
|
||||
}
|
||||
|
||||
settingsList.innerHTML += `
|
||||
<button type="button" class="list-group-item list-group-item-action" id="${section}_button" onclick="showSetting('${section}')">${title}</button>
|
||||
`;
|
||||
settingsContent.appendChild(sectionCollapse);
|
||||
}
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
interface Profile {
|
||||
Admin: boolean;
|
||||
LibraryAccess: string;
|
||||
FromUser: string;
|
||||
}
|
||||
|
||||
(document.getElementById('profiles_button') as HTMLButtonElement).onclick = (): void => showSetting("profiles", populateProfiles);
|
||||
|
||||
const populateProfiles = (noTable?: boolean): void => _get("/profiles", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
const profileList = document.getElementById('profileList');
|
||||
profileList.textContent = '';
|
||||
availableProfiles = [this.response["default_profile"]];
|
||||
for (let name in this.response["profiles"]) {
|
||||
if (name != availableProfiles[0]) {
|
||||
availableProfiles.push(name);
|
||||
}
|
||||
const reqProfile = this.response["profiles"][name];
|
||||
if (!noTable && name != "default_profile") {
|
||||
const profile: Profile = {
|
||||
Admin: reqProfile["admin"],
|
||||
LibraryAccess: reqProfile["libraries"],
|
||||
FromUser: reqProfile["fromUser"]
|
||||
};
|
||||
profileList.innerHTML += `
|
||||
<td nowrap="nowrap" class="align-middle"><strong>${name}</strong></td>
|
||||
<td nowrap="nowrap" class="align-middle"><input class="${(bsVersion == 5) ? "form-check-input" : ""}" type="radio" name="defaultProfile" onclick="setDefaultProfile('${name}')" ${(name == availableProfiles[0]) ? "checked" : ""}></td>
|
||||
<td nowrap="nowrap" class="align-middle">${profile.FromUser}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${profile.Admin ? "Yes" : "No"}</td>
|
||||
<td nowrap="nowrap" class="align-middle">${profile.LibraryAccess}</td>
|
||||
<td nowrap="nowrap" class="align-middle"><button class="btn btn-outline-danger" id="defaultProfile_${name}" onclick="deleteProfile('${name}')">Delete</button></td>
|
||||
`;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const setDefaultProfile = (name: string): void => _post("/profiles/default", { "name": name }, function (): void {
|
||||
window.setDefaultProfile = (name: string): void => _post("/profiles/default", { "name": name }, function (): void {
|
||||
if (this.readyState == 4) {
|
||||
if (this.status != 200) {
|
||||
(document.getElementById(`defaultProfile_${availableProfiles[0]}`) as HTMLInputElement).checked = true;
|
||||
(document.getElementById(`defaultProfile_${window.availableProfiles[0]}`) as HTMLInputElement).checked = true;
|
||||
(document.getElementById(`defaultProfile_${name}`) as HTMLInputElement).checked = false;
|
||||
} else {
|
||||
generateInvites();
|
||||
@@ -179,7 +61,7 @@ const setDefaultProfile = (name: string): void => _post("/profiles/default", { "
|
||||
}
|
||||
});
|
||||
|
||||
const deleteProfile = (name: string): void => _delete("/profiles", { "name": name }, function (): void {
|
||||
window.deleteProfile = (name: string): void => _delete("/profiles", { "name": name }, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
populateProfiles();
|
||||
}
|
||||
@@ -187,7 +69,7 @@ const deleteProfile = (name: string): void => _delete("/profiles", { "name": nam
|
||||
|
||||
const createProfile = (): void => _get("/users", null, function (): void {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
jfUsers = this.response["users"];
|
||||
window.jfUsers = this.response["users"];
|
||||
populateRadios();
|
||||
const submitButton = document.getElementById('storeDefaults') as HTMLButtonElement;
|
||||
submitButton.disabled = false;
|
||||
@@ -205,10 +87,12 @@ const createProfile = (): void => _get("/users", null, function (): void {
|
||||
Focus(document.getElementById('newProfileBox'));
|
||||
(document.getElementById('newProfileName') as HTMLInputElement).value = '';
|
||||
Focus(document.getElementById('defaultUserRadiosBox'));
|
||||
userDefaultsModal.show();
|
||||
window.Modals.userDefaults.show();
|
||||
}
|
||||
});
|
||||
|
||||
window.createProfile = createProfile;
|
||||
|
||||
function storeProfile(): void {
|
||||
this.disabled = true;
|
||||
this.innerHTML =
|
||||
@@ -239,7 +123,7 @@ function storeProfile(): void {
|
||||
addAttr(button, "btn-primary");
|
||||
rmAttr(button, "btn-success");
|
||||
button.disabled = false;
|
||||
userDefaultsModal.hide();
|
||||
window.Modals.userDefaults.hide();
|
||||
|
||||
}, 1000);
|
||||
populateProfiles();
|
||||
@@ -265,41 +149,17 @@ function storeProfile(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function showSetting(id: string, runBefore?: () => void): void {
|
||||
const els = document.getElementById('settingsLeft').querySelectorAll("button[type=button]:not(.static)") as NodeListOf<HTMLButtonElement>;
|
||||
for (let i = 0; i < els.length; i++) {
|
||||
const el = els[i];
|
||||
if (el.id != `${id}_button`) {
|
||||
rmAttr(el, "active");
|
||||
}
|
||||
const sectEl = document.getElementById(el.id.replace("_button", ""));
|
||||
if (sectEl.id != id) {
|
||||
Unfocus(sectEl);
|
||||
}
|
||||
}
|
||||
addAttr(document.getElementById(`${id}_button`), "active");
|
||||
const section = document.getElementById(id);
|
||||
if (runBefore) {
|
||||
runBefore();
|
||||
}
|
||||
Focus(section);
|
||||
if (screen.width <= 1100) {
|
||||
// ugly
|
||||
setTimeout((): void => section.scrollIntoView(<ScrollIntoViewOptions>{ block: "center", behavior: "smooth" }), 200);
|
||||
}
|
||||
}
|
||||
|
||||
// (document.getElementById('openSettings') as HTMLButtonElement).onclick = (): void => openSettings(document.getElementById('settingsList'), document.getElementById('settingsList'), (): void => settingsModal.show());
|
||||
|
||||
(document.getElementById('settingsSave') as HTMLButtonElement).onclick = function (): void {
|
||||
modifiedConfig = {};
|
||||
window.modifiedConfig = {};
|
||||
const save = this as HTMLButtonElement;
|
||||
let restartSettingsChanged = false;
|
||||
let settingsChanged = false;
|
||||
for (const i in config["order"]) {
|
||||
const section = config["order"][i];
|
||||
for (const x in config[section]["order"]) {
|
||||
const entry = config[section]["order"][x];
|
||||
for (const i in window.config["order"]) {
|
||||
const section = window.config["order"][i];
|
||||
for (const x in window.config[section]["order"]) {
|
||||
const entry = window.config[section]["order"][x];
|
||||
if (entry == "meta") {
|
||||
continue;
|
||||
}
|
||||
@@ -311,13 +171,13 @@ function showSetting(id: string, runBefore?: () => void): void {
|
||||
} else {
|
||||
val = el.value.toString();
|
||||
}
|
||||
if (val != config[section][entry]["value"].toString()) {
|
||||
if (!(section in modifiedConfig)) {
|
||||
modifiedConfig[section] = {};
|
||||
if (val != window.config[section][entry]["value"].toString()) {
|
||||
if (!(section in window.modifiedConfig)) {
|
||||
window.modifiedConfig[section] = {};
|
||||
}
|
||||
modifiedConfig[section][entry] = val;
|
||||
window.modifiedConfig[section][entry] = val;
|
||||
settingsChanged = true;
|
||||
if (config[section][entry]["requires_restart"]) {
|
||||
if (window.config[section][entry]["requires_restart"]) {
|
||||
restartSettingsChanged = true;
|
||||
}
|
||||
}
|
||||
@@ -333,7 +193,7 @@ function showSetting(id: string, runBefore?: () => void): void {
|
||||
if (restartButton) {
|
||||
restartButton.onclick = (): void => sendConfig(true);
|
||||
}
|
||||
restartModal.show();
|
||||
window.Modals.restart.show();
|
||||
} else if (settingsChanged) {
|
||||
save.innerHTML = spinnerHTML;
|
||||
sendConfig();
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"outDir": "../data/static",
|
||||
"target": "es6",
|
||||
"lib": ["dom", "es2017"],
|
||||
"types": ["jquery"]
|
||||
"typeRoots": ["./node_modules/@types", "./typings"]
|
||||
}
|
||||
}
|
||||
|
||||
61
ts/typings/d.ts
Normal file
61
ts/typings/d.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
declare interface ModalConstructor {
|
||||
(id: string, find?: boolean): BSModal;
|
||||
}
|
||||
|
||||
declare interface BSModal {
|
||||
el: HTMLDivElement;
|
||||
modal: any;
|
||||
show: () => void;
|
||||
hide: () => void;
|
||||
}
|
||||
|
||||
declare interface Window {
|
||||
getComputedStyle(element: HTMLElement, pseudoElt: HTMLElement): any;
|
||||
bsVersion: number;
|
||||
bs5: boolean;
|
||||
BS: Bootstrap;
|
||||
Modals: BSModals;
|
||||
cssFile: string;
|
||||
availableProfiles: Array<any>;
|
||||
jfUsers: Array<Object>;
|
||||
notifications_enabled: boolean;
|
||||
token: string;
|
||||
buttonWidth: number;
|
||||
}
|
||||
|
||||
declare interface tooltipTrigger {
|
||||
(): void;
|
||||
}
|
||||
|
||||
declare interface Bootstrap {
|
||||
newModal: ModalConstructor;
|
||||
triggerTooltips: tooltipTrigger;
|
||||
Compat?(): void;
|
||||
}
|
||||
|
||||
declare interface BSModals {
|
||||
login: BSModal;
|
||||
userDefaults: BSModal;
|
||||
users: BSModal;
|
||||
restart: BSModal;
|
||||
refresh: BSModal;
|
||||
about: BSModal;
|
||||
delete: BSModal;
|
||||
newUser: BSModal;
|
||||
}
|
||||
|
||||
interface Invite {
|
||||
code?: string;
|
||||
expiresIn?: string;
|
||||
empty: boolean;
|
||||
remainingUses?: string;
|
||||
email?: string;
|
||||
usedBy?: Array<Array<string>>;
|
||||
created?: string;
|
||||
notifyExpiry?: boolean;
|
||||
notifyCreation?: boolean;
|
||||
profile?: string;
|
||||
}
|
||||
|
||||
declare var config: Object;
|
||||
declare var modifiedConfig: Object;
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/usr/bin/bash
|
||||
set +e
|
||||
npx tsc -p ts/
|
||||
set -e
|
||||
13
views.go
13
views.go
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -30,8 +31,10 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
|
||||
// if app.checkInvite(code, false, "") {
|
||||
if _, ok := app.storage.invites[code]; ok {
|
||||
email := app.storage.invites[code].Email
|
||||
gc.HTML(http.StatusOK, "form.html", gin.H{
|
||||
"bs5": app.config.Section("ui").Key("bs5").MustBool(false),
|
||||
if strings.Contains(email, "Failed") {
|
||||
email = ""
|
||||
}
|
||||
gc.HTML(http.StatusOK, "form-loader.html", gin.H{
|
||||
"cssFile": app.cssFile,
|
||||
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
|
||||
"helpMessage": app.config.Section("ui").Key("help_message").String(),
|
||||
@@ -40,7 +43,11 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
|
||||
"validate": app.config.Section("password_validation").Key("enabled").MustBool(false),
|
||||
"requirements": app.validator.getCriteria(),
|
||||
"email": email,
|
||||
"username": !app.config.Section("email").Key("no_username").MustBool(false),
|
||||
"settings": map[string]bool{
|
||||
"bs5": app.config.Section("ui").Key("bs5").MustBool(false),
|
||||
"username": !app.config.Section("email").Key("no_username").MustBool(false),
|
||||
},
|
||||
"lang": app.storage.lang.Form["strings"],
|
||||
})
|
||||
} else {
|
||||
gc.HTML(404, "invalidCode.html", gin.H{
|
||||
|
||||
Reference in New Issue
Block a user