Skip to content

Commit

Permalink
add domain settings
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavel Tatarskiy authored and Pavel Tatarskiy committed Jul 11, 2024
1 parent 89b03b3 commit 9d1fb83
Show file tree
Hide file tree
Showing 17 changed files with 181 additions and 21 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"mode": "auto",
"program": "${workspaceRoot}",
"args": ["serve", "--assets-host", "http://localhost:8082"],
"envFile": "${workspaceRoot}/.env"
"envFile": "${workspaceRoot}/.env",
},
{
"name": "Launch Webpack Dev Server",
Expand Down
4 changes: 3 additions & 1 deletion assets/src/js/app/embed/check.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ 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 Expand Up @@ -45,14 +44,17 @@ function initEmbed(data) {
const csrf = document.createElement('input');
csrf.setAttribute('name', '_csrf');
csrf.setAttribute('value', window._CSRF);
csrf.setAttribute('type', 'hidden');
form.append(csrf);
const sessionID = document.createElement('input');
sessionID.setAttribute('name', '_sessionID');
sessionID.setAttribute('value', window._sessionID);
sessionID.setAttribute('type', 'hidden');
form.append(sessionID);
const i = document.createElement('input');
i.setAttribute('name', 'settings');
i.setAttribute('value', JSON.stringify(data));
i.setAttribute('type', 'hidden');
form.append(i);
document.body.append(form);
// form.setAttribute('action', '/');
Expand Down
12 changes: 9 additions & 3 deletions assets/src/js/app/embed/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import message from './message';

function setHeight() {
const width = document.body.offsetWidth;
const height = width/16*9;
Expand All @@ -15,21 +17,25 @@ window.addEventListener('load', async () => {
document.body.style.height = 'auto';
progress.classList.add('hidden');
el.classList.remove('hidden');
if (window._domainSettings.ads && window._injectAds) {
console.log('injecting ads');
message.send('inject', window._injectAds);
}
}, {once: true});
el.classList.add('hidden');
el.classList.add('mb-5')
document.body.appendChild(el);
ev.render(el);
});
if (!window._settings.height) {
if (!window._embedSettings.height) {
const s = document.createElement('script');
s.src = 'assets/lib/iframeResizer.contentWindow.min.js';
document.body.appendChild(s);
}
setHeight();
window.addEventListener('resize', setHeight);
if (window._settings.poster) {
document.body.style.backgroundImage = 'url(' + window._settings.poster + ')';
if (window._embedSettings.poster) {
document.body.style.backgroundImage = 'url(' + window._embedSettings.poster + ')';
document.body.style.backgroundSize = 'cover';
}
});
4 changes: 3 additions & 1 deletion configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package main

import (
"github.com/urfave/cli"
services "github.com/webtor-io/common-services"
)

func configure(app *cli.App) {
serveCmd := makeServeCMD()
app.Commands = []cli.Command{serveCmd}
migrationCMD := services.MakePGMigrationCMD()
app.Commands = []cli.Command{serveCmd, migrationCMD}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ require (
github.com/prometheus/common v0.54.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/satori/go.uuid v1.2.0
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.2 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,8 @@ github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncj
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/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46/go.mod h1:uAQ5PCi+MFsC7HjREoAz1BU+Mq60+05gifQSsHSDG/8=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
Expand Down
2 changes: 2 additions & 0 deletions migrations/1_embed_domain.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
DROP TABLE public.embed_domain;
DROP FUNCTION public.update_updated_at();
28 changes: 28 additions & 0 deletions migrations/1_embed_domain.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE public.embed_domain (
embed_domain_id uuid DEFAULT uuid_generate_v4() NOT NULL,
"domain" text NOT NULL,
email text NOT NULL,
created_at timestamptz DEFAULT now() NOT NULL,
ads bool DEFAULT true NOT NULL,
updated_at timestamptz DEFAULT now() NOT NULL,
CONSTRAINT embed_domain_pk PRIMARY KEY (embed_domain_id),
CONSTRAINT embed_domain_unique UNIQUE (domain)
);

CREATE OR REPLACE FUNCTION public.update_updated_at()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$function$
;

create trigger update_updated_at before
update
on
public.embed_domain for each row execute function update_updated_at();
17 changes: 16 additions & 1 deletion serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/webtor-io/web-ui-v2/services/api"
"github.com/webtor-io/web-ui-v2/services/auth"
"github.com/webtor-io/web-ui-v2/services/embed"

log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
Expand Down Expand Up @@ -41,6 +42,7 @@ func makeServeCMD() cli.Command {
}

func configureServe(c *cli.Command) {
c.Flags = cs.RegisterPGFlags(c.Flags)
c.Flags = cs.RegisterProbeFlags(c.Flags)
c.Flags = api.RegisterFlags(c.Flags)
c.Flags = w.RegisterFlags(c.Flags)
Expand All @@ -55,6 +57,16 @@ func configureServe(c *cli.Command) {
}

func serve(c *cli.Context) error {
// Setting DB
pg := cs.NewPG(c)
defer pg.Close()

// Setting Migrations
m := cs.NewPGMigration(pg)
err := m.Run()
if err != nil {
return err
}

// Setting Redis
// redis := cs.NewRedisClient(c)
Expand Down Expand Up @@ -137,6 +149,9 @@ func serve(c *cli.Context) error {
uc.RegisterHandler(c, r)
}

// Setting DomainSettings
ds := embed.NewDomainSettings(pg, uc)

// Setting ApiClaimsHandler
api.RegisterHandler(c, r)

Expand All @@ -156,7 +171,7 @@ func serve(c *cli.Context) error {
wee.RegisterHandler(c, r, tm)

// Setting EmbedHandler
we.RegisterHandler(c, r, tm, jobs)
we.RegisterHandler(c, r, tm, jobs, ds)

// Render templates
err = tm.Init()
Expand Down
60 changes: 60 additions & 0 deletions services/embed/domain_settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package embed

import (
"time"

"github.com/go-pg/pg/v10"
cs "github.com/webtor-io/common-services"
"github.com/webtor-io/lazymap"
"github.com/webtor-io/web-ui-v2/services/claims"
"github.com/webtor-io/web-ui-v2/services/models"
)

type DomainSettings struct {
lazymap.LazyMap
pg *cs.PG
claims *claims.Claims
}
type DomainSettingsData struct {
Ads bool `json:"ads"`
}

func NewDomainSettings(pg *cs.PG, claims *claims.Claims) *DomainSettings {
return &DomainSettings{
pg: pg,
claims: claims,
LazyMap: lazymap.New(&lazymap.Config{
Expire: time.Minute,
ErrorExpire: 10 * time.Second,
}),
}
}

func (s *DomainSettings) get(domain string) (*DomainSettingsData, error) {
if s.pg == nil || s.pg.Get() == nil || s.claims == nil {
return &DomainSettingsData{}, nil
}
db := s.pg.Get()
em := &models.EmbedDomain{}
err := db.Model(em).Where("domain = ?", domain).Select()
if err == pg.ErrNoRows {
return &DomainSettingsData{Ads: true}, nil
} else if err != nil {
return nil, err
}
cl, err := s.claims.Get(em.Email)
if err != nil {
return nil, err
}
return &DomainSettingsData{Ads: em.Ads || !cl.Claims.Embed.NoAds}, nil
}

func (s *DomainSettings) Get(domain string) (*DomainSettingsData, error) {
resp, err := s.LazyMap.Get(domain, func() (interface{}, error) {
return s.get(domain)
})
if err != nil {
return nil, err
}
return resp.(*DomainSettingsData), nil
}
17 changes: 17 additions & 0 deletions services/models/embed_domain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package models

import (
"time"

uuid "github.com/satori/go.uuid"
)

type EmbedDomain struct {
tableName struct{} `pg:"embed_domain"`
ID uuid.UUID `pg:"embed_domain_id,type:uuid,pk,default:uuid_generate_v4()"`
Domain string
Email string
Ads bool
CreatedAt time.Time
UpdatedAt time.Time
}
5 changes: 4 additions & 1 deletion services/web/embed/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@ package embed
import (
"github.com/gin-gonic/gin"
"github.com/urfave/cli"
"github.com/webtor-io/web-ui-v2/services/embed"
"github.com/webtor-io/web-ui-v2/services/template"
j "github.com/webtor-io/web-ui-v2/services/web/job"
)

type Handler struct {
tb template.Builder
jobs *j.Handler
ds *embed.DomainSettings
}

func RegisterHandler(c *cli.Context, r *gin.Engine, tm *template.Manager, jobs *j.Handler) {
func RegisterHandler(c *cli.Context, r *gin.Engine, tm *template.Manager, jobs *j.Handler, ds *embed.DomainSettings) {
h := &Handler{
tb: tm.MustRegisterViews("embed/*"),
jobs: jobs,
ds: ds,
}
r.GET("/embed", h.get)
r.POST("/embed", h.post)
Expand Down
36 changes: 25 additions & 11 deletions services/web/embed/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,26 @@ package embed
import (
"encoding/json"
"net/http"
"net/url"

"github.com/gin-gonic/gin"
"github.com/webtor-io/web-ui-v2/services/api"
"github.com/webtor-io/web-ui-v2/services/embed"
"github.com/webtor-io/web-ui-v2/services/job"
"github.com/webtor-io/web-ui-v2/services/web/job/script"
)

type PostArgs struct {
ID string
Settings *script.EmbedSettings
Claims *api.Claims
ID string
EmbedSettings *script.EmbedSettings
Claims *api.Claims
}

type PostData struct {
ID string
Settings *script.EmbedSettings
Job *job.Job
ID string
EmbedSettings *script.EmbedSettings
DomainSettings *embed.DomainSettingsData
Job *job.Job
}

func (s *Handler) bindPostArgs(c *gin.Context) (*PostArgs, error) {
Expand All @@ -32,9 +35,9 @@ func (s *Handler) bindPostArgs(c *gin.Context) (*PostArgs, error) {
id := c.Query("id")

return &PostArgs{
ID: id,
Settings: &settings,
Claims: api.GetClaimsFromContext(c),
ID: id,
EmbedSettings: &settings,
Claims: api.GetClaimsFromContext(c),
}, nil

}
Expand All @@ -48,8 +51,19 @@ func (s *Handler) post(c *gin.Context) {
return
}
pd.ID = args.ID
pd.Settings = args.Settings
job, err := s.jobs.Embed(c, args.Claims, args.Settings)
u, err := url.Parse(args.EmbedSettings.Referer)
if err != nil {
tpl.HTMLWithErr(err, http.StatusBadRequest, c, pd)
return
}
dsd, err := s.ds.Get(u.Hostname())
if err != nil {
tpl.HTMLWithErr(err, http.StatusBadRequest, c, pd)
return
}
pd.EmbedSettings = args.EmbedSettings
pd.DomainSettings = dsd
job, err := s.jobs.Embed(c, args.Claims, args.EmbedSettings)
if err != nil {
tpl.HTMLWithErr(err, http.StatusBadRequest, c, pd)
return
Expand Down
1 change: 1 addition & 0 deletions services/web/job/script/embed.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type EmbedSettings struct {
StreamSettings
Version string `json:"version"`
Magnet string `json:"magnet"`
Referer string `json:"referer"`
}

type EmbedScript struct {
Expand Down
2 changes: 1 addition & 1 deletion templates/layouts/embed/example.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@
</head>
<body>
{{ template "main" . }}
<script src="https://cdn.jsdelivr.net/npm/@webtor/embed-sdk-js/dist/index.min.js" charset="utf-8" async></script>
<script src="https://cdn.jsdelivr.net/npm/@webtor/embed-sdk-js@0.2.18/dist/index.min.js" charset="utf-8" async></script>
</body>
</html>
2 changes: 2 additions & 0 deletions templates/partials/extend_base.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{{ define "head_extra" }}
{{ end }}
{{ define "get_extra" }}
{{ end }}
{{ define "embed_extra" }}
{{ end }}
Loading

0 comments on commit 9d1fb83

Please sign in to comment.