API: Direct Messages moved to new place

This commit is contained in:
Michael 2021-12-16 22:44:50 +00:00
parent 0165811f09
commit b7a460485a
15 changed files with 778 additions and 466 deletions

View file

@ -144,60 +144,6 @@ function api_call($command, $extension)
}
}
/**
*
* @param array $item
* @param array $recipient
* @param array $sender
*
* @return array
* @throws InternalServerErrorException
*/
function api_format_messages($item, $recipient, $sender)
{
// standard meta information
$ret = [
'id' => $item['id'],
'sender_id' => $sender['id'],
'text' => "",
'recipient_id' => $recipient['id'],
'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
'sender_screen_name' => $sender['screen_name'],
'recipient_screen_name' => $recipient['screen_name'],
'sender' => $sender,
'recipient' => $recipient,
'title' => "",
'friendica_seen' => $item['seen'] ?? 0,
'friendica_parent_uri' => $item['parent-uri'] ?? '',
];
// "uid" is only needed for some internal stuff, so remove it from here
if (isset($ret['sender']['uid'])) {
unset($ret['sender']['uid']);
}
if (isset($ret['recipient']['uid'])) {
unset($ret['recipient']['uid']);
}
//don't send title to regular StatusNET requests to avoid confusing these apps
if (!empty($_GET['getText'])) {
$ret['title'] = $item['title'];
if ($_GET['getText'] == 'html') {
$ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
} elseif ($_GET['getText'] == 'plain') {
$ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
}
} else {
$ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
}
if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
unset($ret['sender']);
unset($ret['recipient']);
}
return $ret;
}
/**
*
* @param string $acl_string
@ -554,32 +500,6 @@ function prepare_photo_data($type, $scale, $photo_id, $uid)
return $data;
}
/**
*
* @param string $text
*
* @return string
* @throws InternalServerErrorException
*/
function api_clean_plain_items($text)
{
$include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
$text = BBCode::cleanPictureLinks($text);
$URLSearchString = "^\[\]";
$text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
if ($include_entities == "true") {
$text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
}
// Simplify "attachment" element
$text = BBCode::removeAttachment($text);
return $text;
}
/**
* Add a new group to the database.
*
@ -701,291 +621,6 @@ function api_lists_ownerships($type)
api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
/**
* Sends a new direct message.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @throws BadRequestException
* @throws ForbiddenException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws NotFoundException
* @throws UnauthorizedException
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
*/
function api_direct_messages_new($type)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$uid = BaseApi::getCurrentUserID();
if (empty($_POST["text"]) || empty($_REQUEST['screen_name']) && empty($_REQUEST['user_id'])) {
return;
}
$sender = DI::twitterUser()->createFromUserId($uid, true)->toArray();
$cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
if (empty($cid)) {
throw new NotFoundException('Recipient not found');
}
$replyto = '';
if (!empty($_REQUEST['replyto'])) {
$mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
$replyto = $mail['parent-uri'];
$sub = $mail['title'];
} else {
if (!empty($_REQUEST['title'])) {
$sub = $_REQUEST['title'];
} else {
$sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
}
}
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
$id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
if ($id > -1) {
$mail = DBA::selectFirst('mail', [], ['id' => $id]);
$ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid, true)->toArray(), $sender);
} else {
$ret = ["error" => $id];
}
return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
}
api_register_func('api/direct_messages/new', 'api_direct_messages_new', true);
/**
* delete a direct_message from mail table through api
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @return string|array
* @throws BadRequestException
* @throws ForbiddenException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws UnauthorizedException
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
*/
function api_direct_messages_destroy($type)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$uid = BaseApi::getCurrentUserID();
//required
$id = $_REQUEST['id'] ?? 0;
// optional
$parenturi = $_REQUEST['friendica_parenturi'] ?? '';
$verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
/// @todo optional parameter 'include_entities' from Twitter API not yet implemented
// error if no id or parenturi specified (for clients posting parent-uri as well)
if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
$answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
}
// BadRequestException if no id specified (for clients using Twitter API)
if ($id == 0) {
throw new BadRequestException('Message id not specified');
}
// add parent-uri to sql command if specified by calling app
$sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
// error message if specified id is not in database
if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
if ($verbose == "true") {
$answer = ['result' => 'error', 'message' => 'message id not in database'];
return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
}
/// @todo BadRequestException ok for Twitter API clients?
throw new BadRequestException('message id not in database');
}
// delete message
$result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
if ($verbose == "true") {
if ($result) {
// return success
$answer = ['result' => 'ok', 'message' => 'message deleted'];
return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
} else {
$answer = ['result' => 'error', 'message' => 'unknown error'];
return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
}
}
/// @todo return JSON data like Twitter API not yet implemented
}
api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true);
/**
*
* @param string $type Return type (atom, rss, xml, json)
* @param string $box
* @param string $verbose
*
* @return array|string
* @throws BadRequestException
* @throws ForbiddenException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws UnauthorizedException
*/
function api_direct_messages_box($type, $box, $verbose)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID();
// params
$count = $_GET['count'] ?? 20;
$page = $_REQUEST['page'] ?? 1;
$since_id = $_REQUEST['since_id'] ?? 0;
$max_id = $_REQUEST['max_id'] ?? 0;
$user_id = $_REQUEST['user_id'] ?? '';
$screen_name = $_REQUEST['screen_name'] ?? '';
$user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
$profile_url = $user_info["url"];
// pagination
$start = max(0, ($page - 1) * $count);
$sql_extra = "";
// filters
if ($box=="sentbox") {
$sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
} elseif ($box == "conversation") {
$sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
} elseif ($box == "all") {
$sql_extra = "true";
} elseif ($box == "inbox") {
$sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
}
if ($max_id > 0) {
$sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
}
if ($user_id != "") {
$sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
} elseif ($screen_name !="") {
$sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
}
$r = DBA::toArray(DBA::p(
"SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
$uid,
$since_id,
$start,
$count
));
if ($verbose == "true" && !DBA::isResult($r)) {
$answer = ['result' => 'error', 'message' => 'no mails available'];
return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
}
$ret = [];
foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url) {
$recipient = $user_info;
$sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
} elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
$recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
$sender = $user_info;
}
if (isset($recipient) && isset($sender)) {
$ret[] = api_format_messages($item, $recipient, $sender);
}
}
return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
}
/**
* Returns the most recent direct messages sent by the user.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @throws BadRequestException
* @throws ForbiddenException
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
*/
function api_direct_messages_sentbox($type)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
return api_direct_messages_box($type, "sentbox", $verbose);
}
api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
/**
* Returns the most recent direct messages sent to the user.
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @throws BadRequestException
* @throws ForbiddenException
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
*/
function api_direct_messages_inbox($type)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
return api_direct_messages_box($type, "inbox", $verbose);
}
api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @throws BadRequestException
* @throws ForbiddenException
*/
function api_direct_messages_all($type)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
return api_direct_messages_box($type, "all", $verbose);
}
api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
/**
*
* @param string $type Return type (atom, rss, xml, json)
*
* @return array|string
* @throws BadRequestException
* @throws ForbiddenException
*/
function api_direct_messages_conversation($type)
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
return api_direct_messages_box($type, "conversation", $verbose);
}
api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
/**
* list all photos of the authenticated user
*
@ -1526,69 +1161,3 @@ function api_lists_update($type)
}
api_register_func('api/lists/update', 'api_lists_update', true);
/**
* search for direct_messages containing a searchstring through api
*
* @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
* @param string $box
* @return string|array (success: success=true if found and search_result contains found messages,
* success=false if nothing was found, search_result='nothing found',
* error: result=error with error message)
* @throws BadRequestException
* @throws ForbiddenException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws UnauthorizedException
*/
function api_friendica_direct_messages_search($type, $box = "")
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID();
// params
$user_info = DI::twitterUser()->createFromUserId($uid, true)->toArray();
$searchstring = $_REQUEST['searchstring'] ?? '';
// error if no searchstring specified
if ($searchstring == "") {
$answer = ['result' => 'error', 'message' => 'searchstring not specified'];
return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
}
// get data for the specified searchstring
$r = DBA::toArray(DBA::p(
"SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
$uid,
'%'.$searchstring.'%'
));
$profile_url = $user_info["url"];
// message if nothing was found
if (!DBA::isResult($r)) {
$success = ['success' => false, 'search_results' => 'problem with query'];
} elseif (count($r) == 0) {
$success = ['success' => false, 'search_results' => 'nothing found'];
} else {
$ret = [];
foreach ($r as $item) {
if ($box == "inbox" || $item['from-url'] != $profile_url) {
$recipient = $user_info;
$sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
} elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
$recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid, true)->toArray();
$sender = $user_info;
}
if (isset($recipient) && isset($sender)) {
$ret[] = api_format_messages($item, $recipient, $sender);
}
}
$success = ['success' => true, 'search_results' => $ret];
}
return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
}
api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);