add fix for template donat

This commit is contained in:
harold 2025-04-29 23:17:40 +05:00
parent be57a14ca5
commit 81e7cd2082
8 changed files with 193 additions and 130 deletions

View File

@ -2048,6 +2048,9 @@ const docTemplate = `{
"audio_link": { "audio_link": {
"type": "string" "type": "string"
}, },
"donat_user": {
"type": "string"
},
"duration": { "duration": {
"type": "integer", "type": "integer",
"example": 30 "example": 30
@ -2067,9 +2070,18 @@ const docTemplate = `{
"order_id": { "order_id": {
"type": "string" "type": "string"
}, },
"play_content": {
"type": "boolean"
},
"scenery": { "scenery": {
"type": "string" "type": "string"
}, },
"show_name": {
"type": "boolean"
},
"show_text": {
"type": "boolean"
},
"text": { "text": {
"type": "string" "type": "string"
}, },

View File

@ -2041,6 +2041,9 @@
"audio_link": { "audio_link": {
"type": "string" "type": "string"
}, },
"donat_user": {
"type": "string"
},
"duration": { "duration": {
"type": "integer", "type": "integer",
"example": 30 "example": 30
@ -2060,9 +2063,18 @@
"order_id": { "order_id": {
"type": "string" "type": "string"
}, },
"play_content": {
"type": "boolean"
},
"scenery": { "scenery": {
"type": "string" "type": "string"
}, },
"show_name": {
"type": "boolean"
},
"show_text": {
"type": "boolean"
},
"text": { "text": {
"type": "string" "type": "string"
}, },

View File

@ -401,6 +401,8 @@ definitions:
type: integer type: integer
audio_link: audio_link:
type: string type: string
donat_user:
type: string
duration: duration:
example: 30 example: 30
type: integer type: integer
@ -414,8 +416,14 @@ definitions:
type: integer type: integer
order_id: order_id:
type: string type: string
play_content:
type: boolean
scenery: scenery:
type: string type: string
show_name:
type: boolean
show_text:
type: boolean
text: text:
type: string type: string
voice_enabled: voice_enabled:

View File

@ -333,6 +333,10 @@ type PlayingDonat struct {
Text string `json:"text"` Text string `json:"text"`
Amount int `json:"amount"` Amount int `json:"amount"`
OrderID string `json:"order_id"` OrderID string `json:"order_id"`
DonatUser *string `json:"donat_user"`
PlayContent bool `json:"play_content"`
ShowName bool `json:"show_name"`
ShowText bool `json:"show_text"`
} }
type PlayingDonatResponse struct { type PlayingDonatResponse struct {
@ -342,6 +346,10 @@ type PlayingDonatResponse struct {
Text string `json:"text"` Text string `json:"text"`
Amount int `json:"amount"` Amount int `json:"amount"`
OrderID string `json:"order_id"` OrderID string `json:"order_id"`
DonatUser *string `json:"donat_user"`
PlayContent bool `json:"play_content"`
ShowName bool `json:"show_name"`
ShowText bool `json:"show_text"`
// Добавляем новые поля для настроек голоса // Добавляем новые поля для настроек голоса
VoiceSpeed string `json:"voice_speed,omitempty"` VoiceSpeed string `json:"voice_speed,omitempty"`
Scenery string `json:"scenery,omitempty"` Scenery string `json:"scenery,omitempty"`

View File

@ -555,7 +555,7 @@ VALUES
(@streamer_id, @voice_speed, @voice_sound_percent, @min_price)` (@streamer_id, @voice_speed, @voice_sound_percent, @min_price)`
var GetPlayingDonats = ` var GetPlayingDonats = `
SELECT w.duration, w.image, w.audio, d.text, d.amount, d.order_id SELECT w.duration, w.image, w.audio, d.text, d.amount, d.order_id, d.donat_user, d.
FROM widgets AS w FROM widgets AS w
INNER JOIN INNER JOIN
donats AS d ON d.widget_id = w.id donats AS d ON d.widget_id = w.id

View File

@ -29,6 +29,10 @@ func GetTemplate1(streamerID int, donatHost, ttsHost string) string {
object-fit: contain; object-fit: contain;
border-radius: 15px; border-radius: 15px;
} }
.text-container, .donation-user {
opacity: 0;
animation: fadeIn 2s forwards;
}
.text-container { .text-container {
display: flex; display: flex;
align-items: center; align-items: center;
@ -36,8 +40,11 @@ func GetTemplate1(streamerID int, donatHost, ttsHost string) string {
font-size: 40px; font-size: 40px;
color: #fff; color: #fff;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5); text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
opacity: 0; }
animation: fadeIn 2s forwards; .donation-user {
font-size: 35px;
color: #FFD700;
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
} }
.donation-text { .donation-text {
margin: 0; margin: 0;
@ -50,9 +57,7 @@ func GetTemplate1(streamerID int, donatHost, ttsHost string) string {
border-radius: 8px; border-radius: 8px;
} }
@keyframes fadeIn { @keyframes fadeIn {
to { to { opacity: 1; }
opacity: 1;
}
}` }`
script := fmt.Sprintf(` script := fmt.Sprintf(`
@ -76,6 +81,16 @@ function createTextWithAmount(text, amount) {
return container; return container;
} }
function createTextElement(text) {
const container = document.createElement('div');
container.className = 'text-container';
const textElem = document.createElement('p');
textElem.className = 'donation-text';
textElem.textContent = text;
container.appendChild(textElem);
return container;
}
async function getDonatInfo(streamerID) { async function getDonatInfo(streamerID) {
try { try {
let response = await fetch(widgetUrl + '/widget/get-donat-for-playing/' + streamerID); let response = await fetch(widgetUrl + '/widget/get-donat-for-playing/' + streamerID);
@ -86,19 +101,22 @@ async function getDonatInfo(streamerID) {
} }
} }
function playAudio(url, callback, volume) { function playAudio(url, volume) {
return new Promise((resolve, reject) => {
const audio = new Audio(url); const audio = new Audio(url);
audio.volume = volume; audio.volume = volume;
audio.play().then(() => { audio.play().then(() => {
audio.addEventListener('ended', callback); audio.addEventListener('ended', resolve);
}).catch(error => { }).catch(error => {
console.error('Error playing audio:', error); console.error('Error playing audio:', error);
callback(); reject(error);
});
}); });
} }
function playSpeech(text, voiceSettings) { function playSpeech(text, voiceSettings) {
if (!voiceSettings.voice_enabled) return; return new Promise((resolve, reject) => {
if (!voiceSettings.voice_enabled) return resolve();
const requestBody = { const requestBody = {
text: text, text: text,
@ -111,9 +129,7 @@ function playSpeech(text, voiceSettings) {
fetch(ttsUrl + '/generate', { fetch(ttsUrl + '/generate', {
method: 'POST', method: 'POST',
headers: { headers: {'Content-Type': 'application/json'},
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody) body: JSON.stringify(requestBody)
}) })
.then(response => { .then(response => {
@ -124,17 +140,33 @@ function playSpeech(text, voiceSettings) {
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
const audio = new Audio(url); const audio = new Audio(url);
audio.volume = (voiceSettings.voice_sound_percent || 100) / 100; audio.volume = (voiceSettings.voice_sound_percent || 100) / 100;
audio.play().catch(console.error); audio.play().catch(reject);
audio.addEventListener('ended', () => { audio.addEventListener('ended', () => {
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
resolve();
}); });
}) })
.catch(console.error); .catch(reject);
});
} }
function playSpeechAfterAudio(audioUrl, text, voiceSettings) { async function playMedia(donat, voiceSettings) {
try {
let mediaPromise = Promise.resolve();
const volume = (voiceSettings.voice_sound_percent || 100) / 100; const volume = (voiceSettings.voice_sound_percent || 100) / 100;
playAudio(audioUrl, () => playSpeech(text, voiceSettings), volume);
if (donat.play_content && donat.audio_link) {
mediaPromise = playAudio(donat.audio_link, volume)
.then(() => playSpeech(donat.text, voiceSettings));
} else if (donat.text && donat.voice_enabled) {
mediaPromise = playSpeech(donat.text, voiceSettings);
}
const timeoutPromise = new Promise(r => setTimeout(r, donat.duration * 1000));
await Promise.race([mediaPromise, timeoutPromise]);
} catch (error) {
console.error('Media play error:', error);
}
} }
function clearContainer(container) { function clearContainer(container) {
@ -143,26 +175,9 @@ function clearContainer(container) {
} }
} }
function addImage(container, imageUrl) {
const img = document.createElement('img');
img.src = imageUrl;
container.appendChild(img);
}
function createTextElement(text) {
const container = document.createElement('div');
container.className = 'text-container';
const textElem = document.createElement('p');
textElem.className = 'donation-text';
textElem.textContent = text;
container.appendChild(textElem);
return container;
}
async function widgetView() { async function widgetView() {
const streamerID = '%v'; const streamerID = '%v';
const contentDiv = document.getElementById('content'); const contentDiv = document.getElementById('content');
const REQUEST_INTERVAL = 5000;
if (!contentDiv) { if (!contentDiv) {
console.error('Content container not found!'); console.error('Content container not found!');
@ -174,7 +189,6 @@ async function widgetView() {
try { try {
const donat = await getDonatInfo(streamerID); const donat = await getDonatInfo(streamerID);
if (!donat || Object.keys(donat).length === 0) { if (!donat || Object.keys(donat).length === 0) {
await new Promise(r => setTimeout(r, 5000)); await new Promise(r => setTimeout(r, 5000));
continue; continue;
@ -182,20 +196,30 @@ async function widgetView() {
clearContainer(contentDiv); clearContainer(contentDiv);
// Добавление элементов // Добавление изображения
if (donat.image_link) { if (donat.image_link) {
addImage(contentDiv, donat.image_link); const img = document.createElement('img');
img.src = donat.image_link;
contentDiv.appendChild(img);
} }
// Текст с суммой // Отображение имени пользователя
if (donat.text) { if (donat.show_name && donat.donat_user) {
const textElement = donat.amount const userElem = document.createElement('div');
? createTextWithAmount(donat.text, donat.amount) userElem.className = 'donation-user';
: createTextElement(donat.text); userElem.textContent = donat.donat_user;
contentDiv.appendChild(textElement); contentDiv.appendChild(userElem);
} }
// Настройки голоса и громкости // Отображение текста
if (donat.show_text && donat.text) {
const textElem = donat.amount ?
createTextWithAmount(donat.text, donat.amount) :
createTextElement(donat.text);
contentDiv.appendChild(textElem);
}
// Воспроизведение медиа
const voiceSettings = { const voiceSettings = {
voice_speed: donat.voice_speed, voice_speed: donat.voice_speed,
scenery: donat.scenery, scenery: donat.scenery,
@ -205,41 +229,32 @@ async function widgetView() {
voice_enabled: donat.voice_enabled voice_enabled: donat.voice_enabled
}; };
// Воспроизведение аудио и TTS await playMedia(donat, voiceSettings);
if (donat.audio_link) {
playSpeechAfterAudio(donat.audio_link, donat.text, voiceSettings);
} else if (donat.text && donat.voice_enabled) {
playSpeech(donat.text, voiceSettings);
}
// Таймаут на основе duration // Отправка подтверждения
await new Promise(r => setTimeout(r, donat.duration * 1000));
// Отправка подтверждения просмотра
if (donat.order_id) { if (donat.order_id) {
try { try {
const response = await fetch(widgetUrl + '/widget/donat/viewed', { await fetch(widgetUrl + '/widget/donat/viewed', {
method: 'POST', method: 'POST',
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
body: JSON.stringify({order_id: donat.order_id}), body: JSON.stringify({order_id: donat.order_id}),
}); });
if (!response.ok) console.error('Ошибка подтверждения просмотра');
} catch (error) { } catch (error) {
console.error('Ошибка:', error); console.error('Ошибка подтверждения:', error);
} }
} }
} catch (error) { } catch (error) {
console.error('Ошибка в цикле:', error); console.error('Ошибка обработки доната:', error);
} finally { }
// Гарантируем задержку между итерациями
// Пауза между итерациями
const elapsed = Date.now() - iterationStart; const elapsed = Date.now() - iterationStart;
const remaining = REQUEST_INTERVAL - elapsed; const remaining = 5000 - elapsed;
if (remaining > 0) { if (remaining > 0) {
await new Promise(r => setTimeout(r, remaining)); await new Promise(r => setTimeout(r, remaining));
} }
} }
}
} }
document.addEventListener('DOMContentLoaded', widgetView);`, donatHost, ttsHost, streamerID) document.addEventListener('DOMContentLoaded', widgetView);`, donatHost, ttsHost, streamerID)

View File

@ -844,6 +844,10 @@ func (repoDonat *RepoDonat) GetPlayingDonat(
&donatForPlaying.Text, &donatForPlaying.Text,
&donatForPlaying.Amount, &donatForPlaying.Amount,
&donatForPlaying.OrderID, &donatForPlaying.OrderID,
&donatForPlaying.DonatUser,
&donatForPlaying.PlayContent,
&donatForPlaying.ShowName,
&donatForPlaying.ShowText,
) )
if err != nil { if err != nil {

View File

@ -724,6 +724,10 @@ func (donatService *ServiceDonat) GetPlayingDonat(
Text: playingDonat.Text, Text: playingDonat.Text,
Amount: playingDonat.Amount, Amount: playingDonat.Amount,
OrderID: playingDonat.OrderID, OrderID: playingDonat.OrderID,
DonatUser: playingDonat.DonatUser,
PlayContent: playingDonat.PlayContent,
ShowName: playingDonat.ShowName,
ShowText: playingDonat.ShowText,
} }
filteredSettings, err := donatService.GetFiltersSettings(ctx, streamerID) filteredSettings, err := donatService.GetFiltersSettings(ctx, streamerID)