Skip to content

Commit

Permalink
Posts: add source param (#934)
Browse files Browse the repository at this point in the history
* Chopin

- Полностью переписана та часть где про источник поста
- Исправлен метод video.search
- Сокращено число запросов в БД у шаблона поста
- Удалена ссылка на прикреплятор заметок потому что low quality
- Исправлен баг с прикреплённой заметкой в api, но только если ты указал версию.
- Исправлены проблемы с кешированными спрайтшитами

* Chopin 2
  • Loading branch information
mrilyew authored Nov 1, 2024
1 parent 9b220a8 commit fab39bd
Show file tree
Hide file tree
Showing 25 changed files with 380 additions and 58 deletions.
3 changes: 2 additions & 1 deletion VKAPI/Handlers/Video.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ function search(string $q = '', int $sort = 0, int $offset = 0, int $count = 10,
$return_items = [];
$profiles = [];
$groups = [];
foreach($items as $item)
foreach($items as $item) {
$return_item = $item->getApiStructure($this->getUser());
$return_item = $return_item->video;
$return_items[] = $return_item;
Expand All @@ -85,6 +85,7 @@ function search(string $q = '', int $sort = 0, int $offset = 0, int $count = 10,
else
$groups[] = abs($return_item['owner_id']);
}
}

if($extended) {
$profiles = array_unique($profiles);
Expand Down
102 changes: 94 additions & 8 deletions VKAPI/Handlers/Wall.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,14 @@ function get(int $owner_id, string $domain = "", int $offset = 0, int $count = 3
} else if ($attachment instanceof \openvk\Web\Models\Entities\Video) {
$attachments[] = $attachment->getApiStructure($this->getUser());
} else if ($attachment instanceof \openvk\Web\Models\Entities\Note) {
$attachments[] = $attachment->toVkApiStruct();
if(VKAPI_DECL_VER === '4.100') {
$attachments[] = $attachment->toVkApiStruct();
} else {
$attachments[] = [
'type' => 'note',
'note' => $attachment->toVkApiStruct()
];
}
} else if ($attachment instanceof \openvk\Web\Models\Entities\Audio) {
$attachments[] = [
"type" => "audio",
Expand Down Expand Up @@ -188,6 +195,9 @@ function get(int $owner_id, string $domain = "", int $offset = 0, int $count = 3
]
];

if($post->hasSource())
$post_temp_obj->copyright = $post->getVkApiCopyright();

if($signerId)
$post_temp_obj->signer_id = $signerId;

Expand Down Expand Up @@ -291,7 +301,14 @@ function getById(string $posts, int $extended = 0, string $fields = "", User $us
} else if ($attachment instanceof \openvk\Web\Models\Entities\Video) {
$attachments[] = $attachment->getApiStructure($this->getUser());
} else if ($attachment instanceof \openvk\Web\Models\Entities\Note) {
$attachments[] = $attachment->toVkApiStruct();
if(VKAPI_DECL_VER === '4.100') {
$attachments[] = $attachment->toVkApiStruct();
} else {
$attachments[] = [
'type' => 'note',
'note' => $attachment->toVkApiStruct()
];
}
} else if ($attachment instanceof \openvk\Web\Models\Entities\Audio) {
$attachments[] = [
"type" => "audio",
Expand Down Expand Up @@ -373,6 +390,9 @@ function getById(string $posts, int $extended = 0, string $fields = "", User $us
]
];

if($post->hasSource())
$post_temp_obj->copyright = $post->getVkApiCopyright();

if($signerId)
$post_temp_obj->signer_id = $signerId;

Expand Down Expand Up @@ -543,6 +563,12 @@ function post(string $owner_id, string $message = "", int $from_group = 0, int $
$post->setFlags($flags);
$post->setApi_Source_Name($this->getPlatform());

if(!is_null($copyright) && !empty($copyright)) {
try {
$post->setSource($copyright);
} catch(\Throwable) {}
}

if($owner_id < 0 && !$wallOwner->canBeModifiedBy($this->getUser()) && $wallOwner->getWallType() == 2)
$post->setSuggested(1);

Expand All @@ -558,11 +584,11 @@ function post(string $owner_id, string $message = "", int $from_group = 0, int $
# Пример: photo1_1

if(sizeof($attachmentsArr) > 10)
$this->fail(50, "Error: too many attachments");
$this->fail(50, "Too many attachments");

preg_match_all("/poll/m", $attachments, $matches, PREG_SET_ORDER, 0);
if(sizeof($matches) > 1)
$this->fail(85, "Error: too many polls");
$this->fail(85, "Too many polls");

foreach($attachmentsArr as $attac) {
$attachmentType = NULL;
Expand Down Expand Up @@ -993,7 +1019,7 @@ function delete(int $owner_id, int $post_id)
}
}

function edit(int $owner_id, int $post_id, string $message = "", string $attachments = "") {
function edit(int $owner_id, int $post_id, string $message = "", string $attachments = "", string $copyright = NULL) {
$this->requireUser();
$this->willExecuteWriteAction();

Expand All @@ -1002,16 +1028,19 @@ function edit(int $owner_id, int $post_id, string $message = "", string $attachm
if(!$post || $post->isDeleted())
$this->fail(102, "Invalid post");

if(empty($message) && empty($attachments))
$this->fail(100, "Required parameter 'message' missing.");

if(!$post->canBeEditedBy($this->getUser()))
$this->fail(7, "Access to editing denied");

if(!empty($message))
$post->setContent($message);

$post->setEdited(time());
if(!is_null($copyright) && !empty($copyright)) {
try {
$post->setSource($copyright);
} catch(\Throwable) {}
}

$post->save(true);

# todo добавить такое в веб версию
Expand Down Expand Up @@ -1082,6 +1111,63 @@ function editComment(int $comment_id, int $owner_id = 0, string $message = "", s
return 1;
}

function checkCopyrightLink(string $link): int
{
$this->requireUser();

try {
$result = check_copyright_link($link);
} catch(\InvalidArgumentException $e) {
$this->fail(3102, "Specified link is incorrect (can't find source)");
} catch(\LengthException $e) {
$this->fail(3103, "Specified link is incorrect (too long)");
} catch(\LogicException $e) {
$this->fail(3104, "Link is suspicious");
} catch(\Throwable $e) {
$this->fail(3102, "Specified link is incorrect");
}

return 1;
}

function pin(int $owner_id, int $post_id)
{
$this->requireUser();
$this->willExecuteWriteAction();

$post = (new PostsRepo)->getPostById($owner_id, $post_id);
if(!$post || $post->isDeleted())
$this->fail(100, "One of the parameters specified was missing or invalid: post_id is undefined");

if(!$post->canBePinnedBy($this->getUser()))
return 0;

if($post->isPinned())
return 1;

$post->pin();
return 1;
}

function unpin(int $owner_id, int $post_id)
{
$this->requireUser();
$this->willExecuteWriteAction();

$post = (new PostsRepo)->getPostById($owner_id, $post_id);
if(!$post || $post->isDeleted())
$this->fail(100, "One of the parameters specified was missing or invalid: post_id is undefined");

if(!$post->canBePinnedBy($this->getUser()))
return 0;

if(!$post->isPinned())
return 1;

$post->unpin();
return 1;
}

private function getApiPhoto($attachment) {
return [
"type" => "photo",
Expand Down
34 changes: 34 additions & 0 deletions Web/Models/Entities/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,40 @@ function isPinned(): bool
{
return (bool) $this->getRecord()->pinned;
}

function hasSource(): bool
{
return $this->getRecord()->source != NULL;
}

function getSource(bool $format = false)
{
$orig_source = $this->getRecord()->source;
if(!str_contains($orig_source, "https://") && !str_contains($orig_source, "http://"))
$orig_source = "https://" . $orig_source;

if(!$format)
return $orig_source;

return $this->formatLinks($orig_source);
}

function setSource(string $source)
{
$result = check_copyright_link($source);

$this->stateChanges("source", $source);
}

function getVkApiCopyright(): object
{
return (object)[
'id' => 0,
'link' => $this->getSource(false),
'name' => $this->getSource(false),
'type' => 'link',
];
}

function isAd(): bool
{
Expand Down
11 changes: 11 additions & 0 deletions Web/Models/Entities/Traits/TRichText.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,19 @@ private function formatLinks(string &$text): string
$href = str_replace("#", "&num;", $matches[1]);
$href = rawurlencode(str_replace(";", "&#59;", $href));
$link = str_replace("#", "&num;", $matches[3]);
# this string breaks ampersands
$link = str_replace(";", "&#59;", $link);
$rel = $this->isAd() ? "sponsored" : "ugc";

$server_domain = str_replace(':' . $_SERVER['SERVER_PORT'], '', $_SERVER['HTTP_HOST']);
if(str_contains($link, $server_domain)) {
$replaced_link = str_replace(':' . $_SERVER['SERVER_PORT'], '', $link);
$replaced_link = str_replace($server_domain, '', $replaced_link);

return "<a href='$replaced_link' rel='$rel'>$link</a>" . htmlentities($matches[4]);
}

$link = htmlentities(urldecode($link));

return "<a href='/away.php?to=$href' rel='$rel' target='_blank'>$link</a>" . htmlentities($matches[4]);
}),
Expand Down
6 changes: 6 additions & 0 deletions Web/Presenters/WallPresenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,12 @@ function renderMakePost(int $wall): void
$post->setFlags($flags);
$post->setNsfw($this->postParam("nsfw") === "on");

if(!empty($this->postParam("source")) && $this->postParam("source") != 'none') {
try {
$post->setSource($this->postParam("source"));
} catch(\Throwable) {}
}

if($wall < 0 && !$wallOwner->canBeModifiedBy($this->user->identity) && $wallOwner->getWallType() == 2)
$post->setSuggested(1);

Expand Down
2 changes: 1 addition & 1 deletion Web/Presenters/templates/Audio/Upload.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
{else}
<a href="{$owner->getURL()}">{$owner->getCanonicalName()}</a>
»
<a href="/playlists{$ownerId}">{_playlists}</a>
<a href="/playlists{$owner->getRealId()}">{_playlists}</a>
»
<a href="/playlist{$playlist->getPrettyId()}">{_playlist}</a>
{/if}
Expand Down
2 changes: 1 addition & 1 deletion Web/Presenters/templates/Audio/tabs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

<a n:if="!$isMy" n:attr="id => $mode === 'list' ? 'used' : 'ki'" href="/audios{$ownerId}">{if $ownerId > 0}{_music_user}{else}{_music_club}{/if}</a>
<a href="/player/upload?gid={abs($ownerId)}" n:if="isset($thisUser) && isset($club) && $club->canUploadAudio($thisUser)">{_upload_audio}</a>
<a n:attr="id => $mode === 'playlists' && $ownerId != $thisUser->getId() ? 'used' : 'ki'" href="/playlists{$ownerId}" n:if="isset($thisUser) && isset($ownerId) && !$isMy">{if $ownerId > 0}{_playlists_user}{else}{_playlists_club}{/if}</a>
<a n:attr="id => $mode === 'playlists' && $ownerId != $thisUser->getId() ? 'used' : 'ki'" class='noOverflow' href="/playlists{$ownerId}" n:if="isset($thisUser) && isset($ownerId) && !$isMy">{if $ownerId > 0}{_playlists_user}{else}{_playlists_club}{/if}</a>
<a href="/audios/newPlaylist{if $isMyClub}?gid={abs($ownerId)}{/if}" n:if="isset($thisUser) && $isMyClub">{_new_playlist}</a>
{/if}
</div>
Expand Down
2 changes: 1 addition & 1 deletion Web/Presenters/templates/Wall/Feed.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</div>

<div n:class="postFeedWrapper, $thisUser->hasMicroblogEnabled() ? postFeedWrapperMicroblog">
{include "../components/textArea.xml", route => "/wall" . $thisUser->getId() . "/makePost", graffiti => true, polls => true, notes => true}
{include "../components/textArea.xml", route => "/wall" . $thisUser->getId() . "/makePost", graffiti => true, polls => true, notes => true, hasSource => true}
</div>

{foreach $posts as $post}
Expand Down
2 changes: 1 addition & 1 deletion Web/Presenters/templates/Wall/Wall.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
</div>

<div n:if="$canPost && $type == 'all'" class="content_subtitle">
{include "../components/textArea.xml", route => "/wall$owner/makePost"}
{include "../components/textArea.xml", route => "/wall$owner/makePost", hasSource => true}
</div>

<div class="content">
Expand Down
12 changes: 7 additions & 5 deletions Web/Presenters/templates/components/comment.xml
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
{var $author = $comment->getOwner()}
{var $Club = openvk\Web\Models\Entities\Club::class}
{var $postId = $comment->getTarget() instanceof \openvk\Web\Models\Entities\Post ? $comment->getTarget()->getId() : NULL}
{var $likesCount = $comment->getLikesCount()}
{var $target = $comment->getTarget()}
{var $postId = $target instanceof \openvk\Web\Models\Entities\Post ? $target->getId() : NULL}

<a name="cid={$comment->getId()}"></a>
<table border="0" style="font-size: 11px;" class="post comment" id="_comment{$comment->getId()}" data-comment-id="{$comment->getId()}" data-owner-id="{$author->getId()}" data-from-group="{$comment->getOwner() instanceof $Club}" n:attr="data-post-id => $postId">
<table border="0" style="font-size: 11px;" class="post comment" id="_comment{$comment->getId()}" data-comment-id="{$comment->getId()}" data-owner-id="{$author->getId()}" data-from-group="{$author instanceof $Club}" n:attr="data-post-id => $postId">
<tbody>
<tr>
<td width="30" valign="top">
Expand Down Expand Up @@ -40,8 +42,8 @@
<span n:if="$comment->getEditTime()" class="edited editedMark">({_edited_short})</span>
</a>
{if !$timeOnly}
&nbsp;|
{if $comment->canBeDeletedBy($thisUser)}
|
<a href="/comment{$comment->getId()}/delete">{_delete}</a>
{/if}
{if $comment->canBeEditedBy($thisUser)}
Expand All @@ -60,7 +62,7 @@
<div style="float: right; font-size: .7rem;">
<a class="post-like-button" href="/comment{$comment->getId()}/like?hash={rawurlencode($csrfToken)}">
<div class="heart" style="{if $comment->hasLikeFrom($thisUser)}opacity: 1;{else}opacity: 0.4;{/if}"></div>
<span class="likeCnt">{if $comment->getLikesCount() > 0}{$comment->getLikesCount()}{/if}</span>
<span class="likeCnt">{if $likesCount > 0}{$likesCount}{/if}</span>
</a>
</div>
{/if}
Expand Down Expand Up @@ -101,4 +103,4 @@
Function.noop
]);
}
</script>
</script>
Loading

0 comments on commit fab39bd

Please sign in to comment.