Merge pull request #11105 from annando/api-direct-messages

API: Direct Messages moved to new place
This commit is contained in:
Hypolite Petovan 2021-12-28 10:29:00 +01:00 committed by GitHub
commit c371d2ec82
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 918 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 * @param string $acl_string
@ -554,32 +500,6 @@ function prepare_photo_data($type, $scale, $photo_id, $uid)
return $data; 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. * 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); 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 * 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); 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);

View File

@ -0,0 +1,89 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Factory\Api\Twitter;
use Friendica\BaseFactory;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
use Friendica\Database\Database;
use Friendica\Factory\Api\Twitter\User as TwitterUser;
use Friendica\Model\Contact;
use Friendica\Network\HTTPException;
use Psr\Log\LoggerInterface;
class DirectMessage extends BaseFactory
{
/** @var Database */
private $dba;
/** @var twitterUser entity */
private $twitterUser;
public function __construct(LoggerInterface $logger, Database $dba, TwitterUser $twitteruser)
{
parent::__construct($logger);
$this->dba = $dba;
$this->twitterUser = $twitteruser;
}
/**
* Create a direct message from a given mail id
*
* @todo Processing of "getUserObjects" (true/false) and "getText" (html/plain)
*
* @param int $id Mail id
* @param int $uid Mail user
* @param string $text_mode Either empty, "html" or "text"
*
* @return \Friendica\Object\Api\Twitter\DirectMessage
*/
public function createFromMailId(int $id, int $uid, string $text_mode = ''): \Friendica\Object\Api\Twitter\DirectMessage
{
$mail = $this->dba->selectFirst('mail', [], ['id' => $id, 'uid' => $uid]);
if (!$mail) {
throw new HTTPException\NotFoundException('Direct message with ID ' . $mail . ' not found.');
}
if (!empty($text_mode)) {
$title = $mail['title'];
if ($text_mode == 'html') {
$text = BBCode::convertForUriId($mail['uri-id'], $mail['body'], BBCode::API);
} elseif ($text_mode == 'plain') {
$text = HTML::toPlaintext(BBCode::convertForUriId($mail['uri-id'], $mail['body'], BBCode::API), 0);
}
} else {
$title = '';
$text = $mail['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($mail['uri-id'], $mail['body'], BBCode::API), 0);
}
$pcid = Contact::getPublicIdByUserId($uid);
if ($mail['author-id'] == $pcid) {
$sender = $this->twitterUser->createFromUserId($uid, true);
$recipient = $this->twitterUser->createFromContactId($mail['contact-id'], $uid, true);
} else {
$sender = $this->twitterUser->createFromContactId($mail['author-id'], $uid, true);
$recipient = $this->twitterUser->createFromUserId($uid, true);
}
return new \Friendica\Object\Api\Twitter\DirectMessage($mail, $sender, $recipient, $text, $title);
}
}

View File

@ -0,0 +1,87 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Friendica\DirectMessages;
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\Factory\Api\Twitter\DirectMessage;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/**
* search for direct_messages containing a searchstring through api
*
* API endpoint: api/friendica/direct_messages_search
*/
class Search extends BaseApi
{
/** @var Database */
private $dba;
/** @var DirectMessage */
private $directMessage;
public function __construct(DirectMessage $directMessage, Database $dba, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->dba = $dba;
$this->directMessage = $directMessage;
}
protected function rawContent(array $request = [])
{
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
$request = $this->getRequest([
'searchstring' => '',
], $request);
// error if no searchstring specified
if ($request['searchstring'] == '') {
$answer = ['result' => 'error', 'message' => 'searchstring not specified'];
$this->response->exit('direct_message_search', ['$result' => $answer], $this->parameters['extension'] ?? null);
return;
}
// get data for the specified searchstring
$mails = $this->dba->selectToArray('mail', ['id'], ["`uid` = ? AND `body` LIKE ?", $uid, '%' . $request['searchstring'] . '%'], ['order' => ['id' => true]]);
// message if nothing was found
if (!DBA::isResult($mails)) {
$success = ['success' => false, 'search_results' => 'nothing found'];
} else {
$ret = [];
foreach ($mails as $mail) {
$ret[] = $this->directMessage->createFromMailId($mail['id'], $uid, $request['getText'] ?? '');
}
$success = ['success' => true, 'search_results' => $ret];
}
$this->response->exit('direct_message_search', ['$result' => $success], $this->parameters['extension'] ?? null);
}
}

View File

@ -23,9 +23,7 @@ namespace Friendica\Module\Api\Twitter;
use Friendica\App; use Friendica\App;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Profile;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Module\Api\ApiResponse; use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;

View File

@ -0,0 +1,39 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter\DirectMessages;
use Friendica\Module\Api\Twitter\DirectMessagesEndpoint;
use Friendica\Module\BaseApi;
/**
* Returns all direct messages
*/
class All extends DirectMessagesEndpoint
{
protected function rawContent(array $request = [])
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID();
$this->getMessages($request, $uid, []);
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter\DirectMessages;
use Friendica\Module\Api\Twitter\DirectMessagesEndpoint;
use Friendica\Module\BaseApi;
/**
* Returns direct messages with a given URI
*/
class Conversation extends DirectMessagesEndpoint
{
protected function rawContent(array $request = [])
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID();
$this->getMessages($request, $uid, ["`parent-uri` = ?", $request['uri'] ?? '']);
}
}

View File

@ -0,0 +1,99 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter\DirectMessages;
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/**
* delete a direct_message from mail table through api
*
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
*/
class Destroy extends BaseApi
{
/** @var Database */
private $dba;
public function __construct(Database $dba, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->dba = $dba;
}
protected function rawContent(array $request = [])
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$uid = BaseApi::getCurrentUserID();
$id = filter_var($request['id'] ?? 0, FILTER_VALIDATE_INT);
$verbose = filter_var($request['friendica_verbose'] ?? false, FILTER_VALIDATE_BOOLEAN);
$parenturi = $request['friendica_parenturi'] ?? '';
// error if no id or parenturi specified (for clients posting parent-uri as well)
if ($verbose && ($id == 0 || $parenturi == "")) {
$answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
$this->response->exit('direct_messages_delete', ['direct_messages_delete' => $answer], $this->parameters['extension'] ?? null);
return;
}
// 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 (!$this->dba->exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
if ($verbose) {
$answer = ['result' => 'error', 'message' => 'message id not in database'];
$this->response->exit('direct_messages_delete', ['direct_messages_delete' => $answer], $this->parameters['extension'] ?? null);
return;
}
throw new BadRequestException('message id not in database');
}
// delete message
$result = $this->dba->delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
if ($verbose) {
if ($result) {
// return success
$answer = ['result' => 'ok', 'message' => 'message deleted'];
$this->response->exit('direct_messages_delete', ['direct_messages_delete' => $answer], $this->parameters['extension'] ?? null);
} else {
$answer = ['result' => 'error', 'message' => 'unknown error'];
$this->response->exit('direct_messages_delete', ['direct_messages_delete' => $answer], $this->parameters['extension'] ?? null);
}
}
}
}

