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": {
"type": "string"
},
"donat_user": {
"type": "string"
},
"duration": {
"type": "integer",
"example": 30
@ -2067,9 +2070,18 @@ const docTemplate = `{
"order_id": {
"type": "string"
},
"play_content": {
"type": "boolean"
},
"scenery": {
"type": "string"
},
"show_name": {
"type": "boolean"
},
"show_text": {
"type": "boolean"
},
"text": {
"type": "string"
},

View File

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

View File

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

View File

@ -333,6 +333,10 @@ type PlayingDonat struct {
Text string `json:"text"`
Amount int `json:"amount"`
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 {
@ -342,6 +346,10 @@ type PlayingDonatResponse struct {
Text string `json:"text"`
Amount int `json:"amount"`
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"`
Scenery string `json:"scenery,omitempty"`

View File

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

View File

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

View File

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