Improved message splitting when posting to Bluesky or Twitter

pull/14548/head
Michael 2024-11-12 06:26:15 +00:00
parent 08d09bcbdf
commit 6cb1794c35
1 changed files with 32 additions and 15 deletions

View File

@ -12,6 +12,7 @@ use Friendica\DI;
use Friendica\Model\Photo; use Friendica\Model\Photo;
use Friendica\Model\Post; use Friendica\Model\Post;
use Friendica\Util\Network; use Friendica\Util\Network;
use IntlChar;
class Plaintext class Plaintext
{ {
@ -237,39 +238,55 @@ class Plaintext
*/ */
private static function getParts(string $message, int $baselimit): array private static function getParts(string $message, int $baselimit): array
{ {
$parts = []; $parts = [];
$part = ''; $part = '';
$break_pos = 0;
$limit = $baselimit; $limit = $baselimit;
while ($message) { while ($message) {
$pos1 = strpos($message, ' '); $pos_word = mb_strpos($message, ' ');
$pos2 = strpos($message, "\n"); $pos_paragraph = mb_strpos($message, "\n");
if (($pos1 !== false) && ($pos2 !== false)) { if (($pos_word !== false) && ($pos_paragraph !== false)) {
$pos = min($pos1, $pos2) + 1; $pos = min($pos_word, $pos_paragraph) + 1;
} elseif ($pos1 !== false) { } elseif ($pos_word !== false) {
$pos = $pos1 + 1; $pos = $pos_word + 1;
} elseif ($pos2 !== false) { } elseif ($pos_paragraph !== false) {
$pos = $pos2 + 1; $pos = $pos_paragraph + 1;
} else { } else {
$word = $message; $word = $message;
$message = ''; $message = '';
} }
if (trim($message)) { if (trim($message)) {
$word = substr($message, 0, $pos); $word = mb_substr($message, 0, $pos);
$message = trim(substr($message, $pos)); $message = trim(mb_substr($message, $pos));
} }
if (Network::isValidHttpUrl(trim($word))) { if (Network::isValidHttpUrl(trim($word))) {
$limit += mb_strlen(trim($word)) - self::URL_LENGTH; $limit += mb_strlen(trim($word)) - self::URL_LENGTH;
} }
$break = mb_strrpos($word, "\n") !== false;
if (!$break && mb_strrpos($word, '. ') !== false) {
$next = mb_substr($message, 0, 1);
$break = IntlChar::isupper($next);
}
if ($break) {
$break_pos = $pos + mb_strlen($part);
}
if ((mb_strlen($part . $word) > $limit - 8) && ($parts || (mb_strlen($part . $word . $message) > $limit))) { if ((mb_strlen($part . $word) > $limit - 8) && ($parts || (mb_strlen($part . $word . $message) > $limit))) {
$parts[] = trim($part); if ($break_pos) {
$part = ''; $parts[] = trim(mb_substr($part, 0, $break_pos));
$limit = $baselimit; $part = mb_substr($part, $break_pos);
} else {
$parts[] = trim($part);
$part = '';
}
$limit = $baselimit;
$break_pos = 0;
} }
$part .= $word; $part .= $word;
} }