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

@ -327,21 +327,29 @@ type MarkDonatViewed struct {
} }
type PlayingDonat struct { type PlayingDonat struct {
Duration int `json:"duration" example:"30"` Duration int `json:"duration" example:"30"`
Image *string `json:"image_link"` Image *string `json:"image_link"`
Audio *string `json:"audio_link"` Audio *string `json:"audio_link"`
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 {
Duration int `json:"duration" example:"30"` Duration int `json:"duration" example:"30"`
Image *string `json:"image_link"` Image *string `json:"image_link"`
Audio *string `json:"audio_link"` Audio *string `json:"audio_link"`
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,79 +81,6 @@ function createTextWithAmount(text, amount) {
return container; return container;
} }
async function getDonatInfo(streamerID) {
try {
let response = await fetch(widgetUrl + '/widget/get-donat-for-playing/' + streamerID);
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
return null;
}
}
function playAudio(url, callback, volume) {
const audio = new Audio(url);
audio.volume = volume;
audio.play().then(() => {
audio.addEventListener('ended', callback);
}).catch(error => {
console.error('Error playing audio:', error);
callback();
});
}
function playSpeech(text, voiceSettings) {
if (!voiceSettings.voice_enabled) return;
const requestBody = {
text: text,
speed: (voiceSettings.voice_speed || 'medium').toLowerCase(),
scenery: voiceSettings.scenery || 'default',
sound_percent: voiceSettings.voice_sound_percent || 100,
min_price: voiceSettings.min_price || 0,
languages: voiceSettings.languages || ['ru']
};
fetch(ttsUrl + '/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
if (!response.ok) throw new Error('TTS error');
return response.blob();
})
.then(blob => {
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
audio.volume = (voiceSettings.voice_sound_percent || 100) / 100;
audio.play().catch(console.error);
audio.addEventListener('ended', () => {
URL.revokeObjectURL(url);
});
})
.catch(console.error);
}
function playSpeechAfterAudio(audioUrl, text, voiceSettings) {
const volume = (voiceSettings.voice_sound_percent || 100) / 100;
playAudio(audioUrl, () => playSpeech(text, voiceSettings), volume);
}
function clearContainer(container) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
}
function addImage(container, imageUrl) {
const img = document.createElement('img');
img.src = imageUrl;
container.appendChild(img);
}
function createTextElement(text) { function createTextElement(text) {
const container = document.createElement('div'); const container = document.createElement('div');
container.className = 'text-container'; container.className = 'text-container';
@ -159,10 +91,93 @@ function createTextElement(text) {
return container; return container;
} }
async function getDonatInfo(streamerID) {
try {
let response = await fetch(widgetUrl + '/widget/get-donat-for-playing/' + streamerID);
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
return null;
}
}
function playAudio(url, volume) {
return new Promise((resolve, reject) => {
const audio = new Audio(url);
audio.volume = volume;
audio.play().then(() => {
audio.addEventListener('ended', resolve);
}).catch(error => {
console.error('Error playing audio:', error);
reject(error);
});
});
}
function playSpeech(text, voiceSettings) {
return new Promise((resolve, reject) => {
if (!voiceSettings.voice_enabled) return resolve();
const requestBody = {
text: text,
speed: (voiceSettings.voice_speed || 'medium').toLowerCase(),
scenery: voiceSettings.scenery || 'default',
sound_percent: voiceSettings.voice_sound_percent || 100,
min_price: voiceSettings.min_price || 0,
languages: voiceSettings.languages || ['ru']
};
fetch(ttsUrl + '/generate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(requestBody)
})
.then(response => {
if (!response.ok) throw new Error('TTS error');
return response.blob();
})
.then(blob => {
const url = URL.createObjectURL(blob);
const audio = new Audio(url);
audio.volume = (voiceSettings.voice_sound_percent || 100) / 100;
audio.play().catch(reject);
audio.addEventListener('ended', () => {
URL.revokeObjectURL(url);
resolve();
});
})
.catch(reject);
});
}
async function playMedia(donat, voiceSettings) {
try {
let mediaPromise = Promise.resolve();
const volume = (voiceSettings.voice_sound_percent || 100) / 100;
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) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
}
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!');
@ -171,10 +186,9 @@ async function widgetView() {
while (true) { while (true) {
const iterationStart = Date.now(); const iterationStart = Date.now();
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,39 +229,30 @@ 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 remaining = REQUEST_INTERVAL - elapsed; const elapsed = Date.now() - iterationStart;
if (remaining > 0) { const remaining = 5000 - elapsed;
await new Promise(r => setTimeout(r, remaining)); if (remaining > 0) {
} await new Promise(r => setTimeout(r, remaining));
} }
} }
} }

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

@ -718,12 +718,16 @@ func (donatService *ServiceDonat) GetPlayingDonat(
} }
response := model.PlayingDonatResponse{ response := model.PlayingDonatResponse{
Duration: playingDonat.Duration, Duration: playingDonat.Duration,
Image: playingDonat.Image, Image: playingDonat.Image,
Audio: playingDonat.Audio, Audio: playingDonat.Audio,
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)