Skip to content

Commit

Permalink
embed: add control, external poster and subtitles
Browse files Browse the repository at this point in the history
  • Loading branch information
vintikzzz committed May 18, 2024
1 parent 36978f2 commit fecd07a
Show file tree
Hide file tree
Showing 22 changed files with 330 additions and 91 deletions.
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ WORKDIR /app
COPY --from=build /app/server .
# copy templates
COPY --from=build /app/templates ./templates
# copy pub
COPY --from=build /app/pub ./pub
# copy assets
COPY --from=build_assets /app/assets/dist ./assets/dist

Expand Down
26 changes: 17 additions & 9 deletions assets/src/js/app/embed/check.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import message from './message';
const sha1 = require('sha1');
message.send('init');
const init = await message.receiveOnce('init');
const data = await message.receiveOnce('init');
const c = await check();
if (c) {
if (!init.height) {
initPlaceholder(data);
window.addEventListener('click', async () => {
initEmbed(data);
}, { once: true });
}

function initPlaceholder(data) {
if (!data.height) {
function setHeight() {
const width = document.body.offsetWidth;
const height = width/16*9;
const height = width / 16 * 9;
document.body.style.height = height + 'px';
}
window.addEventListener('resize', setHeight);
Expand All @@ -16,11 +23,12 @@ if (c) {
document.body.appendChild(s);
setHeight();
} else {
document.body.style.height = init.height;
document.body.style.height = data.height;
}
if (data.poster) {
document.body.style.backgroundImage = 'url(' + data.poster + ')';
document.body.style.backgroundSize = 'cover';
}
window.addEventListener('click', async () => {
initEmbed(init);
}, {once: true});
}

async function check() {
Expand All @@ -29,7 +37,7 @@ async function check() {
return sha1(window._id + check) == _checkHash;
}

function initEmbed(init) {
function initEmbed(data) {
const form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
Expand All @@ -39,7 +47,7 @@ function initEmbed(init) {
form.append(csrf);
const i = document.createElement('input');
i.setAttribute('name', 'settings');
i.setAttribute('value', JSON.stringify(init));
i.setAttribute('value', JSON.stringify(data));
form.append(i);
document.body.append(form);
// form.setAttribute('action', '/');
Expand Down
4 changes: 4 additions & 0 deletions assets/src/js/app/embed/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,8 @@ window.addEventListener('load', async () => {
}
setHeight();
window.addEventListener('resize', setHeight);
if (window._settings.poster) {
document.body.style.backgroundImage = 'url(' + window._settings.poster + ')';
document.body.style.backgroundSize = 'cover';
}
});
9 changes: 7 additions & 2 deletions assets/src/js/app/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import '../../styles/style.css';

import {bindAsync} from '../lib/async';

window.addEventListener('load', async () => {
function onLoad() {
document.body.style.display = 'block';
hideProgress();
bindAsync({
Expand All @@ -33,4 +33,9 @@ window.addEventListener('load', async () => {
layout: 'async',
},
});
});
}

if (document.readyState !== 'loading') {
onLoad();
}
window.addEventListener('DOMContentLoaded', onLoad);
13 changes: 9 additions & 4 deletions assets/src/js/lib/mediaelement.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,15 @@ let video;

export function initPlayer(target, ready) {
video = target.querySelector('.player');
const width = window._settings?.width;
const height = window._settings?.height;
const width = video.width;
const height = video.height;
const controls = video.controls;
const stretching = height ? 'auto' : 'responsive';
if (stretching == 'auto') {
if (width) video.setAttribute('width', width);
if (height) video.setAttribute('height', height);
}

const duration = video.getAttribute('data-duration') ? parseFloat(video.getAttribute('data-duration')) : -1;
const features = [
'playpause',
Expand Down Expand Up @@ -122,7 +124,7 @@ export function initPlayer(target, ready) {
manifestLoadingMaxRetryTimeout: 1000 * 10,
capLevelToPlayerSize: true,
capLevelOnFPSDrop: true,
// progressive: true,
progressive: true,
testBandwidth: false,
path: '/assets/lib/hls.min.js',
},
Expand Down Expand Up @@ -150,7 +152,6 @@ export function initPlayer(target, ready) {
}
}
media.addEventListener('canplay', () => {

if (hlsPlayer && document.getElementById('subtitles')) {
const audioId = document.querySelector('.audio[data-default=true]').getAttribute('data-mp-id');
const subId = document.querySelector('.subtitle[data-default=true]').getAttribute('data-mp-id');
Expand All @@ -161,6 +162,10 @@ export function initPlayer(target, ready) {
if (width) player.node.style.width = width;
if (height) player.node.style.height = height;
}
player.controlsEnabled = controls;
if (!controls) {
document.querySelector('.mejs__controls').style.display = 'none';
}
ready();
});
if (media.hlsPlayer) {
Expand Down
1 change: 1 addition & 0 deletions assets/src/styles/embed.css
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
@apply py-4 popin;
position: relative;
color: white;
background: rgba(0, 0, 0, 0.5);

pre {
@apply px-5 leading-8 whitespace-pre-wrap flex;
Expand Down
Binary file added pub/Sintel.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
110 changes: 110 additions & 0 deletions pub/Sintel.ru.srt
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@

1
00:01:47,250 --> 00:01:50,500
О! Это копьё с темным прошлым.

2
00:01:51,800 --> 00:01:55,800
Его лезвие выпило немало невинной крови.

3
00:01:58,000 --> 00:02:01,450
Только глупец путешествует в одиночку,
да еще без оружия.

4
00:02:01,750 --> 00:02:04,800
Тебе повезло, что осталась жива.

5
00:02:05,250 --> 00:02:06,300
Спасибо.

6
00:02:07,500 --> 00:02:09,000
Раскажи,

7
00:02:09,400 --> 00:02:13,800
что привело тебя в страну
хранителей?

8
00:02:15,000 --> 00:02:17,500
Я ищу кое кого.

9
00:02:18,000 --> 00:02:22,200
Кого-то очень дорогого?
Родственную душу?

10
00:02:23,400 --> 00:02:25,000
Дракона.

11
00:02:28,850 --> 00:02:31,750
Опасное занятие для одиночки.

12
00:02:32,950 --> 00:02:35,870
Сколько себя помню,
я всегда была одна.

13
00:03:27,250 --> 00:03:30,500
Уже почти всё. Шшшш...

14
00:03:30,750 --> 00:03:33,500
Спокойно!

15
00:03:48,250 --> 00:03:52,250
Спокойной ночи, Чешуйчик.

16
00:04:10,350 --> 00:04:13,850
Взять, Чешуйчик! Давай!

17
00:04:25,250 --> 00:04:28,250
Чешуйчик?

18
00:05:04,000 --> 00:05:07,500
Да! Давай!

19
00:05:38,750 --> 00:05:42,000
Чешуйчик!

20
00:07:25,850 --> 00:07:27,500
У меня ничего не получилось.

21
00:07:32,800 --> 00:07:36,500
Не получилось только понять,

22
00:07:37,800 --> 00:07:40,500
что ты дошла до земли драконов, Синтэль.

23
00:07:40,850 --> 00:07:44,000
И теперь ближе к цели,
чем ты думаешь.

24
00:09:17,600 --> 00:09:19,500
Чешуйчик!

25
00:10:21,600 --> 00:10:24,000
Чешуйчик?

26
00:10:26,200 --> 00:10:29,800
Чешуйчик...

39 changes: 35 additions & 4 deletions services/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"bytes"
"context"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -479,12 +480,42 @@ func (s *Api) makeSubtitleURL(u string, esub ExtSubtitle) string {
pathParts := strings.Split(src.Path, "/")
pathParts = pathParts[:len(pathParts)-1]
path = strings.Join(pathParts, "/") + esub.Src
src.Path = path
res := src.String()
if esub.Format == "srt" {
nameParts := strings.Split(esub.Src, "/")
name := strings.Join(nameParts[len(nameParts)-1:], "/")
path += "~vtt/" + strings.TrimSuffix(name, ".srt") + ".vtt"
res = s.convertToVTT(res)
}
src.Path = path
return res
}

func (*Api) convertToVTT(u string) string {
src, _ := url.Parse(u)
nameParts := strings.Split(src.Path, "/")
name := strings.Join(nameParts[len(nameParts)-1:], "/")
src.Path += "~vtt/" + strings.TrimSuffix(name, ".srt") + ".vtt"
return src.String()
}

func (s *Api) AttachExternalSubtitle(ei ra.ExportItem, u string) string {
res := s.AttachExternalFile(ei, u)
format := "vtt"

src, _ := url.Parse(u)
if strings.HasSuffix(src.Path, ".srt") {
format = "srt"
}
if format == "srt" {
res = s.convertToVTT(res)
}
return res
}

func (s *Api) AttachExternalFile(ei ra.ExportItem, u string) string {
src, _ := url.Parse(ei.URL)
nameParts := strings.Split(u, "/")
name := strings.Join(nameParts[len(nameParts)-1:], "/")
encodedURL := url.QueryEscape(base64.StdEncoding.EncodeToString([]byte(u)))
src.Path = fmt.Sprintf("/ext/%s/%s", encodedURL, name)
return src.String()
}

Expand Down
13 changes: 13 additions & 0 deletions services/models/video_stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package models

import (
"fmt"

"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"golang.org/x/text/language"
Expand Down Expand Up @@ -65,3 +66,15 @@ func (s *VideoStreamUserData) UpdateSessionData(c *gin.Context) error {
}
return session.Save()
}

type ExternalData struct {
Poster string
Tracks []ExternalTrack
}

type ExternalTrack struct {
Src string
SrcLang string
Label string
Default bool
}
3 changes: 3 additions & 0 deletions services/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type View struct {
err error
re multitemplate.Renderer
templateName string
mux sync.Mutex
}

func (s *View) makeTemplate() (t *template.Template, err error) {
Expand Down Expand Up @@ -77,6 +78,8 @@ func (s *View) Render() (string, error) {
if s.err != nil {
return
}
s.mux.Lock()
defer s.mux.Unlock()
s.re.Add(s.templateName, t)
}
if gin.IsDebugging() {
Expand Down
18 changes: 17 additions & 1 deletion services/web/action/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ func (s *Helper) selectListItem(lis []ListItem, id string, ud *m.VideoStreamUser
langs = append(langs, t)
}
}
for _, li := range lis {
if li.Default {
return lis
}
}
matcher := language.NewMatcher(langs)
_, index, confidence := matcher.Match(ud.AcceptLangTags...)
if confidence > language.No {
Expand All @@ -108,7 +113,7 @@ func (s *Helper) canoninizeSrcLangs(lis []ListItem) []ListItem {
return lis
}

func (s *Helper) GetSubtitles(ud *m.VideoStreamUserData, mp *api.MediaProbe, tag *ra.ExportTag, opensubs []api.OpenSubtitleTrack) []ListItem {
func (s *Helper) GetSubtitles(ud *m.VideoStreamUserData, mp *api.MediaProbe, tag *ra.ExportTag, opensubs []api.OpenSubtitleTrack, ext *m.ExternalData) []ListItem {
var res []ListItem
res = append(res, ListItem{
ID: "none",
Expand Down Expand Up @@ -159,5 +164,16 @@ func (s *Helper) GetSubtitles(ud *m.VideoStreamUserData, mp *api.MediaProbe, tag
Provider: "OpenSubtitles",
})
}
for i, t := range ext.Tracks {
res = append(res, ListItem{
ID: "ext-" + strconv.Itoa(i+1),
Label: t.Label,
SrcLang: t.SrcLang,
Default: t.Default,
Kind: "subtitles",
Src: t.Src,
Provider: "External",
})
}
return s.selectListItem(s.canoninizeSrcLangs(res), ud.SubtitleID, ud)
}
Loading

0 comments on commit fecd07a

Please sign in to comment.