View File

@ -0,0 +1,43 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter\DirectMessages;
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\DirectMessagesEndpoint;
use Friendica\Module\BaseApi;
/**
* Returns the most recent direct messages sent to the user.
*
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
*/
class Inbox extends DirectMessagesEndpoint
{
protected function rawContent(array $request = [])
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID();
$pcid = Contact::getPublicIdByUserId($uid);
$this->getMessages($request, $uid, ["`author-id` != ?", $pcid]);
}
}

View File

@ -0,0 +1,96 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter\DirectMessages;
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Database\Database;
use Friendica\Factory\Api\Twitter\DirectMessage;
use Friendica\Model\Contact;
use Friendica\Model\Mail;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/**
* Sends a new direct message.
*
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
*/
class NewDM extends BaseApi
{
/** @var Database */
private $dba;
/** @var DirectMessage */
private $directMessage;
public function __construct(DirectMessage $directMessage, Database $dba, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->dba = $dba;
$this->directMessage = $directMessage;
}
protected function rawContent(array $request = [])
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
$uid = BaseApi::getCurrentUserID();
if (empty($request['text']) || empty($request['screen_name']) && empty($request['user_id'])) {
return;
}
$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 = $this->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($request['text']) > 10) ? substr($request['text'], 0, 10) . '...' : $request['text']);
}
}
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
$id = Mail::send($cdata['user'], $request['text'], $sub, $replyto);
if ($id > -1) {
$ret = $this->directMessage->createFromMailId($id, $uid, $request['getText'] ?? '');
} else {
$ret = ['error' => $id];
}
$this->response->exit('direct-messages', ['direct_message' => $ret], $this->parameters['extension'] ?? null, Contact::getPublicIdByUserId($uid));
}
}

