Skip to content

Commit

Permalink
embed: add feature option
Browse files Browse the repository at this point in the history
  • Loading branch information
vintikzzz committed May 21, 2024
1 parent 9e29d8b commit d4f094b
Show file tree
Hide file tree
Showing 14 changed files with 186 additions and 66 deletions.
1 change: 1 addition & 0 deletions assets/src/js/app/embed/check.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import message from './message';
const sha1 = require('sha1');
message.send('init');
const data = await message.receiveOnce('init');
console.log(data);
const c = await check();
if (c) {
initPlaceholder(data);
Expand Down
1 change: 1 addition & 0 deletions assets/src/js/app/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ function onLoad() {
async fetch(f, url, fetchParams) {
showProgress();
fetchParams.headers['X-CSRF-TOKEN'] = window._CSRF;
fetchParams.headers['X-SESSION-ID'] = window._sessionID;
const res = await fetch(url, fetchParams);
hideProgress();
return res;
Expand Down
12 changes: 11 additions & 1 deletion assets/src/js/lib/mediaelement.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ let video;

export function initPlayer(target, ready) {
video = target.querySelector('.player');
const settings = JSON.parse(video.dataset.settings);
const width = video.width;
const height = video.height;
const controls = video.controls;
Expand All @@ -97,7 +98,7 @@ export function initPlayer(target, ready) {
}

const duration = video.getAttribute('data-duration') ? parseFloat(video.getAttribute('data-duration')) : -1;
const features = [
let features = [
'playpause',
'current',
'progress',
Expand All @@ -109,6 +110,15 @@ export function initPlayer(target, ready) {
if (duration > 0) {
features.push('availableprogress');
}
if (settings.features) {
for (const name in settings.features) {
if (features.includes(name) && settings.features[name] == false) {
features = features.filter((e) => e != name);
} else if (!features.includes(name) && settings.features[name] == true) {
features.push(name);
}
}
}
player = new MediaElementPlayer(video, {
autoRewind: false,
defaultSeekBackwardInterval: (media) => 15,
Expand Down
7 changes: 7 additions & 0 deletions serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
wm "github.com/webtor-io/web-ui-v2/services/web/migration"
p "github.com/webtor-io/web-ui-v2/services/web/profile"
wr "github.com/webtor-io/web-ui-v2/services/web/resource"
sess "github.com/webtor-io/web-ui-v2/services/web/session"
)

func makeServeCMD() cli.Command {
Expand All @@ -46,6 +47,7 @@ func configureServe(c *cli.Command) {
c.Flags = auth.RegisterFlags(c.Flags)
c.Flags = claims.RegisterFlags(c.Flags)
c.Flags = claims.RegisterClientFlags(c.Flags)
c.Flags = sess.RegisterFlags(c.Flags)
// c.Flags = cs.RegisterRedisClientFlags(c.Flags)
}

Expand Down Expand Up @@ -76,6 +78,11 @@ func serve(c *cli.Context) error {
servers = append(servers, web)
defer web.Close()

err = sess.RegisterHandler(c, r)
if err != nil {
return err
}

// Setting Migration from v1 to v2
wm.RegisterHandler(r)

Expand Down
3 changes: 2 additions & 1 deletion services/web/action/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/webtor-io/web-ui-v2/services/job"
"github.com/webtor-io/web-ui-v2/services/template"
wj "github.com/webtor-io/web-ui-v2/services/web/job"
"github.com/webtor-io/web-ui-v2/services/web/job/script"
)

type PostArgs struct {
Expand Down Expand Up @@ -116,7 +117,7 @@ func (s *Handler) post(c *gin.Context, action string) {
}
d.Args = args
ctx, _ := context.WithTimeout(context.Background(), 5*time.Minute)
job, err = s.jobs.Action(ctx, c, args.Claims, args.ResourceID, args.ItemID, action)
job, err = s.jobs.Action(ctx, c, args.Claims, args.ResourceID, args.ItemID, action, &script.StreamSettings{})
if err != nil {
postTpl.HTMLWithErr(errors.Wrap(err, "failed to start downloading"), http.StatusBadRequest, c, d)
return
Expand Down
9 changes: 9 additions & 0 deletions services/web/action/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
ra "github.com/webtor-io/rest-api/services"
"github.com/webtor-io/web-ui-v2/services/api"
m "github.com/webtor-io/web-ui-v2/services/models"
"github.com/webtor-io/web-ui-v2/services/web/job/script"
"golang.org/x/text/language"
)

Expand All @@ -32,6 +33,14 @@ func (s *Helper) GetDurationSec(mp *api.MediaProbe) string {
return mp.Format.Duration
}

func (s *Helper) HasControls(settings *script.StreamSettings) bool {
if settings.Controls == nil {
return true
}
controls := *settings.Controls
return controls
}

func (s *Helper) GetAudioTracks(ud *m.VideoStreamUserData, mp *api.MediaProbe) []ListItem {
var res []ListItem
if mp == nil {
Expand Down
25 changes: 14 additions & 11 deletions services/web/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,31 @@ package web

import (
"github.com/gin-gonic/gin"
csrf "github.com/utrack/gin-csrf"
"github.com/webtor-io/web-ui-v2/services/auth"
"github.com/webtor-io/web-ui-v2/services/claims"
"github.com/webtor-io/web-ui-v2/services/web/session"
)

type Context struct {
Data any
CSRF string
Err error
User *auth.User
Claims *claims.Data
Data any
CSRF string
SessionID string
Err error
User *auth.User
Claims *claims.Data
}

func NewContext(c *gin.Context, obj any, err error) any {
user := auth.GetUserFromContext(c)
cl := claims.GetFromContext(c)
sess := session.GetFromContext(c)

return &Context{
Data: obj,
CSRF: csrf.GetToken(c),
Err: err,
User: user,
Claims: cl,
Data: obj,
CSRF: sess.CSRF,
Err: err,
User: user,
Claims: cl,
SessionID: sess.ID,
}
}
6 changes: 2 additions & 4 deletions services/web/job/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@ import (
"github.com/webtor-io/web-ui-v2/services/web/job/script"
)

func (s *Handler) Action(ctx context.Context, c *gin.Context, claims *api.Claims, resourceID string, itemID string, action string) (j *job.Job, err error) {
as, id := script.Action(s.tb, s.api, claims, c, resourceID, itemID, action, &script.StreamSettings{
Controls: true,
})
func (s *Handler) Action(ctx context.Context, c *gin.Context, claims *api.Claims, resourceID string, itemID string, action string, settings *script.StreamSettings) (j *job.Job, err error) {
as, id := script.Action(s.tb, s.api, claims, c, resourceID, itemID, action, settings)
j = s.q.GetOrCreate(action).Enqueue(ctx, id, as)
return
}
4 changes: 2 additions & 2 deletions services/web/job/script/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ type StreamSettings struct {
ImdbID string `json:"imdbId"`
Lang string `json:"lang"`
I18n struct{} `json:"i18n"`
Features struct{} `json:"features"`
Features map[string]bool `json:"features"`
El struct{} `json:"el"`
Controls bool `json:"controls"`
Controls *bool `json:"controls"`
}

func (s *ActionScript) streamContent(j *job.Job, c *gin.Context, claims *api.Claims, resourceID string, itemID string, template string, settings *StreamSettings) (err error) {
Expand Down
116 changes: 116 additions & 0 deletions services/web/session/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package session

import (
"bufio"
"context"
"fmt"
"net/http"
"strings"

"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
"github.com/urfave/cli"
csrf "github.com/utrack/gin-csrf"
"github.com/webtor-io/web-ui-v2/services"

log "github.com/sirupsen/logrus"
)

const (
sessionSecretFlag = "secret"
)

func RegisterFlags(f []cli.Flag) []cli.Flag {
return append(f,
cli.StringFlag{
Name: sessionSecretFlag,
Usage: "session secret",
Value: "secret123",
EnvVar: "SESSION_SECRET",
},
)
}

type Session struct {
ID string
CSRF string
}

func RegisterHandler(c *cli.Context, r *gin.Engine) (err error) {
var store sessions.Store
if c.String(services.RedisHostFlag) != "" && c.Int(services.RedisPortFlag) != 0 {
url := fmt.Sprintf("%v:%v", c.String(services.RedisHostFlag), c.Int(services.RedisPortFlag))
store, err = redis.NewStore(10, "tcp", url, "", []byte(sessionSecretFlag))
if err != nil {
return err
}
log.Infof("using redis store %v", url)
} else {
store = cookie.NewStore([]byte(sessionSecretFlag))
}
r.Use(func(ctx *gin.Context) {
id := ctx.GetHeader("X-Session-Id")
if id != "" {
ctx.Request.AddCookie(&http.Cookie{
Name: "session",
Value: id,
})
}

})
r.Use(sessions.Sessions("session", store))
r.Use(csrf.Middleware(csrf.Options{
Secret: c.String(sessionSecretFlag),
ErrorFunc: func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/auth/dashboard") {
c.Next()
return
}
c.String(400, "CSRF token mismatch")
c.Abort()
},
}))
r.Use(func(c *gin.Context) {
if c.GetHeader("X-Token") != "" {
csrf.GetToken(c)
}
})
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), Session{}, &Session{
CSRF: csrf.GetToken(c),
ID: getSessionId(c, "session"),
}))
})
return
}
func getSessionId(c *gin.Context, name string) (id string) {
id, _ = c.Cookie(name)
if id != "" {
return
}
id = getSessionIdFromResponseHeader(c, "Set-Cookie", name)
return
}

func getSessionIdFromResponseHeader(c *gin.Context, headerName string, cookieName string) string {
cookies := c.Writer.Header().Get(headerName)
rawRequest := fmt.Sprintf("GET / HTTP/1.0\r\nCookie: %s\r\n\r\n", cookies)
req, _ := http.ReadRequest(bufio.NewReader(strings.NewReader(rawRequest)))
var id string
for _, q := range req.Cookies() {
if q.Name == cookieName {
id = q.Value
break
}
}
return id
}

func GetFromContext(c *gin.Context) *Session {
if r := c.Request.Context().Value(Session{}); r != nil {
return r.(*Session)
}
return nil
}
49 changes: 4 additions & 45 deletions services/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,19 @@ import (
"fmt"
"net"
"net/http"
"strings"

"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-contrib/sessions/redis"
csrf "github.com/utrack/gin-csrf"

"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/urfave/cli"

log "github.com/sirupsen/logrus"

"github.com/webtor-io/web-ui-v2/services"
)

const (
webHostFlag = "host"
webPortFlag = "port"
sessionSecretFlag = "secret"
assetsPathFlag = "assets-path"
assetsHostFlag = "assets-host"
webHostFlag = "host"
webPortFlag = "port"
assetsPathFlag = "assets-path"
assetsHostFlag = "assets-host"
)

func RegisterFlags(f []cli.Flag) []cli.Flag {
Expand All @@ -42,12 +33,6 @@ func RegisterFlags(f []cli.Flag) []cli.Flag {
Value: 8080,
EnvVar: "WEB_PORT",
},
cli.StringFlag{
Name: sessionSecretFlag,
Usage: "session secret",
Value: "secret123",
EnvVar: "SESSION_SECRET",
},

cli.StringFlag{
Name: assetsPathFlag,
Expand Down Expand Up @@ -93,33 +78,7 @@ func (s *Web) Close() {
}

func New(c *cli.Context, r *gin.Engine) (*Web, error) {
var (
store sessions.Store
err error
)

if c.String(services.RedisHostFlag) != "" && c.Int(services.RedisPortFlag) != 0 {
url := fmt.Sprintf("%v:%v", c.String(services.RedisHostFlag), c.Int(services.RedisPortFlag))
store, err = redis.NewStore(10, "tcp", url, "", []byte(sessionSecretFlag))
if err != nil {
return nil, err
}
log.Infof("using redis store %v", url)
} else {
store = cookie.NewStore([]byte(sessionSecretFlag))
}
r.Use(sessions.Sessions("session", store))
r.Use(csrf.Middleware(csrf.Options{
Secret: c.String(sessionSecretFlag),
ErrorFunc: func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/auth/dashboard") {
c.Next()
return
}
c.String(400, "CSRF token mismatch")
c.Abort()
},
}))
r.UseRawPath = true
assetsPath := c.String(assetsPathFlag)
r.Static("/assets", assetsPath)
Expand Down
1 change: 1 addition & 0 deletions templates/layouts/main.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<meta name="description" content="Download and play torrents with free online torrent web player and downloader. Just paste the magnet link or open the torrent file and start downloading or watching torrent content safely and anonymously through your web browser. Works instantly without client and registration!">
<script>
window._CSRF = "{{ .CSRF }}";
window._sessionID = "{{ .SessionID }}";
window._domain = "{{ domain }}";
</script>
<script async src="{{ "layout.js" | asset }}"></script>
Expand Down
Loading

0 comments on commit d4f094b

Please sign in to comment.