Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 38127948bd | |||
| 2087cf2c03 | |||
| bb9fe550ad | |||
| 0139b08aae | |||
| 9d18f9d0dc | |||
| 329ac71785 | |||
| 4f1b260334 | |||
| 832892fa41 | |||
| 069d32d4af | |||
| 5c19fbe187 |
@@ -7,6 +7,7 @@
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
ikinuki-server
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package client_api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Describe struct {
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon"`
|
||||
}
|
||||
|
||||
func describeHandler(data_dir string, w http.ResponseWriter, r *http.Request) {
|
||||
log.Debugf("/describe called\n")
|
||||
return_json := Describe{
|
||||
Name: "mediasrv-server",
|
||||
Icon: "",
|
||||
}
|
||||
data, err := json.Marshal(return_json)
|
||||
if err != nil {
|
||||
log.Errorf("Could not marshal data: %v\n", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package client_api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.ohea.xyz/mediasrv/server/database"
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
var log = logging.MustGetLogger("mediasrv-server")
|
||||
|
||||
type Episodes struct {
|
||||
Episodes []database.Episode `json:"episodes"`
|
||||
}
|
||||
|
||||
func episodesHandler(data_dir string, w http.ResponseWriter, r *http.Request) {
|
||||
log.Debugf("/episodes called\n")
|
||||
db, _, err := database.OpenDatabase(data_dir)
|
||||
if err != nil {
|
||||
log.Errorf("Could not open database: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := db.Query("SELECT title, show_title, number, season, original_filename FROM episodes")
|
||||
if err != nil {
|
||||
log.Errorf("Could not check if database was new: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var return_json Episodes
|
||||
|
||||
for {
|
||||
if !rows.Next() {
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not get row from database: %v\n", err)
|
||||
return
|
||||
} else {
|
||||
log.Debugf("%v rows processed\n", len(return_json.Episodes))
|
||||
break
|
||||
}
|
||||
}
|
||||
var episode database.Episode
|
||||
rows.Scan(&episode.Title, &episode.ShowTitle, &episode.Episode, &episode.Season, &episode.OriginalFilename)
|
||||
|
||||
return_json.Episodes = append(return_json.Episodes, episode)
|
||||
}
|
||||
data, err := json.Marshal(return_json)
|
||||
if err != nil {
|
||||
log.Errorf("Could not marshal episode data: %v\n", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package client_api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type InProgress struct {
|
||||
Data []int `json:"data"`
|
||||
}
|
||||
|
||||
func inProgressHandler(data_dir string, w http.ResponseWriter, r *http.Request) {
|
||||
log.Debugf("/in_progress called\n")
|
||||
return_json := InProgress{
|
||||
Data: []int{1, 2, 3},
|
||||
}
|
||||
data, err := json.Marshal(return_json)
|
||||
if err != nil {
|
||||
log.Errorf("Could not marshal data: %v\n", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package client_api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type RecentlyAdded struct {
|
||||
Data []int `json:"data"`
|
||||
}
|
||||
|
||||
func recentlyAddedHandler(data_dir string, w http.ResponseWriter, r *http.Request) {
|
||||
log.Debugf("/recently_added called\n")
|
||||
return_json := RecentlyAdded{
|
||||
Data: []int{4, 5, 6},
|
||||
}
|
||||
data, err := json.Marshal(return_json)
|
||||
if err != nil {
|
||||
log.Errorf("Could not marshal data: %v\n", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package client_api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func SetupHTTPServer(mux *http.ServeMux, data_dir string) {
|
||||
mux.HandleFunc("/client/episodes", func(w http.ResponseWriter, r *http.Request) {
|
||||
episodesHandler(data_dir, w, r)
|
||||
})
|
||||
mux.HandleFunc("/client/shows", func(w http.ResponseWriter, r *http.Request) {
|
||||
showsHandler(data_dir, w, r)
|
||||
})
|
||||
mux.HandleFunc("/client/describe", func(w http.ResponseWriter, r *http.Request) {
|
||||
describeHandler(data_dir, w, r)
|
||||
})
|
||||
mux.HandleFunc("/client/recently_added", func(w http.ResponseWriter, r *http.Request) {
|
||||
recentlyAddedHandler(data_dir, w, r)
|
||||
})
|
||||
mux.HandleFunc("/client/in_progress", func(w http.ResponseWriter, r *http.Request) {
|
||||
inProgressHandler(data_dir, w, r)
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package client_api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.ohea.xyz/mediasrv/server/database"
|
||||
)
|
||||
|
||||
type TVShow struct {
|
||||
Id int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Year int `json:"year"`
|
||||
Description string `json:"description"`
|
||||
Poster string `json:"poster"`
|
||||
}
|
||||
|
||||
type Shows struct {
|
||||
Data []TVShow `json:"data"`
|
||||
}
|
||||
|
||||
func showsHandler(data_dir string, w http.ResponseWriter, r *http.Request) {
|
||||
log.Debugf("/shows called\n")
|
||||
db, _, err := database.OpenDatabase(data_dir)
|
||||
if err != nil {
|
||||
log.Errorf("Could not open database: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := db.Query("SELECT id, title, year, description, poster FROM tvshows")
|
||||
if err != nil {
|
||||
log.Errorf("Could not check if database was new: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var return_json Shows
|
||||
|
||||
for {
|
||||
if !rows.Next() {
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not get row from database: %v\n", err)
|
||||
return
|
||||
} else {
|
||||
log.Debugf("%v rows processed\n", len(return_json.Data))
|
||||
break
|
||||
}
|
||||
}
|
||||
var show TVShow
|
||||
rows.Scan(&show.Id, &show.Title, &show.Year, &show.Description, &show.Poster)
|
||||
|
||||
return_json.Data = append(return_json.Data, show)
|
||||
}
|
||||
data, err := json.Marshal(return_json)
|
||||
if err != nil {
|
||||
log.Errorf("Could not marshal episode data: %v\n", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
var log = logging.MustGetLogger("mediasrv-server")
|
||||
|
||||
func OpenDatabase(data_dir string) (*sql.DB, bool, error) {
|
||||
// create data directory
|
||||
err := os.MkdirAll(data_dir, 0755)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("Could not create data directory: %v", err)
|
||||
}
|
||||
|
||||
// open database
|
||||
db_path := filepath.Join(data_dir, "server.db")
|
||||
|
||||
db, err := sql.Open("sqlite3", db_path)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("Could not open database: %v", err)
|
||||
}
|
||||
|
||||
// check if the database is new
|
||||
is_db_new := `SELECT CASE WHEN EXISTS(SELECT 1 FROM sqlite_master) THEN 0 ELSE 1 END AS IsEmpty;`
|
||||
|
||||
// initalize database
|
||||
db_init := `
|
||||
CREATE TABLE tvshows(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT,
|
||||
original_title TEXT,
|
||||
show_title TEXT,
|
||||
year INTEGER,
|
||||
description TEXT,
|
||||
poster TEXT
|
||||
);
|
||||
CREATE TABLE episodes(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT,
|
||||
show_title TEXT,
|
||||
number INTEGER,
|
||||
season INTEGER,
|
||||
original_filename TEXT
|
||||
);
|
||||
`
|
||||
|
||||
// transaction new check isn't racy
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("Could not begin db transaction: %v", err)
|
||||
}
|
||||
defer tx.Commit()
|
||||
|
||||
// check if the database is new
|
||||
rows, err := tx.Query(is_db_new)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("Could not check if database was new: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
rows.Next()
|
||||
var isEmpty int
|
||||
rows.Scan(&isEmpty)
|
||||
|
||||
// if the sqlite_master table is empty (the databse is newly created)
|
||||
if isEmpty == 1 {
|
||||
log.Infof("Creating new database at %v\n", db_path)
|
||||
// initalize database
|
||||
_, err = tx.Exec(db_init)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("Could not initalize database: %v", err)
|
||||
}
|
||||
return db, true, nil
|
||||
} else {
|
||||
log.Infof("Existing database found at %v", db_path)
|
||||
return db, false, nil
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type TVShow struct {
|
||||
XMLName xml.Name `xml:"tvshow" json:"-"`
|
||||
Title string `xml:"title"`
|
||||
OriginalTile string `xml:"originaltitle"`
|
||||
ShowTitle string `xml:"showtitle"`
|
||||
Year int `xml:"year"`
|
||||
Description string `xml:"plot"`
|
||||
Thumb []Thumb `xml:"thumb"`
|
||||
}
|
||||
|
||||
type Thumb struct {
|
||||
Aspect string `xml:"aspect,attr"`
|
||||
Season string `xml:"season,attr"`
|
||||
Type string `xml:"type,attr"`
|
||||
Value string `xml:",chardata"`
|
||||
}
|
||||
|
||||
func ScanTvshowRoot(root string, db *sql.DB) error {
|
||||
log.Noticef("Scanning directory root %v", root)
|
||||
|
||||
files, err := ioutil.ReadDir(root)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not get files in directory \"%v\": %v", root, err)
|
||||
}
|
||||
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not begin db transaction: %v", err)
|
||||
}
|
||||
defer tx.Commit()
|
||||
|
||||
stmt, err := tx.Prepare("insert into tvshows(title, original_title, show_title, year, description, poster) values(?, ?, ?, ?, ?, ?)")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not prepare statement: %v", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
show_path := filepath.Join(root, file.Name())
|
||||
if insert_tvshow_nfo(show_path, stmt) {
|
||||
err = scan_tvshow_episodes(show_path, tx)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Could not scan for episodes in %v: %v", show_path, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insert_tvshow_nfo(show_dir string, stmt *sql.Stmt) bool {
|
||||
tvshow_nfo_path := filepath.Join(show_dir, "tvshow.nfo")
|
||||
|
||||
tvshow_nfo_file, err := os.OpenFile(tvshow_nfo_path, os.O_RDONLY, 0755)
|
||||
if err != nil {
|
||||
log.Debugf("Could not open tvshow.nfo file in \"%v\"\n", show_dir)
|
||||
return false
|
||||
}
|
||||
defer tvshow_nfo_file.Close()
|
||||
|
||||
// try to parse nfo file
|
||||
data, err := ioutil.ReadAll(tvshow_nfo_file)
|
||||
if err != nil {
|
||||
log.Debugf("Could not read data from tvshow.nfo file: %v\n", err)
|
||||
return false
|
||||
}
|
||||
var tvshow TVShow
|
||||
|
||||
err = xml.Unmarshal(data, &tvshow)
|
||||
if err != nil {
|
||||
log.Debugf("Could not parse tvshow.nfo file contents: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// TODO: Replace with print formatting logic
|
||||
log.Debugf("%v (%v):\n", tvshow.Title, tvshow.Year)
|
||||
log.Debugf(" Original Title: %v\n", tvshow.OriginalTile)
|
||||
log.Debugf(" Show Title: %v\n", tvshow.ShowTitle)
|
||||
|
||||
_, err = stmt.Exec(tvshow.Title, tvshow.OriginalTile, tvshow.ShowTitle, tvshow.Year, tvshow.Description, tvshow.Thumb[0].Value)
|
||||
if err != nil {
|
||||
log.Debugf("Could not insert tvshow \"%v\" into database: %v\n", tvshow.Title, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type Episode struct {
|
||||
XMLName xml.Name `xml:"episodedetails" json:"-"`
|
||||
Title string `xml:"title"`
|
||||
ShowTitle string `xml:"showtitle"`
|
||||
Season int `xml:"season"`
|
||||
Episode int `xml:"episode"`
|
||||
OriginalFilename string `xml:"original_filename"`
|
||||
}
|
||||
|
||||
func scan_tvshow_episodes(show_dir string, tx *sql.Tx) error {
|
||||
|
||||
log.Infof("Scanning episodes for show %v\n", show_dir)
|
||||
|
||||
files, err := ioutil.ReadDir(show_dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not enumerate files in folder: %v", err)
|
||||
}
|
||||
|
||||
num_episodes := 0
|
||||
|
||||
stmt, err := tx.Prepare("insert into episodes(title, show_title, number, season, original_filename) values(?, ?, ?, ?, ?)")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not prepare statement: %v", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for _, file := range files {
|
||||
ext := filepath.Ext(file.Name())
|
||||
nfo_path := filepath.Join(show_dir, file.Name())
|
||||
|
||||
if file.Name() == "tvshow.nfo" {
|
||||
continue
|
||||
} else if ext == ".nfo" {
|
||||
log.Debugf("Found nfo file: \"%v\"\n", file.Name())
|
||||
} else {
|
||||
log.Debugf("Skipping file \"%v\", not an nfo file\n", file.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
log.Debugf("%v\n", file.Name())
|
||||
|
||||
nfo_file, err := os.OpenFile(nfo_path, os.O_RDONLY, 0755)
|
||||
if err != nil {
|
||||
log.Debugf("Could not open nfo file \"%v\": %v", nfo_path, err)
|
||||
continue
|
||||
}
|
||||
defer nfo_file.Close()
|
||||
|
||||
// try to parse nfo file
|
||||
data, err := ioutil.ReadAll(nfo_file)
|
||||
if err != nil {
|
||||
log.Debugf("Could not read data from nfo file \"%v\": %v\n", nfo_path, err)
|
||||
continue
|
||||
}
|
||||
var episode Episode
|
||||
|
||||
err = xml.Unmarshal(data, &episode)
|
||||
if err != nil {
|
||||
log.Debugf("Could not parse contents of nfo file \"%v\": %v\n", nfo_path, err)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Debugf(" Title: %v\n", episode.Title)
|
||||
log.Debugf(" Season %v\n", episode.Season)
|
||||
log.Debugf(" Episode %v\n", episode.Episode)
|
||||
log.Debugf(" Show: %v\n", episode.ShowTitle)
|
||||
log.Debugf(" Original Filename: %v\n", episode.OriginalFilename)
|
||||
|
||||
full_original_filename := filepath.Join(show_dir, episode.OriginalFilename)
|
||||
|
||||
_, err = stmt.Exec(episode.Title, episode.ShowTitle, episode.Episode, episode.Season, full_original_filename)
|
||||
if err != nil {
|
||||
log.Debugf("Could not insert episode %v of tvshow \"%v\" into database: %v\n", episode.Episode, episode.ShowTitle, err)
|
||||
continue
|
||||
}
|
||||
|
||||
num_episodes++
|
||||
|
||||
}
|
||||
|
||||
log.Infof("Found %v episodes\n", num_episodes)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package filesystem
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
var log = logging.MustGetLogger("mediasrv-server")
|
||||
|
||||
type File struct {
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type Dir struct {
|
||||
Path string `json:"path"`
|
||||
Name string `json:"name"`
|
||||
SubDirs []Dir `json:"subDirs,omitempty"`
|
||||
SubFiles []File `json:"subFiles,omitempty"`
|
||||
}
|
||||
|
||||
func printDir(d Dir, offset int) {
|
||||
for i := 0; i < offset; i++ {
|
||||
fmt.Print(" ")
|
||||
}
|
||||
fmt.Printf("%v\n", d.Name)
|
||||
for _, subFile := range d.SubFiles {
|
||||
for i := 0; i < offset+1; i++ {
|
||||
fmt.Print(" ")
|
||||
}
|
||||
fmt.Printf("%v\n", subFile.Name)
|
||||
}
|
||||
for _, subDir := range d.SubDirs {
|
||||
printDir(subDir, offset+1)
|
||||
}
|
||||
}
|
||||
|
||||
func GetFilesystem(dir string) (Dir, error) {
|
||||
|
||||
var err error
|
||||
|
||||
root := Dir{
|
||||
Path: dir,
|
||||
Name: filepath.Base(dir),
|
||||
}
|
||||
|
||||
currentDir := &root
|
||||
dirStack := make([]*Dir, 1000)
|
||||
subStack := make([][]fs.DirEntry, 1000)
|
||||
ind := 0
|
||||
|
||||
outer:
|
||||
for {
|
||||
var subDirs []fs.DirEntry
|
||||
if len(currentDir.SubDirs) > 0 {
|
||||
subDirs = subStack[ind]
|
||||
} else {
|
||||
subDirs, err = os.ReadDir(currentDir.Path)
|
||||
if err != nil {
|
||||
return Dir{}, err
|
||||
}
|
||||
}
|
||||
|
||||
for i, subDir := range subDirs {
|
||||
subPath := filepath.Join(currentDir.Path, subDir.Name())
|
||||
if subDir.IsDir() {
|
||||
dirStack[ind] = currentDir
|
||||
subStack[ind] = subDirs[i+1:]
|
||||
ind++
|
||||
newDir := Dir{
|
||||
Path: subPath,
|
||||
Name: subDir.Name(),
|
||||
}
|
||||
currentDir.SubDirs = append(currentDir.SubDirs, newDir)
|
||||
currentDir = ¤tDir.SubDirs[len(currentDir.SubDirs)-1]
|
||||
|
||||
continue outer
|
||||
} else {
|
||||
currentDir.SubFiles = append(currentDir.SubFiles, File{
|
||||
Path: subPath,
|
||||
Name: subDir.Name(),
|
||||
})
|
||||
}
|
||||
}
|
||||
if ind == 0 {
|
||||
break
|
||||
}
|
||||
ind--
|
||||
currentDir = dirStack[ind]
|
||||
}
|
||||
|
||||
//printDir(root, 0)
|
||||
|
||||
return root, nil
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
module github.com/restitux/ikinuki-server
|
||||
module git.ohea.xyz/mediasrv/server
|
||||
|
||||
go 1.18
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/mattn/go-sqlite3 v1.14.12
|
||||
github.com/pelletier/go-toml/v2 v2.0.0-beta.8
|
||||
git.ohea.xyz/golang/config v0.0.0-20221002005232-8a901413a8b0
|
||||
github.com/mattn/go-sqlite3 v1.14.16
|
||||
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
|
||||
)
|
||||
|
||||
require github.com/pelletier/go-toml/v2 v2.0.5 // indirect
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
git.ohea.xyz/golang/config v0.0.0-20221002005232-8a901413a8b0 h1:a8ygEuzmqFDxXmf+e1IseDKBcAtkaIwfL3k4PIVVVr8=
|
||||
git.ohea.xyz/golang/config v0.0.0-20221002005232-8a901413a8b0/go.mod h1:86PbXJ2WdqQ+3hYqrnv3ukgKNRK9nQfThnlY03FAO0g=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0=
|
||||
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/pelletier/go-toml/v2 v2.0.0-beta.8 h1:dy81yyLYJDwMTifq24Oi/IslOslRrDSb3jwDggjz3Z0=
|
||||
github.com/pelletier/go-toml/v2 v2.0.0-beta.8/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88=
|
||||
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
|
||||
github.com/pelletier/go-toml/v2 v2.0.5 h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg=
|
||||
github.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@@ -1,97 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/op/go-logging"
|
||||
|
||||
toml "github.com/pelletier/go-toml/v2"
|
||||
"git.ohea.xyz/golang/config"
|
||||
|
||||
"git.ohea.xyz/mediasrv/server/database"
|
||||
"git.ohea.xyz/mediasrv/server/rest"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Address string
|
||||
Port int
|
||||
ScanDirectory string
|
||||
//Age int
|
||||
//Cats []string
|
||||
//Pi float64
|
||||
//Perfection []int
|
||||
//DOB time.Time // requires `import time`
|
||||
}
|
||||
|
||||
func get_config_dir() string {
|
||||
// Find config directory
|
||||
|
||||
// Linux (XDG base directory specification compliant)
|
||||
xdg_config_home := os.Getenv("XDG_CONFIG_HOME")
|
||||
|
||||
if xdg_config_home != "" {
|
||||
return filepath.Join(xdg_config_home, "ikinuki")
|
||||
} else {
|
||||
home := os.Getenv("HOME")
|
||||
return filepath.Join(home, ".config", "ikinuki")
|
||||
}
|
||||
}
|
||||
|
||||
func get_config(config_dir string) (*Config, error) {
|
||||
config := Config{
|
||||
Address: "127.0.0.1",
|
||||
Port: 32520,
|
||||
ScanDirectory: "FILL IN",
|
||||
}
|
||||
|
||||
err := os.MkdirAll(config_dir, 0755)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not create config directory: %v", err)
|
||||
}
|
||||
|
||||
config_path := filepath.Join(config_dir, "server.toml")
|
||||
|
||||
fmt.Printf("Config File Dir: %v\n", config_path)
|
||||
|
||||
// open file, creating it if empty
|
||||
config_file, err := os.OpenFile(config_path, os.O_RDWR|os.O_CREATE, 0755)
|
||||
defer config_file.Close()
|
||||
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not open config file: %v", err)
|
||||
}
|
||||
|
||||
fi, err := config_file.Stat()
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not get config file size: %v", err)
|
||||
}
|
||||
|
||||
if fi.Size() == 0 {
|
||||
// if file is empty, write default config
|
||||
data, err := toml.Marshal(config)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not write default config to file: %v", err)
|
||||
}
|
||||
config_file.Write(data)
|
||||
// return nil as the user must edit the config file
|
||||
return nil, nil
|
||||
} else {
|
||||
// try to parse config file
|
||||
data, err := ioutil.ReadAll(config_file)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not read data from config file: %v", err)
|
||||
}
|
||||
err = toml.Unmarshal(data, &config)
|
||||
if err != nil {
|
||||
return &config, fmt.Errorf("Could not parse config file contents: %v", err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func get_data_dir() string {
|
||||
// Find data directory
|
||||
|
||||
@@ -99,187 +20,64 @@ func get_data_dir() string {
|
||||
xdg_data_home := os.Getenv("XDG_DATA_HOME")
|
||||
|
||||
if xdg_data_home != "" {
|
||||
return filepath.Join(xdg_data_home, "ikinuki")
|
||||
return filepath.Join(xdg_data_home, "mediasrv")
|
||||
} else {
|
||||
home := os.Getenv("HOME")
|
||||
return filepath.Join(home, ".local", "share", "ikinuki")
|
||||
return filepath.Join(home, ".local", "share", "mediasrv")
|
||||
}
|
||||
}
|
||||
|
||||
func open_database(data_dir string) (*sql.DB, error) {
|
||||
// create data directory
|
||||
err := os.MkdirAll(data_dir, 0755)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not create data directory: %v", err)
|
||||
}
|
||||
var log = logging.MustGetLogger("mediasrv-server")
|
||||
|
||||
// open database
|
||||
db_path := filepath.Join(data_dir, "ikinuki-server.db")
|
||||
|
||||
db, err := sql.Open("sqlite3", db_path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not open database: %v", err)
|
||||
}
|
||||
|
||||
// initalize database
|
||||
sqlStmt := `
|
||||
CREATE TABLE tvshows(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT,
|
||||
original_title TEXT,
|
||||
show_title TEXT,
|
||||
year INTEGER
|
||||
);
|
||||
CREATE TABLE episodes(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
number INTEGER,
|
||||
season INTEGER
|
||||
);
|
||||
`
|
||||
|
||||
_, err = db.Exec(sqlStmt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Could not initalize database: %v", err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
type TVShow struct {
|
||||
XMLName xml.Name `xml:"tvshow"`
|
||||
Title string `xml:"title"`
|
||||
OriginalTile string `xml:"originaltitle"`
|
||||
ShowTitle string `xml:"showtitle"`
|
||||
Year int `xml:"year"`
|
||||
}
|
||||
|
||||
func scan_tvshow_root(root string, db *sql.DB) error {
|
||||
files, err := ioutil.ReadDir(root)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not get files in directory \"%v\": %v", root, err)
|
||||
}
|
||||
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not begin db transaction: %v", err)
|
||||
}
|
||||
defer tx.Commit()
|
||||
|
||||
stmt, err := tx.Prepare("insert into tvshows(title, original_title, show_title, year) values(?, ?, ?, ?)")
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not prepare statement: %v", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
show_path := filepath.Join(root, file.Name())
|
||||
if insert_tvshow_nfo(show_path, stmt) {
|
||||
err = scan_tvshow_episodes(show_path)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Could not scan for episodes in %v: %v", show_path, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insert_tvshow_nfo(show_dir string, stmt *sql.Stmt) bool {
|
||||
tvshow_nfo_path := filepath.Join(show_dir, "tvshow.nfo")
|
||||
|
||||
tvshow_nfo_file, err := os.OpenFile(tvshow_nfo_path, os.O_RDONLY, 0755)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Could not open tvshow.nfo file in \"%v\"\n", show_dir)
|
||||
return false
|
||||
}
|
||||
defer tvshow_nfo_file.Close()
|
||||
|
||||
// try to parse nfo file
|
||||
data, err := ioutil.ReadAll(tvshow_nfo_file)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: Could not read data from tvshow.nfo file: %v\n", err)
|
||||
return false
|
||||
}
|
||||
var tvshow TVShow
|
||||
|
||||
err = xml.Unmarshal(data, &tvshow)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: Could not parse tvshow.nfo file contents: %v\n", err)
|
||||
return false
|
||||
}
|
||||
|
||||
// TODO: Replace with print formatting logic
|
||||
fmt.Printf("%v (%v):\n", tvshow.Title, tvshow.Year)
|
||||
fmt.Printf(" Original Title: %v\n", tvshow.OriginalTile)
|
||||
fmt.Printf(" Show Title: %v\n", tvshow.ShowTitle)
|
||||
|
||||
_, err = stmt.Exec(tvshow.Title, tvshow.OriginalTile, tvshow.ShowTitle, tvshow.Year)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: Could not insert tvshow into database: %v\n", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type Episode struct {
|
||||
XMLName xml.Name `xml:"episodedetails"`
|
||||
Title string `xml:"title"`
|
||||
ShowTitle string `xml:"showtitle"`
|
||||
Year int `xml:"year"`
|
||||
}
|
||||
|
||||
func scan_tvshow_episodes(show_dir string) error {
|
||||
|
||||
files, err := ioutil.ReadDir(show_dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not enumerate files in folder: %v", err)
|
||||
}
|
||||
|
||||
// Regex to see if filename contains SXXEYY string
|
||||
var re = regexp.MustCompile(".*S(\\d+)E(\\d+).*")
|
||||
|
||||
for _, file := range files {
|
||||
parts := re.FindStringSubmatch(file.Name())
|
||||
if len(parts) != 3 {
|
||||
fmt.Fprintf(os.Stderr, "Filename \"%v\" failed regex capture (%v)\n", file.Name(), len(parts))
|
||||
continue
|
||||
}
|
||||
fmt.Printf("%v: S%vE%v\n", file.Name(), parts[1], parts[2])
|
||||
|
||||
|
||||
}
|
||||
return nil
|
||||
type Config struct {
|
||||
Address string
|
||||
Port int
|
||||
ScanDirectory string
|
||||
}
|
||||
|
||||
func main() {
|
||||
var format = logging.MustStringFormatter(
|
||||
`%{color}%{time:15:04:05.000} %{level:.4s}:%{color:reset} %{message}`,
|
||||
)
|
||||
|
||||
config_dir := get_config_dir()
|
||||
backend := logging.NewLogBackend(os.Stderr, "", 0)
|
||||
backendFormatter := logging.NewBackendFormatter(backend, format)
|
||||
backendLeveled := logging.AddModuleLevel(backendFormatter)
|
||||
backendLeveled.SetLevel(logging.DEBUG, "")
|
||||
|
||||
config, err := get_config(config_dir)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
logging.SetBackend(backendLeveled)
|
||||
|
||||
configData := config.Config[Config]{
|
||||
Name: "mediasrv",
|
||||
Filename: "server",
|
||||
Config: Config{
|
||||
Address: "127.0.0.1",
|
||||
Port: 32520,
|
||||
ScanDirectory: "FILL IN",
|
||||
},
|
||||
}
|
||||
if config == nil {
|
||||
fmt.Printf("Created config file at %v, please edit and launch again\n", config_dir)
|
||||
os.Exit(0)
|
||||
|
||||
ret, err := configData.Get()
|
||||
if ret == true {
|
||||
log.Warningf("Created config file at %v, please edit and launch again\n", *configData.ConfigFile)
|
||||
return
|
||||
}
|
||||
fmt.Printf("Config: %v\n", config)
|
||||
|
||||
data_dir := get_data_dir()
|
||||
|
||||
db, err := open_database(data_dir)
|
||||
db, is_new, err := database.OpenDatabase(data_dir)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: Could not open database: %v", err)
|
||||
os.Exit(1)
|
||||
log.Fatalf("Could not open database: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
err = scan_tvshow_root(config.ScanDirectory, db)
|
||||
if is_new {
|
||||
err = database.ScanTvshowRoot(configData.Config.ScanDirectory, db)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: Could not scan directory \"%v\": %v\n", config.ScanDirectory, err)
|
||||
os.Exit(1)
|
||||
log.Fatalf("Could not scan directory \"%v\": %v\n", configData.Config.ScanDirectory, err)
|
||||
}
|
||||
}
|
||||
|
||||
rest.RunServer(configData.Config.Address, configData.Config.Port, data_dir, configData.Config.ScanDirectory)
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.ohea.xyz/mediasrv/server/client_api"
|
||||
"git.ohea.xyz/mediasrv/server/server_api"
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
var log = logging.MustGetLogger("mediasrv-server")
|
||||
|
||||
func RunServer(address string, port int, dataDir string, scanDir string) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
client_api.SetupHTTPServer(mux, dataDir)
|
||||
server_api.SetupHTTPServer(mux, scanDir)
|
||||
|
||||
connect_string := fmt.Sprintf("%v:%v", address, port)
|
||||
log.Noticef("Launching HTTP server on %v\n", connect_string)
|
||||
log.Fatal(http.ListenAndServe(connect_string, mux))
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package server_api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"git.ohea.xyz/mediasrv/server/filesystem"
|
||||
"github.com/op/go-logging"
|
||||
)
|
||||
|
||||
var log = logging.MustGetLogger("mediasrv-server")
|
||||
|
||||
func SetupHTTPServer(mux *http.ServeMux, data_dir string) {
|
||||
mux.HandleFunc("/server/files", func(w http.ResponseWriter, r *http.Request) {
|
||||
filesHandler(data_dir, w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func filesHandler(rootDir string, w http.ResponseWriter, r *http.Request) {
|
||||
log.Debugf("/server/files called")
|
||||
return_json, err := filesystem.GetFilesystem(rootDir)
|
||||
if err != nil {
|
||||
log.Errorf("Could not get filsystem data: %v", err)
|
||||
return
|
||||
}
|
||||
data, err := json.MarshalIndent(return_json, "", "\t")
|
||||
if err != nil {
|
||||
log.Errorf("Could not marshal data: %v\n", err)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}
|
||||
Reference in New Issue
Block a user