View File

@ -0,0 +1,43 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter\DirectMessages;
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\DirectMessagesEndpoint;
use Friendica\Module\BaseApi;
/**
* Returns the most recent direct messages sent by the user.
*
* @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
*/
class Sent extends DirectMessagesEndpoint
{
protected function rawContent(array $request = [])
{
BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID();
$pcid = Contact::getPublicIdByUserId($uid);
$this->getMessages($request, $uid, ["`author-id` = ?", $pcid]);
}
}

View File

@ -0,0 +1,119 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Twitter;
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\Factory\Api\Twitter\DirectMessage;
use Friendica\Model\Contact;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
abstract class DirectMessagesEndpoint extends BaseApi
{
/** @var Database */
private $dba;
/** @var DirectMessage */
private $directMessage;
public function __construct(DirectMessage $directMessage, Database $dba, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->dba = $dba;
$this->directMessage = $directMessage;
}
/**
* Handles a direct messages endpoint with the given condition
*
* @param array $request
* @param int $uid
* @param array $condition
*/
protected function getMessages(array $request, int $uid, array $condition)
{
// params
$count = filter_var($request['count'] ?? 20, FILTER_VALIDATE_INT, ['options' => ['max_range' => 100]]);
$page = filter_var($request['page'] ?? 1, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$since_id = filter_var($request['since_id'] ?? 0, FILTER_VALIDATE_INT);
$max_id = filter_var($request['max_id'] ?? 0, FILTER_VALIDATE_INT);
$min_id = filter_var($request['min_id'] ?? 0, FILTER_VALIDATE_INT);
$verbose = filter_var($request['friendica_verbose'] ?? false, FILTER_VALIDATE_BOOLEAN);
// pagination
$start = max(0, ($page - 1) * $count);
$params = ['order' => ['id' => true], 'limit' => [$start, $count]];
if (!empty($max_id)) {
$condition = DBA::mergeConditions($condition, ["`id` < ?", $max_id]);
}
if (!empty($since_id)) {
$condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
}
if (!empty($min_id)) {
$condition = DBA::mergeConditions($condition, ["`id` > ?", $min_id]);
$params['order'] = ['id'];
}
$cid = BaseApi::getContactIDForSearchterm($request['screen_name'] ?? '', $request['profileurl'] ?? '', $_REQUEST['user_id'] ?? 0, 0);
if (!empty($cid)) {
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (!empty($cdata['user'])) {
$condition = DBA::mergeConditions($condition, ["`contact-id` = ?", $cdata['user']]);
}
}
$condition = DBA::mergeConditions($condition, ["`uid` = ?", $uid]);
$mails = $this->dba->selectToArray('mail', ['id'], $condition, $params);
if ($verbose && !DBA::isResult($mails)) {
$answer = ['result' => 'error', 'message' => 'no mails available'];
$this->response->exit('direct-messages', ['direct_message' => $answer], $this->parameters['extension'] ?? null);
return;
}
$ids = array_column($mails, 'id');
if (!empty($min_id)) {
$ids = array_reverse($ids);
}
$ret = [];
foreach ($ids as $id) {
$ret[] = $this->directMessage->createFromMailId($id, $uid, $request['getText'] ?? '');
}
self::setLinkHeader();
$this->response->exit('direct-messages', ['direct_message' => $ret], $this->parameters['extension'] ?? null, Contact::getPublicIdByUserId($uid));
}
}

View File

@ -0,0 +1,100 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Object\Api\Twitter;
use Friendica\BaseDataTransferObject;
use Friendica\Util\DateTimeFormat;
/**
* Class DirectMessage
*/
class DirectMessage extends BaseDataTransferObject
{
/** @var int */
protected $id;
/** @var int */
protected $sender_id;
/** @var string */
protected $text;
/** @var int */
protected $recipient_id;
/** @var string (Datetime) */
protected $created_at;
/** @var string */
protected $sender_screen_name = null;
/** @var string */
protected $recipient_screen_name = null;
/** @var User */
protected $sender;
/** @var User */
protected $recipient;
/** @var string|null */
protected $title;
/** @var bool */
protected $friendica_seen;
/** @var string|null */
protected $friendica_parent_uri = null;
/**
* Creates a direct message record
*
* @param array $mail
* @param User $sender
* @param User $recipient
* @param string $text
* @param string $title
*/
public function __construct(array $mail, User $sender, User $recipient, string $text, string $title = null)
{
$this->id = (int)$mail['id'];
$this->created_at = DateTimeFormat::utc($mail['created'] ?? 'now', DateTimeFormat::API);
$this->title = $title;
$this->text = $text;
$this->sender = $sender->toArray();
$this->recipient = $recipient->toArray();
$this->sender_id = (int)$this->sender['id'];
$this->recipient_id = (int)$this->recipient['id'];
$this->sender_screen_name = $this->sender['screen_name'];
$this->recipient_screen_name = $this->recipient['screen_name'];
$this->friendica_seen = (bool)$mail['seen'] ?? false;
$this->friendica_parent_uri = $mail['parent-uri'] ?? '';
}
/**
* Returns the current entity as an array
*
* @return array
*/
public function toArray(): array
{
$status = parent::toArray();
if (is_null($status['title'])) {
unset($status['title']);
}
unset($status['sender']['uid']);
unset($status['recipient']['uid']);
return $status;
}
}

View File

@ -52,13 +52,13 @@ $apiRoutes = [
'/blocks/list[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\Blocks\Lists::class, [R::GET ]], '/blocks/list[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\Blocks\Lists::class, [R::GET ]],
'/conversation/show[.{extension:json|xml|rss|atom}]' => [Module\Api\GNUSocial\Statusnet\Conversation::class, [R::GET ]], '/conversation/show[.{extension:json|xml|rss|atom}]' => [Module\Api\GNUSocial\Statusnet\Conversation::class, [R::GET ]],
'/direct_messages' => [ '/direct_messages' => [
'/all[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET ]], '/all[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\DirectMessages\All::class, [R::GET ]],
'/conversation[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET ]], '/conversation[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\DirectMessages\Conversation::class, [R::GET ]],
'/destroy[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [ R::POST]], '/destroy[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\DirectMessages\Destroy::class, [ R::POST]],
'/new[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [ R::POST]], '/new[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\DirectMessages\NewDM::class, [ R::POST]],
'/sent[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET ]], '/sent[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\DirectMessages\Sent::class, [R::GET ]],
], ],
'/direct_messages[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET, R::POST]], '/direct_messages[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\DirectMessages\Inbox::class, [R::GET, R::POST]],
'/externalprofile/show[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\Users\Show::class, [R::GET ]], '/externalprofile/show[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\Users\Show::class, [R::GET ]],
'/favorites/create[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\Favorites\Create::class, [ R::POST]], '/favorites/create[.{extension:json|xml|rss|atom}]' => [Module\Api\Twitter\Favorites\Create::class, [ R::POST]],
@ -78,7 +78,7 @@ $apiRoutes = [
'/notification/seen[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Notification\Seen::class, [ R::POST]], '/notification/seen[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Notification\Seen::class, [ R::POST]],
'/notification[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Notification::class, [R::GET ]], '/notification[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Notification::class, [R::GET ]],
'/direct_messages_setseen[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\DirectMessages\Setseen::class, [ R::POST]], '/direct_messages_setseen[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\DirectMessages\Setseen::class, [ R::POST]],
'/direct_messages_search[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET ]], '/direct_messages_search[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\DirectMessages\Search ::class, [R::GET ]],
'/events[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Events\Index::class, [R::GET ]], '/events[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Events\Index::class, [R::GET ]],
'/group_show[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET ]], '/group_show[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [R::GET ]],
'/group_create[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [ R::POST]], '/group_create[.{extension:json|xml|rss|atom}]' => [Module\Api\Friendica\Index::class, [ R::POST]],

View File

@ -0,0 +1,17 @@
<?php
return [
'mail' => [
[
'uid' => 42,
'author-id' => 44,
'uri-id' => 44,
'parent-uri-id' => 44,
'thr-parent-id' => 44,
'guid' => '123456',
'from-name' => 'Tester',
'title' => 'test message',
'body' => 'this is a test',
],
],
];

View File

@ -842,6 +842,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiFormatMessages() public function testApiFormatMessages()
{ {
/*
$result = api_format_messages( $result = api_format_messages(
['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'], ['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'],
['id' => 2, 'uri-id' => 2, 'screen_name' => 'recipient_name'], ['id' => 2, 'uri-id' => 2, 'screen_name' => 'recipient_name'],
@ -853,6 +854,7 @@ class ApiTest extends FixtureTest
self::assertEquals(3, $result['sender_id']); self::assertEquals(3, $result['sender_id']);
self::assertEquals('recipient_name', $result['recipient_screen_name']); self::assertEquals('recipient_name', $result['recipient_screen_name']);
self::assertEquals('sender_name', $result['sender_screen_name']); self::assertEquals('sender_name', $result['sender_screen_name']);
*/
} }
/** /**
@ -862,6 +864,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiFormatMessagesWithHtmlText() public function testApiFormatMessagesWithHtmlText()
{ {
/*
$_GET['getText'] = 'html'; $_GET['getText'] = 'html';
$result = api_format_messages( $result = api_format_messages(
['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'], ['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'],
@ -870,6 +873,7 @@ class ApiTest extends FixtureTest
); );
self::assertEquals('item_title', $result['title']); self::assertEquals('item_title', $result['title']);
self::assertEquals('<strong>item_body</strong>', $result['text']); self::assertEquals('<strong>item_body</strong>', $result['text']);
*/
} }
/** /**
@ -879,6 +883,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiFormatMessagesWithPlainText() public function testApiFormatMessagesWithPlainText()
{ {
/*
$_GET['getText'] = 'plain'; $_GET['getText'] = 'plain';
$result = api_format_messages( $result = api_format_messages(
['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'], ['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'],
@ -887,6 +892,7 @@ class ApiTest extends FixtureTest
); );
self::assertEquals('item_title', $result['title']); self::assertEquals('item_title', $result['title']);
self::assertEquals('item_body', $result['text']); self::assertEquals('item_body', $result['text']);
*/
} }
/** /**
@ -896,6 +902,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiFormatMessagesWithoutUserObjects() public function testApiFormatMessagesWithoutUserObjects()
{ {
/*
$_GET['getUserObjects'] = 'false'; $_GET['getUserObjects'] = 'false';
$result = api_format_messages( $result = api_format_messages(
['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'], ['id' => 1, 'uri-id' => 1, 'title' => 'item_title', 'body' => '[b]item_body[/b]'],
@ -904,6 +911,7 @@ class ApiTest extends FixtureTest
); );
self::assertTrue(!isset($result['sender'])); self::assertTrue(!isset($result['sender']));
self::assertTrue(!isset($result['recipient'])); self::assertTrue(!isset($result['recipient']));
*/
} }
/** /**
@ -1189,8 +1197,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesNew() public function testApiDirectMessagesNew()
{ {
$result = api_direct_messages_new('json'); //$result = api_direct_messages_new('json');
self::assertNull($result); //self::assertNull($result);
} }
/** /**
@ -1200,10 +1208,12 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesNewWithoutAuthenticatedUser() public function testApiDirectMessagesNewWithoutAuthenticatedUser()
{ {
/*
$this->expectException(\Friendica\Network\HTTPException\UnauthorizedException::class); $this->expectException(\Friendica\Network\HTTPException\UnauthorizedException::class);
BasicAuth::setCurrentUserID(); BasicAuth::setCurrentUserID();
$_SESSION['authenticated'] = false; $_SESSION['authenticated'] = false;
api_direct_messages_new('json'); api_direct_messages_new('json');
*/
} }
/** /**
@ -1213,10 +1223,12 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesNewWithUserId() public function testApiDirectMessagesNewWithUserId()
{ {
/*
$_POST['text'] = 'message_text'; $_POST['text'] = 'message_text';
$_REQUEST['user_id'] = $this->otherUser['id']; $_REQUEST['user_id'] = $this->otherUser['id'];
$result = api_direct_messages_new('json'); $result = api_direct_messages_new('json');
self::assertEquals(['direct_message' => ['error' => -1]], $result); self::assertEquals(['direct_message' => ['error' => -1]], $result);
*/
} }
/** /**
@ -1226,6 +1238,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesNewWithScreenName() public function testApiDirectMessagesNewWithScreenName()
{ {
/*
$this->app->setLoggedInUserNickname($this->selfUser['nick']); $this->app->setLoggedInUserNickname($this->selfUser['nick']);
$_POST['text'] = 'message_text'; $_POST['text'] = 'message_text';
$_REQUEST['user_id'] = $this->friendUser['id']; $_REQUEST['user_id'] = $this->friendUser['id'];
@ -1233,6 +1246,7 @@ class ApiTest extends FixtureTest
self::assertStringContainsString('message_text', $result['direct_message']['text']); self::assertStringContainsString('message_text', $result['direct_message']['text']);
self::assertEquals('selfcontact', $result['direct_message']['sender_screen_name']); self::assertEquals('selfcontact', $result['direct_message']['sender_screen_name']);
self::assertEquals(1, $result['direct_message']['friendica_seen']); self::assertEquals(1, $result['direct_message']['friendica_seen']);
*/
} }
/** /**
@ -1242,6 +1256,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesNewWithTitle() public function testApiDirectMessagesNewWithTitle()
{ {
/*
$this->app->setLoggedInUserNickname($this->selfUser['nick']); $this->app->setLoggedInUserNickname($this->selfUser['nick']);
$_POST['text'] = 'message_text'; $_POST['text'] = 'message_text';
$_REQUEST['user_id'] = $this->friendUser['id']; $_REQUEST['user_id'] = $this->friendUser['id'];
@ -1251,6 +1266,7 @@ class ApiTest extends FixtureTest
self::assertStringContainsString('message_title', $result['direct_message']['text']); self::assertStringContainsString('message_title', $result['direct_message']['text']);
self::assertEquals('selfcontact', $result['direct_message']['sender_screen_name']); self::assertEquals('selfcontact', $result['direct_message']['sender_screen_name']);
self::assertEquals(1, $result['direct_message']['friendica_seen']); self::assertEquals(1, $result['direct_message']['friendica_seen']);
*/
} }
/** /**
@ -1260,11 +1276,13 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesNewWithRss() public function testApiDirectMessagesNewWithRss()
{ {
/*
$this->app->setLoggedInUserNickname($this->selfUser['nick']); $this->app->setLoggedInUserNickname($this->selfUser['nick']);
$_POST['text'] = 'message_text'; $_POST['text'] = 'message_text';
$_REQUEST['user_id'] = $this->friendUser['id']; $_REQUEST['user_id'] = $this->friendUser['id'];
$result = api_direct_messages_new('rss'); $result = api_direct_messages_new('rss');
self::assertXml($result, 'direct-messages'); self::assertXml($result, 'direct-messages');
*/
} }
/** /**
@ -1274,8 +1292,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesDestroy() public function testApiDirectMessagesDestroy()
{ {
$this->expectException(\Friendica\Network\HTTPException\BadRequestException::class); //$this->expectException(\Friendica\Network\HTTPException\BadRequestException::class);
api_direct_messages_destroy('json'); //api_direct_messages_destroy('json');
} }
/** /**
@ -1285,6 +1303,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesDestroyWithVerbose() public function testApiDirectMessagesDestroyWithVerbose()
{ {
/*
$_GET['friendica_verbose'] = 'true'; $_GET['friendica_verbose'] = 'true';
$result = api_direct_messages_destroy('json'); $result = api_direct_messages_destroy('json');
self::assertEquals( self::assertEquals(
@ -1296,6 +1315,7 @@ class ApiTest extends FixtureTest
], ],
$result $result
); );
*/
} }
/** /**
@ -1305,10 +1325,12 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesDestroyWithoutAuthenticatedUser() public function testApiDirectMessagesDestroyWithoutAuthenticatedUser()
{ {
/*
$this->expectException(\Friendica\Network\HTTPException\UnauthorizedException::class); $this->expectException(\Friendica\Network\HTTPException\UnauthorizedException::class);
BasicAuth::setCurrentUserID(); BasicAuth::setCurrentUserID();
$_SESSION['authenticated'] = false; $_SESSION['authenticated'] = false;
api_direct_messages_destroy('json'); api_direct_messages_destroy('json');
*/
} }
/** /**
@ -1318,9 +1340,11 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesDestroyWithId() public function testApiDirectMessagesDestroyWithId()
{ {
/*
$this->expectException(\Friendica\Network\HTTPException\BadRequestException::class); $this->expectException(\Friendica\Network\HTTPException\BadRequestException::class);
$_REQUEST['id'] = 1; $_REQUEST['id'] = 1;
api_direct_messages_destroy('json'); api_direct_messages_destroy('json');
*/
} }
/** /**
@ -1330,6 +1354,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesDestroyWithIdAndVerbose() public function testApiDirectMessagesDestroyWithIdAndVerbose()
{ {
/*
$_REQUEST['id'] = 1; $_REQUEST['id'] = 1;
$_REQUEST['friendica_parenturi'] = 'parent_uri'; $_REQUEST['friendica_parenturi'] = 'parent_uri';
$_GET['friendica_verbose'] = 'true'; $_GET['friendica_verbose'] = 'true';
@ -1343,6 +1368,7 @@ class ApiTest extends FixtureTest
], ],
$result $result
); );
*/
} }
/** /**
@ -1362,10 +1388,12 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithSentbox() public function testApiDirectMessagesBoxWithSentbox()
{ {
/*
$_REQUEST['page'] = -1; $_REQUEST['page'] = -1;
$_REQUEST['max_id'] = 10; $_REQUEST['max_id'] = 10;
$result = api_direct_messages_box('json', 'sentbox', 'false'); $result = api_direct_messages_box('json', 'sentbox', 'false');
self::assertArrayHasKey('direct_message', $result); self::assertArrayHasKey('direct_message', $result);
*/
} }
/** /**
@ -1375,8 +1403,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithConversation() public function testApiDirectMessagesBoxWithConversation()
{ {
$result = api_direct_messages_box('json', 'conversation', 'false'); //$result = api_direct_messages_box('json', 'conversation', 'false');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1386,8 +1414,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithAll() public function testApiDirectMessagesBoxWithAll()
{ {
$result = api_direct_messages_box('json', 'all', 'false'); //$result = api_direct_messages_box('json', 'all', 'false');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1397,8 +1425,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithInbox() public function testApiDirectMessagesBoxWithInbox()
{ {
$result = api_direct_messages_box('json', 'inbox', 'false'); //$result = api_direct_messages_box('json', 'inbox', 'false');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1408,6 +1436,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithVerbose() public function testApiDirectMessagesBoxWithVerbose()
{ {
/*
$result = api_direct_messages_box('json', 'sentbox', 'true'); $result = api_direct_messages_box('json', 'sentbox', 'true');
self::assertEquals( self::assertEquals(
[ [
@ -1418,6 +1447,7 @@ class ApiTest extends FixtureTest
], ],
$result $result
); );
*/
} }
/** /**
@ -1427,8 +1457,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithRss() public function testApiDirectMessagesBoxWithRss()
{ {
$result = api_direct_messages_box('rss', 'sentbox', 'false'); //$result = api_direct_messages_box('rss', 'sentbox', 'false');
self::assertXml($result, 'direct-messages'); //self::assertXml($result, 'direct-messages');
} }
/** /**
@ -1438,9 +1468,9 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesBoxWithUnallowedUser() public function testApiDirectMessagesBoxWithUnallowedUser()
{ {
$this->expectException(\Friendica\Network\HTTPException\UnauthorizedException::class); //$this->expectException(\Friendica\Network\HTTPException\UnauthorizedException::class);
BasicAuth::setCurrentUserID(); //BasicAuth::setCurrentUserID();
api_direct_messages_box('json', 'sentbox', 'false'); //api_direct_messages_box('json', 'sentbox', 'false');
} }
/** /**
@ -1450,8 +1480,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesSentbox() public function testApiDirectMessagesSentbox()
{ {
$result = api_direct_messages_sentbox('json'); //$result = api_direct_messages_sentbox('json');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1461,8 +1491,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesInbox() public function testApiDirectMessagesInbox()
{ {
$result = api_direct_messages_inbox('json'); //$result = api_direct_messages_inbox('json');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1472,8 +1502,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesAll() public function testApiDirectMessagesAll()
{ {
$result = api_direct_messages_all('json'); //$result = api_direct_messages_all('json');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1483,8 +1513,8 @@ class ApiTest extends FixtureTest
*/ */
public function testApiDirectMessagesConversation() public function testApiDirectMessagesConversation()
{ {
$result = api_direct_messages_conversation('json'); //$result = api_direct_messages_conversation('json');
self::assertArrayHasKey('direct_message', $result); //self::assertArrayHasKey('direct_message', $result);
} }
/** /**
@ -1746,9 +1776,9 @@ class ApiTest extends FixtureTest
*/ */
public function testApiCleanPlainItems() public function testApiCleanPlainItems()
{ {
$_REQUEST['include_entities'] = 'true'; //$_REQUEST['include_entities'] = 'true';
$result = api_clean_plain_items('some_text [url="some_url"]some_text[/url]'); //$result = api_clean_plain_items('some_text [url="some_url"]some_text[/url]');
self::assertEquals('some_text [url="some_url"]"some_url"[/url]', $result); //self::assertEquals('some_text [url="some_url"]"some_url"[/url]', $result);
} }
/** /**

View File

@ -0,0 +1,84 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Test\src\Module\Api\Friendica\DirectMessages;
use Friendica\App\Router;
use Friendica\DI;
use Friendica\Factory\Api\Twitter\DirectMessage;
use Friendica\Module\Api\Friendica\DirectMessages\Search;
use Friendica\Test\src\Module\Api\ApiTest;
use Psr\Log\NullLogger;
class SearchTest extends ApiTest
{
public function testEmpty()
{
$directMessage = new DirectMessage(new NullLogger(), DI::dba(), DI::twitterUser());
$response = (new Search($directMessage, DI::dba(), DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), ['REQUEST_METHOD' => Router::GET]))->run();
$json = $this->toJson($response);
$assert = new \stdClass();
$assert->result = 'error';
$assert->message = 'searchstring not specified';
self::assertEquals($assert, $json);
}
public function testMail()
{
$this->loadFixture(__DIR__ . '/../../../../../datasets/mail/mail.fixture.php', DI::dba());
$directMessage = new DirectMessage(new NullLogger(), DI::dba(), DI::twitterUser());
$search = new Search($directMessage, DI::dba(), DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), ['REQUEST_METHOD' => Router::GET]);
$response = $search->run(['searchstring' => 'test']);
$json = $this->toJson($response);
self::assertTrue($json->success);
foreach ($json->search_results as $searchResult) {
self::assertIsObject($searchResult->sender);
self::assertIsInt($searchResult->id);
self::assertIsInt($searchResult->sender_id);
self::assertIsObject($searchResult->recipient);
}
}
public function testNothingFound()
{
$directMessage = new DirectMessage(new NullLogger(), DI::dba(), DI::twitterUser());
$search = new Search($directMessage, DI::dba(), DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), ['REQUEST_METHOD' => Router::GET]);
$response = $search->run(['searchstring' => 'test']);
$json = $this->toJson($response);
$assert = new \stdClass();
$assert->success = false;
$assert->search_results = 'nothing found';
self::assertEquals($assert, $json);
}
}