use new lib

This commit is contained in:
2021-08-20 21:20:33 +02:00
parent 546f9c34d2
commit 4f6025759f
47 changed files with 211 additions and 705 deletions

48
apiGo/api/API.go Normal file
View File

@ -0,0 +1,48 @@
package api
import (
gws "github.com/gowebsecure/goWebSecure-go"
"github.com/gowebsecure/goWebSecure-go/oauth"
"openmediacenter/apiGo/database/settings"
)
const (
VideoNode = iota
TagNode = iota
SettingsNode = iota
ActorNode = iota
TVShowNode = iota
)
func Init() {
AddVideoHandlers()
AddSettingsHandlers()
AddTagHandlers()
AddActorsHandlers()
AddTvshowHandlers()
gws.AddAPINode("video", VideoNode)
gws.AddAPINode("tags", TagNode)
gws.AddAPINode("settings", SettingsNode)
gws.AddAPINode("actor", ActorNode)
gws.AddAPINode("tvshow", TVShowNode)
// serverinit is blocking
gws.ServerInit(func(id string) (oauth.CustomClientInfo, error) {
password := settings.GetPassword()
// if password not set assign default password
if password == nil {
defaultpassword := "openmediacenter"
password = &defaultpassword
}
clientinfo := oauth.CustomClientInfo{
ID: "openmediacenter",
Secret: *password,
Domain: "http://localhost:8081",
UserID: "openmediacenter",
}
return clientinfo, nil
}, 8080)
}

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
gws "github.com/gowebsecure/goWebSecure-go"
"openmediacenter/apiGo/api/types"
"openmediacenter/apiGo/database"
)
@ -23,7 +24,7 @@ func getActorsFromDB() {
* @apiSuccess {string} .Name Actor Name
* @apiSuccess {string} .Thumbnail Portrait Thumbnail
*/
AddHandler("getAllActors", ActorNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getAllActors", ActorNode, func(info *gws.HandlerInfo) []byte {
query := "SELECT actor_id, name, thumbnail FROM actors"
return jsonify(readActorsFromResultset(database.Query(query)))
})
@ -41,7 +42,7 @@ func getActorsFromDB() {
* @apiSuccess {string} .Name Actor Name
* @apiSuccess {string} .Thumbnail Portrait Thumbnail
*/
AddHandler("getActorsOfVideo", ActorNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getActorsOfVideo", ActorNode, func(info *gws.HandlerInfo) []byte {
var args struct {
MovieId int
}
@ -74,7 +75,7 @@ func getActorsFromDB() {
* @apiSuccess {string} Info.Name Actor Name
* @apiSuccess {string} Info.Thumbnail Actor Thumbnail
*/
AddHandler("getActorInfo", ActorNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getActorInfo", ActorNode, func(info *gws.HandlerInfo) []byte {
var args struct {
ActorId int
}
@ -114,7 +115,7 @@ func saveActorsToDB() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("createActor", ActorNode, func(info *HandlerInfo) []byte {
gws.AddHandler("createActor", ActorNode, func(info *gws.HandlerInfo) []byte {
var args struct {
ActorName string
}
@ -138,7 +139,7 @@ func saveActorsToDB() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("addActorToVideo", ActorNode, func(info *HandlerInfo) []byte {
gws.AddHandler("addActorToVideo", ActorNode, func(info *gws.HandlerInfo) []byte {
var args struct {
ActorId int
MovieId int

View File

@ -1,113 +0,0 @@
package api
import (
"bytes"
"encoding/json"
"fmt"
"gopkg.in/oauth2.v3"
"net/http"
"openmediacenter/apiGo/api/oauth"
)
const APIPREFIX = "/api"
const (
VideoNode = iota
TagNode = iota
SettingsNode = iota
ActorNode = iota
TVShowNode = iota
)
type HandlerInfo struct {
ID string
Token string
Data map[string]interface{}
}
type actionStruct struct {
Action string
}
type Handler struct {
action string
handler func(info *HandlerInfo) []byte
apiNode int
}
var handlers = make(map[string]Handler)
func AddHandler(action string, apiNode int, h func(info *HandlerInfo) []byte) {
// append new handler to the handlers
handlers[fmt.Sprintf("%s/%d", action, apiNode)] = Handler{action, h, apiNode}
}
func ServerInit() {
http.Handle(APIPREFIX+"/video", oauth.ValidateToken(handlefunc, VideoNode))
http.Handle(APIPREFIX+"/tags", oauth.ValidateToken(handlefunc, TagNode))
http.Handle(APIPREFIX+"/settings", oauth.ValidateToken(handlefunc, SettingsNode))
http.Handle(APIPREFIX+"/actor", oauth.ValidateToken(handlefunc, ActorNode))
http.Handle(APIPREFIX+"/tvshow", oauth.ValidateToken(handlefunc, TVShowNode))
// initialize oauth service and add corresponding auth routes
oauth.InitOAuth()
}
func handleAPICall(action string, requestBody string, apiNode int, info *HandlerInfo) []byte {
handler, ok := handlers[fmt.Sprintf("%s/%d", action, apiNode)]
if !ok {
// handler doesn't exist!
fmt.Printf("no handler found for Action: %d/%s\n", apiNode, action)
return nil
}
// check if info even exists
if info == nil {
info = &HandlerInfo{}
}
// parse the arguments
var args map[string]interface{}
err := json.Unmarshal([]byte(requestBody), &args)
if err != nil {
fmt.Printf("failed to decode arguments of action %s :: %s\n", action, requestBody)
} else {
// check if map has an action
if _, ok := args["action"]; ok {
delete(args, "action")
}
info.Data = args
}
// call the handler
return handler.handler(info)
}
func handlefunc(rw http.ResponseWriter, req *http.Request, node int, tokenInfo *oauth2.TokenInfo) {
// only allow post requests
if req.Method != "POST" {
return
}
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
body := buf.String()
var t actionStruct
err := json.Unmarshal([]byte(body), &t)
if err != nil {
fmt.Println("failed to read action from request! :: " + body)
}
// load userid from received token object
id := (*tokenInfo).GetClientID()
userinfo := &HandlerInfo{
ID: id,
Token: (*tokenInfo).GetCode(),
}
rw.Write(handleAPICall(t.Action, body, node, userinfo))
}

View File

@ -1,72 +0,0 @@
package api
import (
"testing"
)
func cleanUp() {
handlers = make(map[string]Handler)
}
func TestAddHandler(t *testing.T) {
cleanUp()
AddHandler("test", ActorNode, func(info *HandlerInfo) []byte {
return nil
})
if len(handlers) != 1 {
t.Errorf("Handler insertion failed, got: %d handlers, want: %d.", len(handlers), 1)
}
}
func TestCallOfHandler(t *testing.T) {
cleanUp()
i := 0
AddHandler("test", ActorNode, func(info *HandlerInfo) []byte {
i++
return nil
})
// simulate the call of the api
handleAPICall("test", "", ActorNode, nil)
if i != 1 {
t.Errorf("Unexpected number of Lambda calls : %d/1", i)
}
}
func TestDecodingOfArguments(t *testing.T) {
cleanUp()
AddHandler("test", ActorNode, func(info *HandlerInfo) []byte {
var args struct {
Test string
TestInt int
}
err := FillStruct(&args, info.Data)
if err != nil {
t.Errorf("Error parsing args: %s", err.Error())
return nil
}
if args.TestInt != 42 || args.Test != "myString" {
t.Errorf("Wrong parsing of argument parameters : %d/42 - %s/myString", args.TestInt, args.Test)
}
return nil
})
// simulate the call of the api
handleAPICall("test", `{"Test":"myString","TestInt":42}`, ActorNode, nil)
}
func TestNoHandlerCovers(t *testing.T) {
cleanUp()
ret := handleAPICall("test", "", ActorNode, nil)
if ret != nil {
t.Error("Expect nil return within unhandled api action")
}
}

View File

@ -3,6 +3,7 @@ package api
import (
"encoding/json"
"fmt"
gws "github.com/gowebsecure/goWebSecure-go"
"openmediacenter/apiGo/api/types"
"openmediacenter/apiGo/database"
"openmediacenter/apiGo/database/settings"
@ -37,7 +38,7 @@ func getSettingsFromDB() {
* @apiSuccess {uint32} Sizes.DifferentTags number of different tags available
* @apiSuccess {uint32} Sizes.TagsAdded number of different tags added to videos
*/
AddHandler("loadGeneralSettings", SettingsNode, func(info *HandlerInfo) []byte {
gws.AddHandler("loadGeneralSettings", SettingsNode, func(info *gws.HandlerInfo) []byte {
result, _, sizes := database.GetSettings()
var ret = struct {
@ -63,7 +64,7 @@ func getSettingsFromDB() {
* @apiSuccess {bool} DarkMode Darkmode enabled?
* @apiSuccess {bool} TVShowEnabled is are TVShows enabled
*/
AddHandler("loadInitialData", SettingsNode, func(info *HandlerInfo) []byte {
gws.AddHandler("loadInitialData", SettingsNode, func(info *gws.HandlerInfo) []byte {
sett := settings.LoadSettings()
type InitialDataTypeResponse struct {
@ -111,7 +112,7 @@ func saveSettingsToDB() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("saveGeneralSettings", SettingsNode, func(info *HandlerInfo) []byte {
gws.AddHandler("saveGeneralSettings", SettingsNode, func(info *gws.HandlerInfo) []byte {
var args types.SettingsType
if err := FillStruct(&args, info.Data); err != nil {
fmt.Println(err.Error())
@ -143,7 +144,7 @@ func reIndexHandling() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("startReindex", SettingsNode, func(info *HandlerInfo) []byte {
gws.AddHandler("startReindex", SettingsNode, func(info *gws.HandlerInfo) []byte {
videoparser.StartReindex()
return database.ManualSuccessResponse(nil)
})
@ -156,7 +157,7 @@ func reIndexHandling() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("startTVShowReindex", SettingsNode, func(info *HandlerInfo) []byte {
gws.AddHandler("startTVShowReindex", SettingsNode, func(info *gws.HandlerInfo) []byte {
videoparser.StartTVShowReindex()
return database.ManualSuccessResponse(nil)
})
@ -167,7 +168,7 @@ func reIndexHandling() {
* @apiName cleanupGravity
* @apiGroup Settings
*/
AddHandler("cleanupGravity", SettingsNode, func(info *HandlerInfo) []byte {
gws.AddHandler("cleanupGravity", SettingsNode, func(info *gws.HandlerInfo) []byte {
videoparser.StartCleanup()
return nil
})

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
gws "github.com/gowebsecure/goWebSecure-go"
"openmediacenter/apiGo/database"
"openmediacenter/apiGo/database/settings"
)
@ -22,7 +23,7 @@ func AddTvshowHandlers() {
* @apiSuccess {uint32} .Id tvshow id
* @apiSuccess {string} .Name tvshow name
*/
AddHandler("getTVShows", TVShowNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getTVShows", TVShowNode, func(info *gws.HandlerInfo) []byte {
query := "SELECT id, name FROM tvshow"
rows := database.Query(query)
return jsonify(readTVshowsFromResultset(rows))
@ -42,7 +43,7 @@ func AddTvshowHandlers() {
* @apiSuccess {uint8} .Season Season number
* @apiSuccess {uint8} .Episode Episode number
*/
AddHandler("getEpisodes", TVShowNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getEpisodes", TVShowNode, func(info *gws.HandlerInfo) []byte {
var args struct {
ShowID uint32
}
@ -90,7 +91,7 @@ func AddTvshowHandlers() {
* @apiSuccess {uint8} Episode Episode number
* @apiSuccess {string} Path webserver path of video file
*/
AddHandler("loadEpisode", TVShowNode, func(info *HandlerInfo) []byte {
gws.AddHandler("loadEpisode", TVShowNode, func(info *gws.HandlerInfo) []byte {
var args struct {
ID uint32
}
@ -137,7 +138,7 @@ WHERE tvshow_episodes.id=%d`, args.ID)
*
* @apiSuccess {string} . Base64 encoded Thubnail
*/
AddHandler("readThumbnail", TVShowNode, func(info *HandlerInfo) []byte {
gws.AddHandler("readThumbnail", TVShowNode, func(info *gws.HandlerInfo) []byte {
var args struct {
Id int
}

View File

@ -2,6 +2,7 @@ package api
import (
"fmt"
gws "github.com/gowebsecure/goWebSecure-go"
"openmediacenter/apiGo/database"
"regexp"
)
@ -24,7 +25,7 @@ func deleteFromDB() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("deleteTag", TagNode, func(info *HandlerInfo) []byte {
gws.AddHandler("deleteTag", TagNode, func(info *gws.HandlerInfo) []byte {
var args struct {
TagId int
Force bool
@ -74,7 +75,7 @@ func getFromDB() {
* @apiSuccess {uint32} TagId
* @apiSuccess {string} TagName name of the Tag
*/
AddHandler("getAllTags", TagNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getAllTags", TagNode, func(info *gws.HandlerInfo) []byte {
query := "SELECT tag_id,tag_name from tags"
return jsonify(readTagsFromResultset(database.Query(query)))
})
@ -91,7 +92,7 @@ func addToDB() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("createTag", TagNode, func(info *HandlerInfo) []byte {
gws.AddHandler("createTag", TagNode, func(info *gws.HandlerInfo) []byte {
var args struct {
TagName string
}
@ -115,7 +116,7 @@ func addToDB() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("addTag", TagNode, func(info *HandlerInfo) []byte {
gws.AddHandler("addTag", TagNode, func(info *gws.HandlerInfo) []byte {
var args struct {
MovieId int
TagId int

View File

@ -3,6 +3,7 @@ package api
import (
"encoding/json"
"fmt"
gws "github.com/gowebsecure/goWebSecure-go"
"net/url"
"openmediacenter/apiGo/api/types"
"openmediacenter/apiGo/database"
@ -29,7 +30,7 @@ func getVideoHandlers() {
* @apiSuccess {String} Videos.MovieName Name of video
* @apiSuccess {String} TagName Name of the Tag returned
*/
AddHandler("getMovies", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getMovies", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
Tag uint32
Sort uint8
@ -120,7 +121,7 @@ func getVideoHandlers() {
*
* @apiSuccess {string} . Base64 encoded Thubnail
*/
AddHandler("readThumbnail", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("readThumbnail", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
Movieid int
}
@ -158,7 +159,7 @@ func getVideoHandlers() {
* @apiSuccess {string} Videos.MovieName Video Name
* @apiSuccess {int} Videos.MovieId Video ID
*/
AddHandler("getRandomMovies", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getRandomMovies", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
Number int
}
@ -219,7 +220,7 @@ func getVideoHandlers() {
* @apiSuccess {number} .MovieId Id of Video
* @apiSuccess {String} .MovieName Name of video
*/
AddHandler("getSearchKeyWord", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getSearchKeyWord", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
KeyWord string
}
@ -271,7 +272,7 @@ func loadVideosHandlers() {
* @apiSuccess {string} Actors.Name Actor Name
* @apiSuccess {string} Actors.Thumbnail Portrait Thumbnail
*/
AddHandler("loadVideo", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("loadVideo", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
MovieId int
}
@ -347,7 +348,7 @@ func loadVideosHandlers() {
* @apiSuccess {uint32} DifferentTags number of different Tags available
* @apiSuccess {uint32} Tagged number of different Tags assigned
*/
AddHandler("getStartData", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("getStartData", VideoNode, func(info *gws.HandlerInfo) []byte {
var result types.StartData
// query settings and infotile values
query := `
@ -398,7 +399,7 @@ func addToVideoHandlers() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("addLike", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("addLike", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
MovieId int
}
@ -421,7 +422,7 @@ func addToVideoHandlers() {
*
* @apiSuccess {string} result 'success' if successfully or error message if not
*/
AddHandler("deleteVideo", VideoNode, func(info *HandlerInfo) []byte {
gws.AddHandler("deleteVideo", VideoNode, func(info *gws.HandlerInfo) []byte {
var args struct {
MovieId int
}

View File

@ -1,57 +0,0 @@
package oauth
import (
"gopkg.in/oauth2.v3"
"openmediacenter/apiGo/database/settings"
)
type CustomClientStore struct {
oauth2.ClientStore
}
type CustomClientInfo struct {
oauth2.ClientInfo
ID string
Secret string
Domain string
UserID string
}
func NewCustomStore() oauth2.ClientStore {
s := new(CustomClientStore)
return s
}
func (a *CustomClientStore) GetByID(id string) (oauth2.ClientInfo, error) {
password := settings.GetPassword()
// if password not set assign default password
if password == nil {
defaultpassword := "openmediacenter"
password = &defaultpassword
}
clientinfo := CustomClientInfo{
ID: "openmediacenter",
Secret: *password,
Domain: "http://localhost:8081",
UserID: "openmediacenter",
}
return &clientinfo, nil
}
func (a *CustomClientInfo) GetID() string {
return a.ID
}
func (a *CustomClientInfo) GetSecret() string {
return a.Secret
}
func (a *CustomClientInfo) GetDomain() string {
return a.Domain
}
func (a *CustomClientInfo) GetUserID() string {
return a.UserID
}

View File

@ -1,62 +0,0 @@
package oauth
import (
"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/errors"
"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/server"
"gopkg.in/oauth2.v3/store"
"log"
"net/http"
)
var srv *server.Server
func InitOAuth() {
manager := manage.NewDefaultManager()
// token store
manager.MustTokenStorage(store.NewMemoryTokenStore())
// create new secretstore
clientStore := NewCustomStore()
manager.MapClientStorage(clientStore)
srv = server.NewServer(server.NewConfig(), manager)
srv.SetClientInfoHandler(server.ClientFormHandler)
manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg)
srv.SetInternalErrorHandler(func(err error) (re *errors.Response) {
log.Println("Internal Error:", err.Error())
return
})
srv.SetResponseErrorHandler(func(re *errors.Response) {
log.Println("Response Error:", re.Error.Error())
})
http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
err := srv.HandleAuthorizeRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
})
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
err := srv.HandleTokenRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
}
func ValidateToken(f func(rw http.ResponseWriter, req *http.Request, node int, tokenInfo *oauth2.TokenInfo), node int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tokeninfo, err := srv.ValidationBearerToken(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
f(w, r, node, &tokeninfo)
}
}