Compare commits

...

5 commits

Author SHA1 Message Date
Dark-Killer228
473d84078a
Merge bf65910730 into be65f81a4a 2025-03-31 18:57:32 +03:00
mrilyew
be65f81a4a
fix(audio, favorites): big patch #1259
# Аудио
- Добавлена вкладка в аудио "загруженное" которую я забыл добавить в
октябре 2023. Она показывает загруженные аудио в порядке возрастания.
Есть так же идеи для вкладок "недавно прослушанное" и "ваши друзья
слушают" (последняя добавит иммерсивности, или как это называется,
персональности на сайт, хотя по факту она просто соберёт id всех друзей
и выдаст их недавние добавления в коллекцию), но тогда будет
нагромождение вкладок и придётся какое то сворачивание добавлять.
- Если аудио больше 10 и ты на странице аудио, то показывается мелкая
кнопка в правом нижнем углу которая развернёт счётчик и пагинатор.
- Если аудио обрабатывается (processed как я назвал в css) то появится
кнопка "всё равно хочу воспроизвести".
- При переключении трека меняется заголовок вкладки
- Если ты вызвал контекстное меню но оно ушло за экран, то оно будет
повыше.

# Уязвимости
- Убрана уязвимость в audio api что можно было посмотреть айди владельца
удалённого аудио. В целом непонятно использование id в тексте ошибки,
поскольку он не должен изменятся и быть обобщённым, по типу access to
audio denied. Но да ладно, коду три года всё таки.
- Удалённый контент заменяется "[deleted]" в /fave. Я бы на самом деле
не добавлял это, но меня испугал последний абзац fixed #1258 поэтому
добавил.
2025-03-28 17:04:13 +03:00
Vladimir Barinov
a12c77083b
fix(links, away) (fixes #1253) 2025-03-16 17:57:21 +03:00
Vladimir Barinov
4815186b79
chore(statistics): change behavior of active users count (#1254) 2025-03-16 17:53:58 +03:00
Vladimir Barinov
9ef7d2d7c4
fix(age): calculation (fixes #1252) 2025-03-16 16:51:05 +03:00
16 changed files with 190 additions and 38 deletions

View file

@ -18,7 +18,7 @@ final class Audio extends VKAPIRequestHandler
if (!$audio) {
$this->fail(0o404, "Audio not found");
} elseif (!$audio->canBeViewedBy($this->getUser())) {
$this->fail(201, "Access denied to audio(" . $audio->getPrettyId() . ")");
$this->fail(201, "Access denied to audio(" . $audio->getId() . ")");
}
# рофлан ебало
@ -201,7 +201,7 @@ final class Audio extends VKAPIRequestHandler
$this->fail(15, "Access denied");
}
if ($uploaded_only) {
if ($uploaded_only && $owner_id == $this->getUser()->getRealId()) {
return DatabaseConnection::i()->getContext()->table("audios")
->where([
"deleted" => false,
@ -283,7 +283,7 @@ final class Audio extends VKAPIRequestHandler
}
$dbCtx = DatabaseConnection::i()->getContext();
if ($uploaded_only == 1) {
if ($uploaded_only == 1 && $owner_id == $this->getUser()->getRealId()) {
if ($owner_id <= 0) {
$this->fail(8, "uploaded_only can only be used with owner_id > 0");
}

View file

@ -41,11 +41,11 @@ trait TRichText
return preg_replace_callback(
"%(([A-z]++):\/\/(\S*?\.\S*?))([\s)\[\]{},\"\'<]|\.\s|$)%",
(function (array $matches): string {
$href = str_replace("#", "&num;", $matches[1]);
$href = rawurlencode(str_replace(";", "&#59;", $href));
$link = str_replace("#", "&num;", $matches[3]);
$href = rawurlencode($matches[1]);
$href = str_replace("%26amp%3B", "%26", $href);
$link = $matches[3];
# this string breaks ampersands
$link = str_replace(";", "&#59;", $link);
# $link = str_replace(";", "&#59;", $link);
$rel = $this->isAd() ? "sponsored" : "ugc";
/*$server_domain = str_replace(':' . $_SERVER['SERVER_PORT'], '', $_SERVER['HTTP_HOST']);

View file

@ -524,7 +524,10 @@ class User extends RowModel
public function getAge(): ?int
{
return (int) floor((time() - $this->getBirthday()->timestamp()) / YEAR);
$birthday = new \DateTime();
$birthday->setTimestamp($this->getBirthday()->timestamp());
$today = new \DateTime();
return (int) $today->diff($birthday)->y;
}
public function get2faSecret(): ?string

View file

@ -157,7 +157,7 @@ class Users
{
return (object) [
"all" => (clone $this->users)->count('*'),
"active" => (clone $this->users)->where("online > 0")->count('*'),
"active" => (clone $this->users)->where("online >= ?", time() - MONTH)->count('*'),
"online" => (clone $this->users)->where("online >= ?", time() - 900)->count('*'),
];
}

View file

@ -78,6 +78,10 @@ final class AudioPresenter extends OpenVKPresenter
} elseif ($mode === "new") {
$audios = $this->audios->getNew();
$audiosCount = $audios->size();
} elseif ($mode === "uploaded") {
$stream = $this->audios->getByUploader($this->user->identity);
$audios = $stream->page($page, 10);
$audiosCount = $stream->size();
} elseif ($mode === "playlists") {
if ($owner < 0) {
$entity = (new Clubs())->get(abs($owner));
@ -130,6 +134,11 @@ final class AudioPresenter extends OpenVKPresenter
}
}
public function renderUploaded()
{
$this->renderList(null, "uploaded");
}
public function renderEmbed(int $owner, int $id): void
{
$audio = $this->audios->getByOwnerAndVID($owner, $id);
@ -841,6 +850,10 @@ final class AudioPresenter extends OpenVKPresenter
$audios = [$found_audio];
$audiosCount = 1;
break;
case "uploaded":
$stream = $this->audios->getByUploader($this->user->identity);
$audios = $stream->page($page, $perPage);
$audiosCount = $stream->size();
}
$pagesCount = ceil($audiosCount / $perPage);

View file

@ -20,7 +20,7 @@ final class AwayPresenter extends OpenVKPresenter
header("HTTP/1.0 302 Found");
header("X-Robots-Tag: noindex, nofollow, noarchive");
header("Location: " . $this->queryParam("to"));
header("Location: " . rawurldecode($this->queryParam("to")));
exit;
}

View file

@ -9,6 +9,8 @@
{/if}
{elseif $mode == 'new'}
{_audio_new}
{elseif $mode == 'uploaded'}
{_my_audios_small_uploaded}
{elseif $mode == 'popular'}
{_audio_popular}
{elseif $mode == 'alone_audio'}
@ -32,6 +34,12 @@
</div>
</div>
<div n:if="$mode == 'uploaded'">
{_my_audios_small}
»
{_my_audios_small_uploaded}
</div>
<div n:if="$mode == 'new'">
{_audios}
»
@ -58,7 +66,7 @@
{block content}
{* ref: https://archive.li/P32em *}
{include "bigplayer.xml"}
{include "bigplayer.xml", buttonsShow_summary => $audiosCount > 10}
<script>
window.__current_page_audio_context = null
@ -68,6 +76,12 @@
entity_id: {$ownerId},
page: {$page}
}
{elseif $mode == 'uploaded'}
window.__current_page_audio_context = {
name: 'uploaded',
entity_id: 0,
page: {$page}
}
{elseif $mode == 'alone_audio'}
window.__current_page_audio_context = {
name: 'alone_audio',
@ -77,6 +91,22 @@
{/if}
</script>
<div class='summaryBarHideable summaryBar summaryBarFlex padding' style="margin: 0px -10px;width: 99.5%;display: none;">
<div class='summary'>
<b>{tr("is_x_audio", $audiosCount)}</b>
</div>
{include "../components/paginator.xml", conf => (object) [
"page" => $page,
"count" => $audiosCount,
"amount" => sizeof($audios),
"perPage" => $perPage ?? OPENVK_DEFAULT_PER_PAGE,
"atTop" => true,
"space" => 6,
"tidy" => true,
]}
</div>
<div class="audiosDiv">
<div class="audiosContainer audiosSideContainer audiosPaddingContainer" n:if="$mode != 'playlists'">
<div n:if="$audiosCount <= 0" style='height: 100%;'>

View file

@ -52,5 +52,9 @@
<div class="shuffleButton musicIcon" data-tip='simple' data-title="{_shuffle_tip}"></div>
<div class="deviceButton musicIcon" data-tip='simple' data-title="{_mute_tip} [M]"></div>
</div>
<div class="absoluteButtons">
<div n:if="$buttonsShow_summary" id="summarySwitchButton">-</div>
</div>
</div>
</div>

View file

@ -2,6 +2,7 @@
<div class="verticalGrayTabs">
<div class='with_padding'>
<a n:if="isset($thisUser)" n:attr="id => $mode === 'list' && $isMy ? 'used' : 'ki'" href="/audios{$thisUser->getId()}">{_my_music}</a>
<a n:attr="id => $mode === 'uploaded' ? 'used' : 'ki'" href="/audios/uploaded">{_my_audios_small_uploaded}</a>
{* TODO: show upload link as and plusick (little plus) in button up*}
<a n:if="isset($thisUser)" href="/player/upload{if $isMyClub}?gid={abs($ownerId)}{/if}">{_upload_audio}</a>
<a n:if="isset($thisUser)" n:attr="id => $mode === 'new' ? 'used' : 'ki'" href="/search?section=audios">{_audio_new}</a>
@ -13,7 +14,7 @@
<a n:if="isset($thisUser)" href="/audios/newPlaylist">{_new_playlist}</a>
{if !$isMy && $mode !== 'popular' && $mode !== 'new' && $mode != 'alone_audio'}
{if !$isMy && $mode !== 'popular' && $mode !== 'new' && $mode != 'alone_audio' && $mode != 'uploaded'}
<hr>
<a n:if="!$isMy" n:attr="id => $mode === 'list' ? 'used' : 'ki'" href="/audios{$ownerId}">{if $ownerId > 0}{_music_user}{else}{_music_club}{/if}</a>

View file

@ -36,24 +36,30 @@
</style>
{if $count > 0}
{foreach $data as $dat}
{if $section == "posts"}
<div class="scroll_node">
{include "../components/post.xml", post => $dat, commentSection => true}
</div>
{elseif $section == "comments"}
<div class="scroll_node">
{include "../components/comment.xml", comment => $dat, correctLink => true, no_reply_button => true}
</div>
{elseif $section == "photos"}
<div class="album-photo scroll_node" onclick="OpenMiniature(event, {$dat->getURLBySizeId('larger')}, null, {$dat->getPrettyId()}, null)">
<a href="/photo{$dat->getPrettyId()}">
<img class="album-photo--image" src="{$dat->getURLBySizeId('tinier')}" alt="{$dat->getDescription()}" loading="lazy" />
</a>
</div>
{elseif $section == "videos"}
<div class="scroll_node">
{include "../components/video.xml", video => $dat}
{if $dat->isDeleted()}
<div n:class="deleted_mark, $section == 'photos' ? album-photo : deleted_mark_average">
<span>[deleted]</span>
</div>
{else}
{if $section == "posts"}
<div class="scroll_node">
{include "../components/post.xml", post => $dat, commentSection => true}
</div>
{elseif $section == "comments"}
<div class="scroll_node">
{include "../components/comment.xml", comment => $dat, correctLink => true, no_reply_button => true}
</div>
{elseif $section == "photos"}
<div class="album-photo scroll_node" onclick="OpenMiniature(event, {$dat->getURLBySizeId('larger')}, null, {$dat->getPrettyId()}, null)">
<a href="/photo{$dat->getPrettyId()}">
<img class="album-photo--image" src="{$dat->getURLBySizeId('tinier')}" alt="{$dat->getDescription()}" loading="lazy" />
</a>
</div>
{elseif $section == "videos"}
<div class="scroll_node">
{include "../components/video.xml", video => $dat}
</div>
{/if}
{/if}
{/foreach}
{else}

View file

@ -201,6 +201,8 @@ routes:
handler: "Audio->upload"
- url: "/audios{num}"
handler: "Audio->list"
- url: "/audios/uploaded"
handler: "Audio->uploaded"
- url: "/audio{num}/listen"
handler: "Audio->listen"
- url: "/audio{num}_{num}"

View file

@ -52,6 +52,34 @@
height: 46px;
}
.bigPlayer .bigPlayerWrapper .absoluteButtons {
position: absolute;
bottom: 0;
right: 0;
}
.bigPlayer .bigPlayerWrapper .absoluteButtons > div {
width: 8px;
height: 8px;
font-size: 9px;
display: flex;
align-items: center;
justify-content: center;
background: #ebebeb;
border: 1px solid #c3c3c3;
border-bottom: unset;
border-right: unset;
color: #c3c3c3;
cursor: pointer;
user-select: none;
}
.bigPlayer .bigPlayerWrapper .absoluteButtons > div:active {
background: #c3c3c3;
color: #ebebeb;
}
/* Play button and arrows */
.bigPlayer .playButtons {
display: flex;
@ -313,7 +341,7 @@
opacity: 0.8;
}
.audioEmbed.processed {
.audioEmbed.processed .playerButton {
filter: opacity(0.6);
}

View file

@ -3039,6 +3039,10 @@ a.poll-retract-vote {
gap: 1px;
}
.verticalGrayTabsPad {
padding: 0px 0px 0px 8px;
}
.searchList hr, .verticalGrayTabs hr {
width: 153px;
margin-left: 0px;
@ -4278,3 +4282,7 @@ hr {
height: 30px;
background-position-y: 9px;
}
.deleted_mark_average {
padding: 5px 61px;
}

View file

@ -54,6 +54,9 @@ window.player = new class {
current_track_id = 0
tracks = []
// time type:
// 0 - shows remaining time before end
// 1 - shows full track time
get timeType() {
return localStorage.getItem('audio.timeType') ?? 0
}
@ -62,6 +65,7 @@ window.player = new class {
localStorage.setItem('audio.timeType', value)
}
// <audio> tag
get audioPlayer() {
return this.__realAudioPlayer
}
@ -231,6 +235,9 @@ window.player = new class {
'query': this.context.object.query,
}))
break
case "uploaded":
form_data.append('context', this.context.object.name)
break
case 'alone_audio':
form_data.append('context', this.context.object.name)
form_data.append('context_entity', this.context.object.entity_id)
@ -322,6 +329,8 @@ window.player = new class {
this.__updateFace()
u(this.audioPlayer).trigger('volumechange')
document.title = ovk_proc_strtr(escapeHtml(`${window.player.currentTrack.performer}${window.player.currentTrack.name}`), 255)
}
hasContext() {
@ -377,7 +386,7 @@ window.player = new class {
}
await this.setTrack(this.previousTrack.id)
if(!this.currentTrack.available || this.currentTrack.withdrawn) {
if(/*!this.currentTrack.available || */this.currentTrack.withdrawn) {
if(!this.previousTrack) {
return
}
@ -394,7 +403,7 @@ window.player = new class {
}
await this.setTrack(this.nextTrack.id)
if(!this.currentTrack.available || this.currentTrack.withdrawn) {
if(/*!this.currentTrack.available || */this.currentTrack.withdrawn) {
if(!this.nextTrack) {
return
}
@ -652,7 +661,7 @@ window.player = new class {
this.uiPlayer.find(".trackInfo .elapsedTime").html(getRemainingTime(this.currentTrack.length, new_time))
}
}
__updateMediaSession() {
const album = document.querySelector(".playlistBlock")
const cur = this.currentTrack
@ -664,6 +673,8 @@ window.player = new class {
})
}
// the listen counts if you reach half of song
// but it doesnt checks on server normally so you can "накрутить" listens
async __countListen() {
let playlist = 0
if(!this.listen_coef) {
@ -787,6 +798,10 @@ window.player = new class {
}
})
}
toggleSummary() {
$(".summaryBarHideable").slideToggle(300, "linear")
}
}
document.addEventListener("DOMContentLoaded", async () => {
@ -1163,7 +1178,25 @@ u(document).on("drop", '.audiosContainer', function(e) {
}
})
u(document).on("click", "#summarySwitchButton", (e) => {
if(u(".summaryBarHideable").nodes[0].style.overflow == "hidden") {
return
}
if(u(e.target).html() == "-") {
u(e.target).html("+")
} else {
u(e.target).html("-")
}
window.player.toggleSummary()
})
u(document).on('contextmenu', '.bigPlayer, .audioEmbed, #ajax_audio_player', (e) => {
if(e.shiftKey) {
return
}
e.preventDefault()
u('#ctx_menu').remove()
@ -1179,6 +1212,10 @@ u(document).on('contextmenu', '.bigPlayer, .audioEmbed, #ajax_audio_player', (e)
x = e.pageX - rx
y = e.pageY - ry
if((rect.height + rect.top) + 100 > window.innerHeight) {
y = ((rect.height + 120) * -1)
}
const ctx_u = u(`
<div id='ctx_menu' style='top:${y}px;left:${x}px;' data-type='ctx_type'>
<a id='audio_ctx_copy'>${tr('copy_link_to_audio')}</a>
@ -1194,7 +1231,7 @@ u(document).on('contextmenu', '.bigPlayer, .audioEmbed, #ajax_audio_player', (e)
<a id='audio_ctx_add_to_playlist'>${tr('audio_ctx_add_to_playlist')}</a>
${ctx_type == 'main_player' ? `
<a id='audio_ctx_clear_context'>${tr('audio_ctx_clear_context')}</a>` : ''}
${ctx_type == 'main_player' ? `<a href='https://github.com/mrilyew' target='_blank'>BigPlayer v1.1 by MrIlyew</a>` : ''}
${ctx_type == 'main_player' ? `<a href='https://github.com/mrilyew' target='_blank'>BigPlayer v1.2 by MrIlyew</a>` : ''}
</div>
`)
u(parent).append(ctx_u)
@ -1948,8 +1985,12 @@ $(document).on("click", ".audioEmbed.processed .playerButton", (e) => {
title: tr('error'),
body: tr('audio_embed_processing'),
unique_name: 'processing_notify',
buttons: [tr('ok')],
callbacks: [Function.noop]
buttons: [tr("audio_embed_processing_bait"), tr('ok')],
callbacks: [() => {
const pl = u(e.target).closest(".audioEmbed")
pl.removeClass("processed")
pl.find(".playIcon").trigger("click")
}, Function.noop]
})
})

View file

@ -928,7 +928,8 @@
"audio_embed_deleted" = "Audio has been deleted";
"audio_embed_withdrawn" = "The audio has been withdrawn at the request of the copyright holder";
"audio_embed_forbidden" = "The user's privacy settings do not allow this audio to be embedded";
"audio_embed_processing" = "Audio is still being processed or has not been processed correctly.";
"audio_embed_processing" = "Audio is processing.";
"audio_embed_processing_bait" = "Play anyway";
"audios_count_zero" = "No audios";
"audios_count_one" = "One audio";
@ -947,6 +948,7 @@
"audio_search" = "Search";
"my_audios_small" = "My audios";
"my_audios_small_uploaded" = "Uploaded";
"my_playlists" = "My playlists";
"playlists" = "Playlists";
"audios_explicit" = "Contains obscene language";
@ -1038,6 +1040,12 @@
"audio_ctx_play_next" = "Play next";
"audio_ctx_clear_context" = "Clear tracks list";
"is_x_audio_zero" = "No audios";
"is_x_audio_one" = "Just one audio.";
"is_x_audio_few" = "Just $1 audios.";
"is_x_audio_many" = "Just $1 audios.";
"is_x_audio_other" = "Just $1 audios.";
/* Notifications */
"feedback" = "Feedback";

View file

@ -883,7 +883,8 @@
"audio_embed_deleted" = "Аудиозапись была удалена";
"audio_embed_withdrawn" = "Аудиозапись была изъята по обращению правообладателя.";
"audio_embed_forbidden" = "Настройки приватности пользователя не позволяют встраивать эту композицию";
"audio_embed_processing" = "Аудио ещё обрабатывается, либо обработалось неправильно.";
"audio_embed_processing" = "Аудио находится в обработке.";
"audio_embed_processing_bait" = "Всё равно хочу воспроизвести";
"audios_count_zero" = "Нет аудиозаписей";
"audios_count_one" = "Одна аудиозапись"; /* сингл */
@ -902,6 +903,7 @@
"audio_search" = "Поиск";
"my_audios_small" = "Мои аудиозаписи";
"my_audios_small_uploaded" = "Загруженное";
"my_playlists" = "Мои плейлисты";
"playlists" = "Плейлисты";
"audios_explicit" = "Содержит нецензурную лексику";
@ -994,6 +996,12 @@
"audio_ctx_play_next" = "Воспроизвести следующим";
"audio_ctx_clear_context" = "Очистить список треков";
"is_x_audio_zero" = "Нету аудиозаписей";
"is_x_audio_one" = "Всего одна аудиозапись.";
"is_x_audio_few" = "Всего $1 аудиозаписи.";
"is_x_audio_many" = "Всего $1 аудиозаписей.";
"is_x_audio_other" = "Всего $1 аудиозаписей.";
/* Notifications */
"feedback" = "Ответы";