Merge pull request #6982 from nextcloud/autocomplete-gui

Comments AutoCompletion
This commit is contained in:
blizzz 2017-11-01 17:00:32 +01:00 committed by GitHub
commit db48575d32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 1721 additions and 114 deletions

3
apps/comments/.bowerrc Normal file
View File

@ -0,0 +1,3 @@
{
"directory": "js/vendor"
}

View File

@ -27,6 +27,7 @@ $eventDispatcher->addListener(
function() {
\OCP\Util::addScript('oc-backbone-webdav');
\OCP\Util::addScript('comments', 'merged');
\OCP\Util::addStyle('comments', 'autocomplete');
\OCP\Util::addStyle('comments', 'comments');
}
);

View File

@ -28,4 +28,10 @@
<provider>OCA\Comments\Activity\Provider</provider>
</providers>
</activity>
<collaboration>
<plugins>
<plugin type="autocomplete-sort">OCA\Comments\Collaboration\CommentersSorter</plugin>
</plugins>
</collaboration>
</info>

View File

@ -11,8 +11,10 @@ return array(
'OCA\\Comments\\Activity\\Provider' => $baseDir . '/../lib/Activity/Provider.php',
'OCA\\Comments\\Activity\\Setting' => $baseDir . '/../lib/Activity/Setting.php',
'OCA\\Comments\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
'OCA\\Comments\\Collaboration\\CommentersSorter' => $baseDir . '/../lib/Collaboration/CommentersSorter.php',
'OCA\\Comments\\Controller\\Notifications' => $baseDir . '/../lib/Controller/Notifications.php',
'OCA\\Comments\\EventHandler' => $baseDir . '/../lib/EventHandler.php',
'OCA\\Comments\\JSSettingsHelper' => $baseDir . '/../lib/JSSettingsHelper.php',
'OCA\\Comments\\Notification\\Listener' => $baseDir . '/../lib/Notification/Listener.php',
'OCA\\Comments\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php',
);

View File

@ -26,8 +26,10 @@ class ComposerStaticInitComments
'OCA\\Comments\\Activity\\Provider' => __DIR__ . '/..' . '/../lib/Activity/Provider.php',
'OCA\\Comments\\Activity\\Setting' => __DIR__ . '/..' . '/../lib/Activity/Setting.php',
'OCA\\Comments\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
'OCA\\Comments\\Collaboration\\CommentersSorter' => __DIR__ . '/..' . '/../lib/Collaboration/CommentersSorter.php',
'OCA\\Comments\\Controller\\Notifications' => __DIR__ . '/..' . '/../lib/Controller/Notifications.php',
'OCA\\Comments\\EventHandler' => __DIR__ . '/..' . '/../lib/EventHandler.php',
'OCA\\Comments\\JSSettingsHelper' => __DIR__ . '/..' . '/../lib/JSSettingsHelper.php',
'OCA\\Comments\\Notification\\Listener' => __DIR__ . '/..' . '/../lib/Notification/Listener.php',
'OCA\\Comments\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php',
);

View File

@ -0,0 +1,77 @@
/**
* based upon apps/comments/js/vendor/At.js/dist/css/jquery.atwho.css,
* only changed colors and font-weight
*/
.atwho-view {
position:absolute;
top: 0;
left: 0;
display: none;
margin-top: 18px;
background: $color-main-background;
color: $color-main-text;
border: 1px solid $color-border;
border-radius: 3px;
box-shadow: 0 0 5px $color-box-shadow;
min-width: 120px;
z-index: 11110 !important;
}
.atwho-view .atwho-header {
padding: 5px;
margin: 5px;
cursor: pointer;
border-bottom: solid 1px $color-border;
color: $color-main-text;
font-size: 11px;
font-weight: bold;
}
.atwho-view .atwho-header .small {
color: $color-main-text;
float: right;
padding-top: 2px;
margin-right: -5px;
font-size: 12px;
font-weight: normal;
}
.atwho-view .atwho-header:hover {
cursor: default;
}
.atwho-view .cur {
background: $color-primary;
color: $color-primary-text;
}
.atwho-view .cur small {
color: $color-primary-text;
}
.atwho-view strong {
color: $color-main-text;
font-weight: normal;
}
.atwho-view .cur strong {
color: $color-primary-text;
font-weight: normal;
}
.atwho-view ul {
/* width: 100px; */
list-style:none;
padding:0;
margin:auto;
max-height: 200px;
overflow-y: auto;
}
.atwho-view ul li {
display: block;
padding: 5px 10px;
border-bottom: 1px solid $color-border;
cursor: pointer;
}
.atwho-view small {
font-size: smaller;
color: $color-main-text;
font-weight: normal;
}

View File

@ -48,22 +48,30 @@
margin-right: 6px;
}
#commentsTabView .newCommentForm textarea {
#commentsTabView .newCommentForm div.message {
resize: none;
}
#commentsTabView .newCommentForm div.message:empty:before {
content: attr(data-placeholder);
color: grey;
}
#commentsTabView .comment {
position: relative;
margin-bottom: 30px;
}
#commentsTabView .comment .avatar {
#commentsTabView .comment .avatar,
.atwho-view-ul * .avatar{
width: 32px;
height: 32px;
line-height: 32px;
}
#commentsTabView .comment .message .avatar {
#commentsTabView .comment .message .avatar,
.atwho-view-ul * .avatar
{
display: inline-block;
}
@ -112,11 +120,16 @@
}
#commentsTabView .comments li .message .avatar-name-wrapper,
.atwho-view-ul * .avatar-name-wrapper,
#commentsTabView .comment .authorRow {
position: relative;
cursor: pointer;
}
.atwho-view-ul * .avatar-name-wrapper {
white-space: nowrap;
}
#commentsTabView .comment .author,
#commentsTabView .comment .date {
opacity: .5;

View File

@ -30,7 +30,7 @@
'{{/if}}' +
' </div>' +
' <form class="newCommentForm">' +
' <textarea rows="1" class="message" placeholder="{{newMessagePlaceholder}}">{{message}}</textarea>' +
' <div contentEditable="true" class="message" data-placeholder="{{newMessagePlaceholder}}">{{message}}</div>' +
' <input class="submit icon-confirm" type="submit" value="" />' +
'{{#if isEditMode}}' +
' <input class="cancel pull-right" type="button" value="{{cancelText}}" />' +
@ -62,6 +62,7 @@
/** @lends OCA.Comments.CommentsTabView.prototype */ {
id: 'commentsTabView',
className: 'tab commentsTabView',
_autoCompleteData: undefined,
events: {
'submit .newCommentForm': '_onSubmitComment',
@ -69,7 +70,11 @@
'click .action.edit': '_onClickEditComment',
'click .action.delete': '_onClickDeleteComment',
'click .cancel': '_onClickCloseComment',
'click .comment': '_onClickComment'
'click .comment': '_onClickComment',
'keyup div.message': '_onTextChange',
'change div.message': '_onTextChange',
'input div.message': '_onTextChange',
'paste div.message': '_onPaste'
},
_commentMaxLength: 1000,
@ -80,11 +85,12 @@
this.collection.on('request', this._onRequest, this);
this.collection.on('sync', this._onEndRequest, this);
this.collection.on('add', this._onAddModel, this);
this.collection.on('change:message', this._onChangeModel, this);
this._commentMaxThreshold = this._commentMaxLength * 0.9;
// TODO: error handling
_.bindAll(this, '_onTypeComment');
_.bindAll(this, '_onTypeComment', '_initAutoComplete', '_onAutoComplete');
},
template: function(params) {
@ -140,8 +146,10 @@
setFileInfo: function(fileInfo) {
if (fileInfo) {
this.model = fileInfo;
this.render();
this.collection.setObjectId(fileInfo.id);
this._initAutoComplete($('#commentsTabView').find('.newCommentForm .message'));
this.collection.setObjectId(this.model.id);
// reset to first page
this.collection.reset([], {silent: true});
this.nextPage();
@ -164,7 +172,85 @@
this.delegateEvents();
this.$el.find('.message').on('keydown input change', this._onTypeComment);
autosize(this.$el.find('.newCommentRow textarea'))
autosize(this.$el.find('.newCommentRow .message'))
},
_initAutoComplete: function($target) {
var s = this;
var limit = 10;
if(!_.isUndefined(OC.appConfig.comments)) {
limit = OC.appConfig.comments.maxAutoCompleteResults;
}
$target.atwho({
at: '@',
limit: limit,
callbacks: {
remoteFilter: s._onAutoComplete,
highlighter: function (li) {
// misuse the highlighter callback to instead of
// highlighting loads the avatars.
var $li = $(li);
$li.find('.avatar').avatar(undefined, 32);
return $li;
},
sorter: function (q, items) { return items; }
},
displayTpl: '<li>'
+ '<span class="avatar-name-wrapper">'
+ '<div class="avatar" '
+ 'data-username="${id}"' // for avatars
+ ' data-user="${id}"' // for contactsmenu
+ ' data-user-display-name="${label}"></div>'
+ ' <strong>${label}</strong>'
+ '</span></li>',
insertTpl: ''
+ '<span class="avatar-name-wrapper">'
+ '<div class="avatar" '
+ 'data-username="${id}"' // for avatars
+ ' data-user="${id}"' // for contactsmenu
+ ' data-user-display-name="${label}"></div>'
+ ' <strong>${label}</strong>'
+ '</span>',
searchKey: "label"
});
$target.on('inserted.atwho', function (je, $el) {
s._postRenderItem(
// we need to pass the parent of the inserted element
// passing the whole comments form would re-apply and request
// avatars from the server
$(je.target).find(
'div[data-username="' + $el.find('[data-username]').data('username') + '"]'
).parent()
);
});
},
_onAutoComplete: function(query, callback) {
if(_.isEmpty(query)) {
return;
}
var s = this;
if(!_.isUndefined(this._autoCompleteRequestTimer)) {
clearTimeout(this._autoCompleteRequestTimer);
}
this._autoCompleteRequestTimer = _.delay(function() {
if(!_.isUndefined(this._autoCompleteRequestCall)) {
this._autoCompleteRequestCall.abort();
}
this._autoCompleteRequestCall = $.get(
OC.generateUrl('/autocomplete/get'),
{
search: query,
itemType: 'files',
itemId: s.model.get('id'),
sorter: 'commenters|share-recipients',
limit: OC.appConfig.comments.maxAutoCompleteResults
},
function (data) {
callback(data);
}
);
}, 400);
},
_formatItem: function(commentModel) {
@ -215,15 +301,80 @@
}
},
/**
* takes care of post-rendering after a new comment was added to the
* collection
*
* @param model
* @param collection
* @param options
* @private
*/
_onAddModel: function(model, collection, options) {
var $el = $(this.commentTemplate(this._formatItem(model)));
// we need to render it immediately, to ensure that the right
// order of comments is kept on opening comments tab
var $comment = $(this.commentTemplate(this._formatItem(model)));
if (!_.isUndefined(options.at) && collection.length > 1) {
this.$container.find('li').eq(options.at).before($el);
this.$container.find('li').eq(options.at).before($comment);
} else {
this.$container.append($el);
this.$container.append($comment);
}
this._postRenderItem($comment);
$('#commentsTabView').find('.newCommentForm div.message').text('').prop('disabled', false);
// we need to update the model, because it consists of client data
// only, but the server might add meta data, e.g. about mentions
var oldMentions = model.get('mentions');
var self = this;
model.fetch({
success: function (model) {
if(_.isEqual(oldMentions, model.get('mentions'))) {
// don't attempt to render if unnecessary, avoids flickering
return;
}
var $updated = $(self.commentTemplate(self._formatItem(model)));
$comment.html($updated.html());
self._postRenderItem($comment);
}
})
},
/**
* takes care of post-rendering after a new comment was edited
*
* @param model
* @private
*/
_onChangeModel: function (model) {
if(model.get('message').trim() === model.previous('message').trim()) {
return;
}
this._postRenderItem($el);
var $form = this.$container.find('.comment[data-id="' + model.id + '"] form');
var $row = $form.closest('.comment');
var $target = $row.data('commentEl');
if(_.isUndefined($target)) {
// ignore noise this is only set after editing a comment and hitting post
return;
}
var self = this;
// we need to update the model, because it consists of client data
// only, but the server might add meta data, e.g. about mentions
model.fetch({
success: function (model) {
$target.removeClass('hidden');
$row.remove();
var $message = $target.find('.message');
$message
.html(self._formatMessage(model.get('message'), model.get('mentions')))
.find('.avatar')
.each(function () { $(this).avatar(); });
self._postRenderItem($message);
}
});
},
_postRenderItem: function($el) {
@ -240,6 +391,10 @@
}
var $message = $el.find('.message');
if($message.length === 0) {
// it is the case when writing a comment and mentioning a person
$message = $el;
}
this._postRenderMessage($message);
},
@ -261,19 +416,15 @@
message = escapeHTML(message).replace(/\n/g, '<br/>');
for(var i in mentions) {
if(!mentions.hasOwnProperty(i)) {
return;
}
var mention = '@' + mentions[i].mentionId;
var avatar = '<div class="avatar" '
+ 'data-user="' + _.escape(mentions[i].mentionId) + '"'
+' data-user-display-name="'
+ _.escape(mentions[i].mentionDisplayName) + '"></div>';
// escape possible regex characters in the name
mention = mention.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
var displayName = ''
+ '<span class="avatar-name-wrapper">'
+ avatar + ' <strong>'+ _.escape(mentions[i].mentionDisplayName)+'</strong>'
+ '</span>';
var displayName = this._composeHTMLMention(mentions[i].mentionId, mentions[i].mentionDisplayName);
// replace every mention either at the start of the input or after a whitespace
// followed by a non-word character.
@ -284,10 +435,24 @@
}
);
}
return message;
},
_composeHTMLMention: function(uid, displayName) {
var avatar = '<div class="avatar" '
+ 'data-username="' + _.escape(uid) + '"'
+ ' data-user="' + _.escape(uid) + '"'
+ ' data-user-display-name="'
+ _.escape(displayName) + '"></div>';
return ''
+ '<span class="atwho-inserted" contenteditable="false">'
+ '<span class="avatar-name-wrapper">'
+ avatar + ' <strong>'+ _.escape(displayName)+'</strong>'
+ '</span>'
+ '</span>';
},
nextPage: function() {
if (this._loading || !this.collection.hasMoreResults()) {
return;
@ -310,14 +475,24 @@
// spawn form
$comment.after($formRow);
$formRow.data('commentEl', $comment);
$formRow.find('textarea').on('keydown input change', this._onTypeComment);
$formRow.find('.message').on('keydown input change', this._onTypeComment);
// copy avatar element from original to avoid flickering
$formRow.find('.avatar:first').replaceWith($comment.find('.avatar:first').clone());
$formRow.find('.has-tooltip').tooltip();
var $message = $formRow.find('.message');
$message
.html(this._formatMessage(commentToEdit.get('message'), commentToEdit.get('mentions')))
.find('.avatar')
.each(function () { $(this).avatar(); });
this._postRenderItem($message);
// Enable autosize
autosize($formRow.find('textarea'));
autosize($formRow.find('.message'));
// enable autocomplete
this._initAutoComplete($formRow.find('.message'));
return false;
},
@ -393,48 +568,41 @@
},
/**
* takes care of updating comment elements after submit (either new
* takes care of updating comment element states after submit (either new
* comment or edit).
*
* @param {OC.Backbone.Model} model
* @param {jQuery} $form
* @param {string|undefined} commentId
* @private
*/
_onSubmitSuccess: function(model, $form, commentId) {
var self = this;
_onSubmitSuccess: function(model, $form) {
var $submit = $form.find('.submit');
var $loading = $form.find('.submitLoading');
var $textArea = $form.find('.message');
model.fetch({
success: function(model) {
$submit.removeClass('hidden');
$loading.addClass('hidden');
var $target;
$submit.removeClass('hidden');
$loading.addClass('hidden');
},
if(!_.isUndefined(commentId)) {
var $row = $form.closest('.comment');
$target = $row.data('commentEl');
$target.removeClass('hidden');
$row.remove();
} else {
$target = $('.commentsTabView .comments').find('li:first');
$textArea.val('').prop('disabled', false);
}
_commentBodyHTML2Plain: function($el) {
var $comment = $el.clone();
var $message = $target.find('.message');
$message
.html(self._formatMessage(model.get('message'), model.get('mentions')))
.find('.avatar')
.each(function () { $(this).avatar(); });
self._postRenderMessage($message);
},
error: function () {
self._onSubmitError($form, commentId);
}
$comment.find('.avatar-name-wrapper').each(function () {
var $this = $(this);
var $inserted = $this.parent();
$inserted.html('@' + $this.find('.avatar').data('username'));
});
var oldHtml;
var html = $comment.html();
do {
// replace works one by one
oldHtml = html;
html = oldHtml.replace("<br>", "\n"); // preserve line breaks
console.warn(html)
} while(oldHtml !== html);
$comment.html(html);
return $comment.text();
},
_onSubmitComment: function(e) {
@ -444,26 +612,27 @@
var currentUser = OC.getCurrentUser();
var $submit = $form.find('.submit');
var $loading = $form.find('.submitLoading');
var $textArea = $form.find('.message');
var message = $textArea.val().trim();
var $commentField = $form.find('.message');
var message = $commentField.text().trim();
e.preventDefault();
if (!message.length || message.length > this._commentMaxLength) {
return;
}
$textArea.prop('disabled', true);
$commentField.prop('disabled', true);
$submit.addClass('hidden');
$loading.removeClass('hidden');
message = this._commentBodyHTML2Plain($commentField);
if (commentId) {
// edit mode
var comment = this.collection.get(commentId);
comment.save({
message: $textArea.val()
message: message
}, {
success: function(model) {
self._onSubmitSuccess(model, $form, commentId);
self._onSubmitSuccess(model, $form);
},
error: function() {
self._onSubmitError($form, commentId);
@ -475,7 +644,7 @@
actorDisplayName: currentUser.displayName,
actorType: 'users',
verb: 'comment',
message: $textArea.val(),
message: message,
creationDateTime: (new Date()).toUTCString()
}, {
at: 0,
@ -485,7 +654,7 @@
self._onSubmitSuccess(model, $form);
},
error: function() {
self._onSubmitError($form);
self._onSubmitError($form, undefined);
}
});
}
@ -513,6 +682,31 @@
}
},
/**
* ensures the contenteditable div is really empty, when user removed
* all input, so that the placeholder will be shown again
*
* @private
*/
_onTextChange: function() {
var $message = $('#commentsTabView').find('.newCommentForm div.message');
if(!$message.text().trim().length) {
$message.empty();
}
},
/**
* Limit pasting to plain text
*
* @param e
* @private
*/
_onPaste: function (e) {
e.preventDefault();
var text = e.originalEvent.clipboardData.getData("text/plain");
document.execCommand('insertText', false, text);
},
/**
* Returns whether the given message is long and needs
* collapsing

View File

@ -5,5 +5,7 @@
"commentsummarymodel.js",
"commentstabview.js",
"filesplugin.js",
"activitytabviewplugin.js"
"activitytabviewplugin.js",
"vendor/Caret.js/dist/jquery.caret.min.js",
"vendor/At.js/dist/js/jquery.atwho.min.js"
]

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -22,7 +22,9 @@
namespace OCA\Comments\AppInfo;
use OCA\Comments\Controller\Notifications;
use OCA\Comments\JSSettingsHelper;
use OCP\AppFramework\App;
use OCP\Util;
class Application extends App {
@ -31,5 +33,8 @@ class Application extends App {
$container = $this->getContainer();
$container->registerAlias('NotificationsController', Notifications::class);
$jsSettingsHelper = new JSSettingsHelper($container->getServer());
Util::connectHook('\OCP\Config', 'js', $jsSettingsHelper, 'extend');
}
}

View File

@ -0,0 +1,115 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Comments\Collaboration;
use OCP\Collaboration\AutoComplete\ISorter;
use OCP\Comments\ICommentsManager;
class CommentersSorter implements ISorter {
/** @var ICommentsManager */
private $commentsManager;
public function __construct(ICommentsManager $commentsManager) {
$this->commentsManager = $commentsManager;
}
public function getId() {
return 'commenters';
}
/**
* Sorts people who commented on the given item atop (descelating) of the
* others
*
* @param array $sortArray
* @param array $context
*/
public function sort(array &$sortArray, array $context) {
$commenters = $this->retrieveCommentsInformation($context['itemType'], $context['itemId']);
if(count($commenters) === 0) {
return;
}
foreach ($sortArray as $type => &$byType) {
if(!isset($commenters[$type])) {
continue;
}
// at least on PHP 5.6 usort turned out to be not stable. So we add
// the current index to the value and compare it on a draw
$i = 0;
$workArray = array_map(function($element) use (&$i) {
return [$i++, $element];
}, $byType);
usort($workArray, function ($a, $b) use ($commenters, $type) {
$r = $this->compare($a[1], $b[1], $commenters[$type]);
if($r === 0) {
$r = $a[0] - $b[0];
}
return $r;
});
// and remove the index values again
$byType = array_column($workArray, 1);
}
}
/**
* @param $type
* @param $id
* @return array
*/
protected function retrieveCommentsInformation($type, $id) {
$comments = $this->commentsManager->getForObject($type, $id);
if(count($comments) === 0) {
return [];
}
$actors = [];
foreach ($comments as $comment) {
if(!isset($actors[$comment->getActorType()])) {
$actors[$comment->getActorType()] = [];
}
if(!isset($actors[$comment->getActorType()][$comment->getActorId()])) {
$actors[$comment->getActorType()][$comment->getActorId()] = 1;
} else {
$actors[$comment->getActorType()][$comment->getActorId()]++;
}
}
return $actors;
}
protected function compare(array $a, array $b, array $commenters) {
$a = $a['value']['shareWith'];
$b = $b['value']['shareWith'];
$valueA = isset($commenters[$a]) ? $commenters[$a] : 0;
$valueB = isset($commenters[$b]) ? $commenters[$b] : 0;
return $valueB - $valueA;
}
}

View File

@ -0,0 +1,45 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Comments;
use OCP\IServerContainer;
class JSSettingsHelper {
/** @var IServerContainer */
private $c;
public function __construct(IServerContainer $c) {
$this->c = $c;
}
public function extend(array $settings) {
$appConfig = json_decode($settings['array']['oc_appconfig'], true);
$value = (int)$this->c->getConfig()->getAppValue('comments', 'maxAutoCompleteResults', 10);
$appConfig['comments']['maxAutoCompleteResults'] = $value;
$settings['array']['oc_appconfig'] = json_encode($appConfig);
}
}

View File

@ -0,0 +1,160 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Comments\Tests\Unit\Collaboration;
use OCA\Comments\Collaboration\CommentersSorter;
use OCP\Comments\IComment;
use OCP\Comments\ICommentsManager;
use OCP\IConfig;
use Test\TestCase;
class CommentersSorterTest extends TestCase {
/** @var ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */
protected $commentsManager;
/** @var CommentersSorter */
protected $sorter;
public function setUp() {
parent::setUp();
$this->commentsManager = $this->createMock(ICommentsManager::class);
$this->sorter = new CommentersSorter($this->commentsManager);
}
/**
* @dataProvider sortDataProvider
* @param $data
*/
public function testSort($data) {
$commentMocks = [];
foreach($data['actors'] as $actorType => $actors) {
foreach ($actors as $actorId => $noOfComments) {
for($i=0;$i<$noOfComments;$i++) {
$mock = $this->createMock(IComment::class);
$mock->expects($this->atLeastOnce())
->method('getActorType')
->willReturn($actorType);
$mock->expects($this->atLeastOnce())
->method('getActorId')
->willReturn($actorId);
$commentMocks[] = $mock;
}
}
}
$this->commentsManager->expects($this->once())
->method('getForObject')
->willReturn($commentMocks);
$workArray = $data['input'];
$this->sorter->sort($workArray, ['itemType' => 'files', 'itemId' => '24']);
$this->assertEquals($data['expected'], $workArray);
}
public function sortDataProvider() {
return [[
[
#1 sort properly and otherwise keep existing order
'actors' => ['users' => ['celia' => 3, 'darius' => 7, 'faruk' => 5, 'gail' => 5], 'bots' => ['r2-d2' => 8]],
'input' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
'users' =>
[
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'elena']],
],
'bots' => [
['value' => ['shareWith' => 'r2-d2']],
['value' => ['shareWith' => 'c-3po']],
]
],
],
[
#2 no commentors, input equals output
'actors' => [],
'input' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
],
[
#3 no nothing
'actors' => [],
'input' => [],
'expected' => [],
],
]];
}
}

View File

@ -0,0 +1,73 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Comments\Tests\Unit;
use OCA\Comments\JSSettingsHelper;
use OCP\IConfig;
use OCP\IServerContainer;
use Test\TestCase;
class JSSettingsHelperTest extends TestCase {
/** @var IServerContainer|\PHPUnit_Framework_MockObject_MockObject */
protected $c;
/** @var JSSettingsHelper */
protected $helper;
public function setUp() {
parent::setUp();
$this->c = $this->createMock(IServerContainer::class);
$this->helper = new JSSettingsHelper($this->c);
}
public function testExtend() {
$config = $this->createMock(IConfig::class);
$config->expects($this->once())
->method('getAppValue')
->with('comments', 'maxAutoCompleteResults')
->willReturn(13);
$this->c->expects($this->once())
->method('getConfig')
->willReturn($config);
$config = [
'oc_appconfig' => json_encode([
'anotherapp' => [
'foo' => 'bar',
'foobar' => true
]
])
];
$this->helper->extend(['array' => &$config]);
$appConfig = json_decode($config['oc_appconfig'], true);
$this->assertTrue(isset($appConfig['comments']));
$this->assertTrue(isset($appConfig['anotherapp']));
$this->assertSame(2, count($appConfig['anotherapp']));
$this->assertSame(13, $appConfig['comments']['maxAutoCompleteResults']);
}
}

View File

@ -157,7 +157,7 @@ describe('OCA.Comments.CommentsTabView tests', function() {
expect($comment.find('.avatar[data-user=macbeth] ~ .contactsmenu-popover').length).toEqual(1);
expect($comment.find('.avatar[data-user=banquo]').length).toEqual(1);
expect($comment.find('.avatar-name-wrapper:last-child strong').text()).toEqual('Lord Banquo');
expect($comment.find('.avatar[data-user=banquo] ~ strong').text()).toEqual('Lord Banquo');
expect($comment.find('.avatar[data-user=banquo] ~ .contactsmenu-popover').length).toEqual(1);
});
@ -239,7 +239,7 @@ describe('OCA.Comments.CommentsTabView tests', function() {
});
it('creates a new comment when clicking post button', function() {
view.$el.find('.message').val('New message');
view.$el.find('.message').text('New message');
view.$el.find('form').submit();
expect(createStub.calledOnce).toEqual(true);
@ -253,7 +253,7 @@ describe('OCA.Comments.CommentsTabView tests', function() {
});
});
it('creates a new comment with mentions when clicking post button', function() {
view.$el.find('.message').val('New message @anotheruser');
view.$el.find('.message').text('New message @anotheruser');
view.$el.find('form').submit();
var createStubExpectedData = {
@ -439,7 +439,7 @@ describe('OCA.Comments.CommentsTabView tests', function() {
var $formRow = view.$el.find('.newCommentRow.comment[data-id=1]');
expect($formRow.length).toEqual(1);
$formRow.find('textarea').val('modified message');
$formRow.find('div.message').text('modified message');
$formRow.find('form').submit();
expect(saveStub.calledOnce).toEqual(true);
@ -451,8 +451,9 @@ describe('OCA.Comments.CommentsTabView tests', function() {
// simulate the fact that save sets the attribute
model.set('message', 'modified\nmessage');
saveStub.yieldTo('success', model);
view.collection.get(model);
expect(fetchStub.calledOnce).toEqual(true);
expect(fetchStub.called).toEqual(true);
fetchStub.yieldTo('success', model);
// original comment element is visible again
@ -472,7 +473,7 @@ describe('OCA.Comments.CommentsTabView tests', function() {
var $formRow = view.$el.find('.newCommentRow.comment[data-id=3]');
expect($formRow.length).toEqual(1);
$formRow.find('textarea').val('modified\nmessage @anotheruser');
$formRow.find('div.message').text('modified\nmessage @anotheruser');
$formRow.find('form').submit();
expect(saveStub.calledOnce).toEqual(true);
@ -485,7 +486,7 @@ describe('OCA.Comments.CommentsTabView tests', function() {
model.set('message', 'modified\nmessage @anotheruser');
saveStub.yieldTo('success', model);
expect(fetchStub.calledOnce).toEqual(true);
expect(fetchStub.called).toEqual(true);
// simulate the fact that fetch sets the attribute
model.set('mentions', {

View File

@ -59,4 +59,10 @@ Turning the feature off removes shared files and folders on the server for all s
<step>OCA\Files_Sharing\Migration\SetPasswordColumn</step>
</post-migration>
</repair-steps>
<collaboration>
<plugins>
<plugin type="autocomplete-sort">OCA\Files_Sharing\Collaboration\ShareRecipientSorter</plugin>
</plugins>
</collaboration>
</info>

View File

@ -19,6 +19,7 @@ return array(
'OCA\\Files_Sharing\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
'OCA\\Files_Sharing\\Cache' => $baseDir . '/../lib/Cache.php',
'OCA\\Files_Sharing\\Capabilities' => $baseDir . '/../lib/Capabilities.php',
'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => $baseDir . '/../lib/Collaboration/ShareRecipientSorter.php',
'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => $baseDir . '/../lib/Command/CleanupRemoteStorages.php',
'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => $baseDir . '/../lib/Controller/ExternalSharesController.php',
'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => $baseDir . '/../lib/Controller/PublicPreviewController.php',

View File

@ -34,6 +34,7 @@ class ComposerStaticInitFiles_Sharing
'OCA\\Files_Sharing\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
'OCA\\Files_Sharing\\Cache' => __DIR__ . '/..' . '/../lib/Cache.php',
'OCA\\Files_Sharing\\Capabilities' => __DIR__ . '/..' . '/../lib/Capabilities.php',
'OCA\\Files_Sharing\\Collaboration\\ShareRecipientSorter' => __DIR__ . '/..' . '/../lib/Collaboration/ShareRecipientSorter.php',
'OCA\\Files_Sharing\\Command\\CleanupRemoteStorages' => __DIR__ . '/..' . '/../lib/Command/CleanupRemoteStorages.php',
'OCA\\Files_Sharing\\Controller\\ExternalSharesController' => __DIR__ . '/..' . '/../lib/Controller/ExternalSharesController.php',
'OCA\\Files_Sharing\\Controller\\PublicPreviewController' => __DIR__ . '/..' . '/../lib/Controller/PublicPreviewController.php',

View File

@ -0,0 +1,110 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Sharing\Collaboration;
use OCP\Collaboration\AutoComplete\ISorter;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\IUserSession;
use OCP\Share\IManager;
class ShareRecipientSorter implements ISorter {
/** @var IManager */
private $shareManager;
/** @var Folder */
private $rootFolder;
/** @var IUserSession */
private $userSession;
public function __construct(IManager $shareManager, IRootFolder $rootFolder, IUserSession $userSession) {
$this->shareManager = $shareManager;
$this->rootFolder = $rootFolder;
$this->userSession = $userSession;
}
public function getId() {
return 'share-recipients';
}
public function sort(array &$sortArray, array $context) {
// let's be tolerant. Comments uses "files" by default, other usages are often singular
if($context['itemType'] !== 'files' && $context['itemType'] !== 'file') {
return;
}
$user = $this->userSession->getUser();
if($user === null) {
return;
}
$userFolder = $this->rootFolder->getUserFolder($user->getUID());
/** @var Node[] $nodes */
$nodes = $userFolder->getById((int)$context['itemId']);
if(count($nodes) === 0) {
return;
}
$al = $this->shareManager->getAccessList($nodes[0]);
foreach ($sortArray as $type => &$byType) {
if(!isset($al[$type]) || !is_array($al[$type])) {
continue;
}
// at least on PHP 5.6 usort turned out to be not stable. So we add
// the current index to the value and compare it on a draw
$i = 0;
$workArray = array_map(function($element) use (&$i) {
return [$i++, $element];
}, $byType);
usort($workArray, function ($a, $b) use ($al, $type) {
$result = $this->compare($a[1], $b[1], $al[$type]);
if($result === 0) {
$result = $a[0] - $b[0];
}
return $result;
});
// and remove the index values again
$byType = array_column($workArray, 1);
}
}
/**
* @param array $a
* @param array $b
* @param array $al
* @return int
*/
protected function compare(array $a, array $b, array $al) {
$a = $a['value']['shareWith'];
$b = $b['value']['shareWith'];
$valueA = (int)in_array($a, $al, true);
$valueB = (int)in_array($b, $al, true);
return $valueB - $valueA;
}
}

View File

@ -0,0 +1,258 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Files_Sharing\Tests\Collaboration;
use OCA\Files_Sharing\Collaboration\ShareRecipientSorter;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Share\IManager;
use Test\TestCase;
class ShareRecipientSorterTest extends TestCase {
/** @var IManager|\PHPUnit_Framework_MockObject_MockObject */
protected $shareManager;
/** @var IRootFolder|\PHPUnit_Framework_MockObject_MockObject */
protected $rootFolder;
/** @var IUserSession|\PHPUnit_Framework_MockObject_MockObject */
protected $userSession;
/** @var ShareRecipientSorter */
protected $sorter;
public function setUp() {
parent::setUp();
$this->shareManager = $this->createMock(IManager::class);
$this->rootFolder = $this->createMock(IRootFolder::class);
$this->userSession = $this->createMock(IUserSession::class);
$this->sorter = new ShareRecipientSorter($this->shareManager, $this->rootFolder, $this->userSession);
}
/**
* @dataProvider sortDataProvider
* @param $data
*/
public function testSort($data) {
$node = $this->createMock(Node::class);
/** @var Folder|\PHPUnit_Framework_MockObject_MockObject $folder */
$folder = $this->createMock(Folder::class);
$this->rootFolder->expects($this->any())
->method('getUserFolder')
->willReturn($folder);
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
->willReturn('yvonne');
$this->userSession->expects($this->once())
->method('getUser')
->willReturn($user);
if ($data['context']['itemType'] === 'files') {
$folder->expects($this->once())
->method('getById')
->with($data['context']['itemId'])
->willReturn([$node]);
$this->shareManager->expects($this->once())
->method('getAccessList')
->with($node)
->willReturn($data['accessList']);
} else {
$folder->expects($this->never())
->method('getById');
$this->shareManager->expects($this->never())
->method('getAccessList');
}
$workArray = $data['input'];
$this->sorter->sort($workArray, $data['context']);
$this->assertEquals($data['expected'], $workArray);
}
public function testSortNoNodes() {
/** @var Folder|\PHPUnit_Framework_MockObject_MockObject $folder */
$folder = $this->createMock(Folder::class);
$this->rootFolder->expects($this->any())
->method('getUserFolder')
->willReturn($folder);
$folder->expects($this->once())
->method('getById')
->willReturn([]);
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
->willReturn('yvonne');
$this->userSession->expects($this->once())
->method('getUser')
->willReturn($user);
$this->shareManager->expects($this->never())
->method('getAccessList');
$originalArray = [
'users' => [
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
]
];
$workArray = $originalArray;
$this->sorter->sort($workArray, ['itemType' => 'files', 'itemId' => 404]);
$this->assertEquals($originalArray, $workArray);
}
public function sortDataProvider() {
return [[
[
#0 sort properly and otherwise keep existing order
'context' => ['itemType' => 'files', 'itemId' => 42],
'accessList' => ['users' => ['celia', 'darius', 'faruk', 'gail'], 'bots' => ['r2-d2']],
'input' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
'users' =>
[
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'elena']],
],
'bots' => [
['value' => ['shareWith' => 'r2-d2']],
['value' => ['shareWith' => 'c-3po']],
]
],
],
[
#1 no recipients
'context' => ['itemType' => 'files', 'itemId' => 42],
'accessList' => ['users' => false],
'input' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
],
[
#2 unsupported item type
'context' => ['itemType' => 'announcements', 'itemId' => 42],
'accessList' => null, // not needed
'input' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
'users' =>
[
['value' => ['shareWith' => 'alice']],
['value' => ['shareWith' => 'bob']],
['value' => ['shareWith' => 'celia']],
['value' => ['shareWith' => 'darius']],
['value' => ['shareWith' => 'elena']],
['value' => ['shareWith' => 'faruk']],
['value' => ['shareWith' => 'gail']],
],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
],
[
#3 no nothing
'context' => ['itemType' => 'files', 'itemId' => 42],
'accessList' => [],
'input' => [],
'expected' => [],
],
]];
}
}

View File

@ -1853,20 +1853,19 @@ class Access extends LDAPUtility implements IUserTools {
$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
// no cookie known, although the offset is not 0. Maybe cache run out. We need
// to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
// searching was designed by MSFT?)
// Lukas: No, but thanks to reading that source I finally know!
// '0' is valid, because 389ds
$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
//a bit recursive, $offset of 0 is the exit
\OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
$this->search($filter, array($base), $attr, $limit, $reOffset, true);
// no cookie known from a potential previous search. We need
// to start from 0 to come to the desired page. cookie value
// of '0' is valid, because 389ds
$reOffset = 0;
while($reOffset < $offset) {
$this->search($filter, array($base), $attr, $limit, $reOffset, true);
$reOffset += $limit;
}
$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
// '0' is valid, because 389ds
//TODO: remember this, probably does not change in the next request...
if(empty($cookie) && $cookie !== '0') {
// '0' is valid, because 389ds
$cookie = null;
}
}

View File

@ -122,7 +122,7 @@ class Connection extends LDAPUtility {
/**
* @param string $name
* @return bool|mixed|void
* @return bool|mixed
*/
public function __get($name) {
if(!$this->configured) {

View File

@ -1232,7 +1232,6 @@ $CONFIG = array(
*/
'sharing.minSearchStringLength' => 0,
/**
* All other configuration options
*/

View File

@ -0,0 +1,102 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Controller;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\DataResponse;
use OCP\Collaboration\AutoComplete\IManager;
use OCP\Collaboration\Collaborators\ISearch;
use OCP\IConfig;
use OCP\IRequest;
use OCP\Share;
class AutoCompleteController extends Controller {
/** @var ISearch */
private $collaboratorSearch;
/** @var IManager */
private $autoCompleteManager;
/** @var IConfig */
private $config;
public function __construct(
$appName,
IRequest $request,
ISearch $collaboratorSearch,
IManager $autoCompleteManager,
IConfig $config
) {
parent::__construct($appName, $request);
$this->collaboratorSearch = $collaboratorSearch;
$this->autoCompleteManager = $autoCompleteManager;
$this->config = $config;
}
/**
* @NoAdminRequired
*
* @param string $search
* @param string $itemType
* @param string $itemId
* @param string|null $sorter can be piped, top prio first, e.g.: "commenters|share-recipients"
* @param array $shareTypes
* @param int $limit
* @return DataResponse
*/
public function get($search, $itemType, $itemId, $sorter = null, $shareTypes = [Share::SHARE_TYPE_USER], $limit = 10) {
// if enumeration/user listings are disabled, we'll receive an empty
// result from search() thus nothing else to do here.
list($results,) = $this->collaboratorSearch->search($search, $shareTypes, false, $limit, 0);
$exactMatches = $results['exact'];
unset($results['exact']);
$results = array_merge_recursive($exactMatches, $results);
$sorters = array_reverse(explode('|', $sorter));
$this->autoCompleteManager->runSorters($sorters, $results, [
'itemType' => $itemType,
'itemId' => $itemId,
]);
// transform to expected format
$results = $this->prepareResultArray($results);
return new DataResponse($results);
}
protected function prepareResultArray(array $results) {
$output = [];
foreach ($results as $type => $subResult) {
foreach ($subResult as $result) {
$output[] = [
'id' => $result['value']['shareWith'],
'label' => $result['label'],
'source' => $type,
];
}
}
return $output;
}
}

View File

@ -152,7 +152,7 @@ form #datadirField legend {
applied to the button instead. */
}
input, textarea, select, button {
input, textarea, select, button, div[contenteditable=true] {
font-family: 'Open Sans', Frutiger, Calibri, 'Myriad Pro', Myriad, sans-serif;
}
input {
@ -664,16 +664,16 @@ p.info {
margin: -9px 0 0 -9px;
}
/* Css replaced elements don't have ::after nor ::before */
img.icon-loading, object.icon-loading, video.icon-loading, button.icon-loading, textarea.icon-loading, input.icon-loading, select.icon-loading {
img.icon-loading, object.icon-loading, video.icon-loading, button.icon-loading, textarea.icon-loading, input.icon-loading, select.icon-loading, div[contenteditable=true].icon-loading {
background-image: url('../img/loading.gif');
}
img.icon-loading-dark, object.icon-loading-dark, video.icon-loading-dark, button.icon-loading-dark, textarea.icon-loading-dark, input.icon-loading-dark, select.icon-loading-dark {
img.icon-loading-dark, object.icon-loading-dark, video.icon-loading-dark, button.icon-loading-dark, textarea.icon-loading-dark, input.icon-loading-dark, select.icon-loading-dark, div[contenteditable=true].icon-loading-dark {
background-image: url('../img/loading-dark.gif');
}
img.icon-loading-small, object.icon-loading-small, video.icon-loading-small, button.icon-loading-small, textarea.icon-loading-small, input.icon-loading-small, select.icon-loading-small {
img.icon-loading-small, object.icon-loading-small, video.icon-loading-small, button.icon-loading-small, textarea.icon-loading-small, input.icon-loading-small, select.icon-loading-small, div[contenteditable=true].icon-loading-small {
background-image: url('../img/loading-small.gif');
}
img.icon-loading-small-dark, object.icon-loading-small-dark, video.icon-loading-small-dark, button.icon-loading-small-dark, textarea.icon-loading-small-dark, input.icon-loading-small-dark, select.icon-loading-small-dark {
img.icon-loading-small-dark, object.icon-loading-small-dark, video.icon-loading-small-dark, button.icon-loading-small-dark, textarea.icon-loading-small-dark, input.icon-loading-small-dark, select.icon-loading-small-dark, div[contenteditable=true].icon-loading-small-dark {
background-image: url('../img/loading-small-dark.gif');
}
@-webkit-keyframes rotate {

View File

@ -61,7 +61,7 @@
}
/* Css replaced elements don't have ::after nor ::before */
img, object, video, button, textarea, input, select {
img, object, video, button, textarea, input, select, div[contenteditable=true] {
.icon-loading {
background-image: url('../img/loading.gif');
}

View File

@ -13,7 +13,7 @@
*/
/* Specifically override browser styles */
input, textarea, select, button {
input, textarea, select, button, div[contenteditable=true] {
font-family: 'Open Sans', Frutiger, Calibri, 'Myriad Pro', Myriad, sans-serif;
}
.select2-container-multi .select2-choices .select2-search-field input, .select2-search input, .ui-widget {
@ -24,7 +24,8 @@ input, textarea, select, button {
select,
button,
input,
textarea {
textarea,
div[contenteditable=true] {
width: 130px;
min-height: 32px;
box-sizing: border-box;
@ -35,6 +36,7 @@ select,
button, .button,
input:not([type='range']),
textarea,
div[contenteditable=true],
.pager li a {
margin: 3px 3px 3px 0;
padding: 7px 6px;
@ -154,7 +156,7 @@ button, .button {
}
}
textarea {
textarea, div[contenteditable=true] {
color: nc-lighten($color-main-text, 33%);
cursor: text;
font-family: inherit;

View File

@ -62,6 +62,7 @@ $application->registerRoutes($this, [
['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'],
['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'],
['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'],
['name' => 'AutoComplete#get', 'url' => 'autocomplete/get', 'verb' => 'GET']
],
'ocs' => [
['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'],

View File

@ -68,6 +68,8 @@ return array(
'OCP\\BackgroundJob\\IJobList' => $baseDir . '/lib/public/BackgroundJob/IJobList.php',
'OCP\\Capabilities\\ICapability' => $baseDir . '/lib/public/Capabilities/ICapability.php',
'OCP\\Capabilities\\IPublicCapability' => $baseDir . '/lib/public/Capabilities/IPublicCapability.php',
'OCP\\Collaboration\\AutoComplete\\IManager' => $baseDir . '/lib/public/Collaboration/AutoComplete/IManager.php',
'OCP\\Collaboration\\AutoComplete\\ISorter' => $baseDir . '/lib/public/Collaboration/AutoComplete/ISorter.php',
'OCP\\Collaboration\\Collaborators\\ISearch' => $baseDir . '/lib/public/Collaboration/Collaborators/ISearch.php',
'OCP\\Collaboration\\Collaborators\\ISearchPlugin' => $baseDir . '/lib/public/Collaboration/Collaborators/ISearchPlugin.php',
'OCP\\Collaboration\\Collaborators\\ISearchResult' => $baseDir . '/lib/public/Collaboration/Collaborators/ISearchResult.php',
@ -390,6 +392,7 @@ return array(
'OC\\Cache\\CappedMemoryCache' => $baseDir . '/lib/private/Cache/CappedMemoryCache.php',
'OC\\Cache\\File' => $baseDir . '/lib/private/Cache/File.php',
'OC\\CapabilitiesManager' => $baseDir . '/lib/private/CapabilitiesManager.php',
'OC\\Collaboration\\AutoComplete\\Manager' => $baseDir . '/lib/private/Collaboration/AutoComplete/Manager.php',
'OC\\Collaboration\\Collaborators\\GroupPlugin' => $baseDir . '/lib/private/Collaboration/Collaborators/GroupPlugin.php',
'OC\\Collaboration\\Collaborators\\LookupPlugin' => $baseDir . '/lib/private/Collaboration/Collaborators/LookupPlugin.php',
'OC\\Collaboration\\Collaborators\\MailPlugin' => $baseDir . '/lib/private/Collaboration/Collaborators/MailPlugin.php',
@ -495,6 +498,7 @@ return array(
'OC\\Core\\Command\\User\\Report' => $baseDir . '/core/Command/User/Report.php',
'OC\\Core\\Command\\User\\ResetPassword' => $baseDir . '/core/Command/User/ResetPassword.php',
'OC\\Core\\Command\\User\\Setting' => $baseDir . '/core/Command/User/Setting.php',
'OC\\Core\\Controller\\AutoCompleteController' => $baseDir . '/core/Controller/AutoCompleteController.php',
'OC\\Core\\Controller\\AvatarController' => $baseDir . '/core/Controller/AvatarController.php',
'OC\\Core\\Controller\\ClientFlowLoginController' => $baseDir . '/core/Controller/ClientFlowLoginController.php',
'OC\\Core\\Controller\\ContactsMenuController' => $baseDir . '/core/Controller/ContactsMenuController.php',

View File

@ -98,6 +98,8 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c
'OCP\\BackgroundJob\\IJobList' => __DIR__ . '/../../..' . '/lib/public/BackgroundJob/IJobList.php',
'OCP\\Capabilities\\ICapability' => __DIR__ . '/../../..' . '/lib/public/Capabilities/ICapability.php',
'OCP\\Capabilities\\IPublicCapability' => __DIR__ . '/../../..' . '/lib/public/Capabilities/IPublicCapability.php',
'OCP\\Collaboration\\AutoComplete\\IManager' => __DIR__ . '/../../..' . '/lib/public/Collaboration/AutoComplete/IManager.php',
'OCP\\Collaboration\\AutoComplete\\ISorter' => __DIR__ . '/../../..' . '/lib/public/Collaboration/AutoComplete/ISorter.php',
'OCP\\Collaboration\\Collaborators\\ISearch' => __DIR__ . '/../../..' . '/lib/public/Collaboration/Collaborators/ISearch.php',
'OCP\\Collaboration\\Collaborators\\ISearchPlugin' => __DIR__ . '/../../..' . '/lib/public/Collaboration/Collaborators/ISearchPlugin.php',
'OCP\\Collaboration\\Collaborators\\ISearchResult' => __DIR__ . '/../../..' . '/lib/public/Collaboration/Collaborators/ISearchResult.php',
@ -420,6 +422,7 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c
'OC\\Cache\\CappedMemoryCache' => __DIR__ . '/../../..' . '/lib/private/Cache/CappedMemoryCache.php',
'OC\\Cache\\File' => __DIR__ . '/../../..' . '/lib/private/Cache/File.php',
'OC\\CapabilitiesManager' => __DIR__ . '/../../..' . '/lib/private/CapabilitiesManager.php',
'OC\\Collaboration\\AutoComplete\\Manager' => __DIR__ . '/../../..' . '/lib/private/Collaboration/AutoComplete/Manager.php',
'OC\\Collaboration\\Collaborators\\GroupPlugin' => __DIR__ . '/../../..' . '/lib/private/Collaboration/Collaborators/GroupPlugin.php',
'OC\\Collaboration\\Collaborators\\LookupPlugin' => __DIR__ . '/../../..' . '/lib/private/Collaboration/Collaborators/LookupPlugin.php',
'OC\\Collaboration\\Collaborators\\MailPlugin' => __DIR__ . '/../../..' . '/lib/private/Collaboration/Collaborators/MailPlugin.php',
@ -525,6 +528,7 @@ class ComposerStaticInit53792487c5a8370acc0b06b1a864ff4c
'OC\\Core\\Command\\User\\Report' => __DIR__ . '/../../..' . '/core/Command/User/Report.php',
'OC\\Core\\Command\\User\\ResetPassword' => __DIR__ . '/../../..' . '/core/Command/User/ResetPassword.php',
'OC\\Core\\Command\\User\\Setting' => __DIR__ . '/../../..' . '/core/Command/User/Setting.php',
'OC\\Core\\Controller\\AutoCompleteController' => __DIR__ . '/../../..' . '/core/Controller/AutoCompleteController.php',
'OC\\Core\\Controller\\AvatarController' => __DIR__ . '/../../..' . '/core/Controller/AvatarController.php',
'OC\\Core\\Controller\\ClientFlowLoginController' => __DIR__ . '/../../..' . '/core/Controller/ClientFlowLoginController.php',
'OC\\Core\\Controller\\ContactsMenuController' => __DIR__ . '/../../..' . '/core/Controller/ContactsMenuController.php',

View File

@ -0,0 +1,81 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Collaboration\AutoComplete;
use OCP\Collaboration\AutoComplete\IManager;
use OCP\Collaboration\AutoComplete\ISorter;
use OCP\IServerContainer;
class Manager implements IManager {
/** @var string[] */
protected $sorters =[];
/** @var ISorter[] */
protected $sorterInstances = [];
/** @var IServerContainer */
private $c;
public function __construct(IServerContainer $container) {
$this->c = $container;
}
public function runSorters(array $sorters, array &$sortArray, array $context) {
$sorterInstances = $this->getSorters();
while($sorter = array_shift($sorters)) {
if(isset($sorterInstances[$sorter])) {
$sorterInstances[$sorter]->sort($sortArray, $context);
} else {
$this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [
'app' => 'core', 'id' => $sorter
]);
}
}
}
public function registerSorter($className) {
$this->sorters[] = $className;
}
protected function getSorters() {
if(count($this->sorterInstances) === 0) {
foreach ($this->sorters as $sorter) {
/** @var ISorter $instance */
$instance = $this->c->resolve($sorter);
if(!$instance instanceof ISorter) {
$this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}',
['app' => 'core', 'class' => $sorter]);
continue;
}
$sorterId = trim($instance->getId());
if(trim($sorterId) === '') {
$this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}',
['app' => 'core', 'class' => $sorter]);
continue;
}
$this->sorterInstances[$sorterId] = $instance;
}
}
return $this->sorterInstances;
}
}

View File

@ -106,6 +106,7 @@ use OCA\Theming\ThemingDefaults;
use OCP\App\IAppManager;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Collaboration\AutoComplete\IManager;
use OCP\Defaults;
use OCA\Theming\Util;
use OCP\Federation\ICloudIdManager;
@ -1011,6 +1012,8 @@ class Server extends ServerContainer implements IServerContainer {
});
$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
$this->registerService('SettingsManager', function (Server $c) {
$manager = new \OC\Settings\Manager(
$c->getLogger(),
@ -1801,6 +1804,13 @@ class Server extends ServerContainer implements IServerContainer {
return $this->query('CollaboratorSearch');
}
/**
* @return \OCP\Collaboration\AutoComplete\IManager
*/
public function getAutoCompleteManager(){
return $this->query(IManager::class);
}
/**
* Returns the LDAP Provider
*

View File

@ -1322,7 +1322,7 @@ class Manager implements IManager {
*
* @param \OCP\Files\Node $path
* @param bool $recursive Should we check all parent folders as well
* @param bool $currentAccess Should the user have currently access to the file
* @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
* @return array
*/
public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {

View File

@ -185,6 +185,8 @@ class OC_App {
'class' => $plugin['@value'],
];
\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
}
}
}

View File

@ -0,0 +1,46 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\Collaboration\AutoComplete;
/**
* Interface IManager
*
* @package OCP\Collaboration\AutoComplete
* @since 13.0.0
*/
interface IManager {
/**
* @param string $className class name of the ISorter implementation
* @since 13.0.0
*/
public function registerSorter($className);
/**
* @param array $sorters list of sorter IDs, seperated by "|"
* @param array $sortArray array representation of OCP\Collaboration\Collaborators\ISearchResult
* @param array $context context info of the search, keys: itemType, itemId
* @since 13.0.0
*/
public function runSorters(array $sorters, array &$sortArray, array $context);
}

View File

@ -0,0 +1,50 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\Collaboration\AutoComplete;
/**
* Interface ISorter
*
* Sorts the list of .e.g users for auto completion
*
* @package OCP\Collaboration\AutoComplete
* @since 13.0.0
*/
interface ISorter {
/**
* @return string The ID of the sorter, e.g. commenters
* @since 13.0.0
*/
public function getId();
/**
* executes the sort action
*
* @param array $sortArray the array to be sorted, provided as reference
* @param array $context carries key 'itemType' and 'itemId' of the source object (e.g. a file)
* @since 13.0.0
*/
public function sort(array &$sortArray, array $context);
}

View File

@ -0,0 +1,118 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace Tests\Core\Controller;
use OC\Core\Controller\AutoCompleteController;
use OCP\Collaboration\AutoComplete\IManager;
use OCP\Collaboration\Collaborators\ISearch;
use OCP\IConfig;
use OCP\IRequest;
use Test\TestCase;
class AutoCompleteControllerTest extends TestCase {
/** @var ISearch|\PHPUnit_Framework_MockObject_MockObject */
protected $collaboratorSearch;
/** @var IManager|\PHPUnit_Framework_MockObject_MockObject */
protected $autoCompleteManager;
/** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
protected $config;
/** @var AutoCompleteController */
protected $controller;
protected function setUp() {
parent::setUp();
/** @var IRequest $request */
$request = $this->createMock(IRequest::class);
$this->collaboratorSearch = $this->createMock(ISearch::class);
$this->autoCompleteManager = $this->createMock(IManager::class);
$this->config = $this->createMock(IConfig::class);
$this->controller = new AutoCompleteController(
'core',
$request,
$this->collaboratorSearch,
$this->autoCompleteManager,
$this->config
);
}
public function testGet() {
$searchResults = [
'exact' => [
'users' => [],
'robots' => [],
],
'users' => [
['label' => 'Alice A.', 'value' => ['shareWith' => 'alice']],
['label' => 'Bob Y.', 'value' => ['shareWith' => 'bob']],
],
];
$expected = [
[ 'id' => 'alice', 'label' => 'Alice A.', 'source' => 'users'],
[ 'id' => 'bob', 'label' => 'Bob Y.', 'source' => 'users'],
];
$this->collaboratorSearch->expects($this->once())
->method('search')
->willReturn([$searchResults, false]);
$response = $this->controller->get('', 'files', '42', null);
$list = $response->getData();
$this->assertEquals($expected, $list); // has better error output…
$this->assertSame($expected, $list);
}
public function testGetWithExactMatch() {
$searchResults = [
'exact' => [
'users' => [
['label' => 'Bob Y.', 'value' => ['shareWith' => 'bob']],
],
'robots' => [],
],
'users' => [
['label' => 'Robert R.', 'value' => ['shareWith' => 'bobby']],
],
];
$expected = [
[ 'id' => 'bob', 'label' => 'Bob Y.', 'source' => 'users'],
[ 'id' => 'bobby', 'label' => 'Robert R.', 'source' => 'users'],
];
$this->collaboratorSearch->expects($this->once())
->method('search')
->willReturn([$searchResults, false]);
$response = $this->controller->get('bob', 'files', '42', null);
$list = $response->getData();
$this->assertEquals($expected, $list); // has better error output…
$this->assertSame($expected, $list);
}
}

View File

@ -10,6 +10,7 @@ default:
- NextcloudTestServerContext
- AppNavigationContext
- CommentsAppContext
- FeatureContext
- FilesAppContext
- FilesSharingAppContext

View File

@ -0,0 +1,8 @@
Feature: app-comments
Scenario: Writing a comment
Given I am logged in
And I open the details view for "welcome.txt"
And I open the "Comments" tab in the details view
When I create a new comment with "Hello world" as message
Then I see that a comment was added

View File

@ -0,0 +1,82 @@
<?php
/**
* @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
use Behat\Behat\Context\Context;
class CommentsAppContext implements Context, ActorAwareInterface {
use ActorAware;
/**
* @When /^I create a new comment with "([^"]*)" as message$/
*/
public function iCreateANewCommentWithAsMessage($commentText) {
$this->actor->find(self::newCommentField(), 2)->setValue($commentText);
$this->actor->find(self::submitNewCommentButton(), 2)->click();
}
/**
* @Then /^I see that a comment was added$/
*/
public function iSeeThatACommentWasAdded() {
$self = $this;
$result = Utils::waitFor(function () use ($self) {
return $self->isCommentAdded();
}, 5, 0.5);
PHPUnit_Framework_Assert::assertTrue($result);
}
public function isCommentAdded() {
try {
$locator = self::commentFields();
$comments = $this->actor->getSession()->getPage()->findAll($locator->getSelector(), $locator->getLocator());
PHPUnit_Framework_Assert::assertSame(1, count($comments));
} catch (PHPUnit_Framework_ExpectationFailedException $e) {
return false;
}
return true;
}
/**
* @return Locator
*/
public static function newCommentField() {
return Locator::forThe()->css("div.newCommentRow .message")->descendantOf(FilesAppContext::currentSectionDetailsView())->
describedAs("New comment field in the details view in Files app");
}
public static function commentFields() {
return Locator::forThe()->css(".comments .comment .message")->descendantOf(FilesAppContext::currentSectionDetailsView())->
describedAs("Comment fields in the details view in Files app");
}
/**
* @return Locator
*/
public static function submitNewCommentButton() {
return Locator::forThe()->css("div.newCommentRow .submit")->descendantOf(FilesAppContext::currentSectionDetailsView())->
describedAs("Submit new comment button in the details view in Files app");
}
}

View File

@ -88,6 +88,8 @@ module.exports = function(config) {
srcFiles: [
// need to enforce loading order...
'apps/comments/js/app.js',
'apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js',
'apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js',
'apps/comments/js/commentmodel.js',
'apps/comments/js/commentcollection.js',
'apps/comments/js/commentsummarymodel.js',

View File

@ -1,12 +1,14 @@
<?php
namespace Test\Comments;
use OCP\Comments\IComment;
use OCP\Comments\ICommentsManager;
use OCP\IUser;
/**
* Class FakeManager
*/
class FakeManager implements \OCP\Comments\ICommentsManager {
class FakeManager implements ICommentsManager {
public function get($id) {}
@ -26,17 +28,17 @@ class FakeManager implements \OCP\Comments\ICommentsManager {
public function delete($id) {}
public function save(\OCP\Comments\IComment $comment) {}
public function save(IComment $comment) {}
public function deleteReferencesOfActor($actorType, $actorId) {}
public function deleteCommentsAtObject($objectType, $objectId) {}
public function setReadMark($objectType, $objectId, \DateTime $dateTime, \OCP\IUser $user) {}
public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {}
public function getReadMark($objectType, $objectId, \OCP\IUser $user) {}
public function getReadMark($objectType, $objectId, IUser $user) {}
public function deleteReadMarksFromUser(\OCP\IUser $user) {}
public function deleteReadMarksFromUser(IUser $user) {}
public function deleteReadMarksOnObject($objectType, $objectId) {}
@ -47,4 +49,6 @@ class FakeManager implements \OCP\Comments\ICommentsManager {
public function resolveDisplayName($type, $id) {}
public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {}
public function getActorsInTree($id) {}
}

View File

@ -3,12 +3,13 @@
namespace Test\Comments;
use OC\Comments\Comment;
use OCP\Comments\CommentsEvent;
use OC\Comments\ManagerFactory;
use OCP\Comments\IComment;
use OCP\Comments\ICommentsEventHandler;
use OCP\Comments\ICommentsManager;
use OCP\Comments\NotFoundException;
use OCP\IDBConnection;
use OCP\IUser;
use Test\Files\Storage\DummyUser;
use Test\TestCase;
/**
@ -62,7 +63,7 @@ class ManagerTest extends TestCase {
}
protected function getManager() {
$factory = new \OC\Comments\ManagerFactory(\OC::$server);
$factory = new ManagerFactory(\OC::$server);
return $factory->getManager();
}
@ -109,7 +110,7 @@ class ManagerTest extends TestCase {
$id = strval($qb->getLastInsertId());
$comment = $manager->get($id);
$this->assertTrue($comment instanceof \OCP\Comments\IComment);
$this->assertTrue($comment instanceof IComment);
$this->assertSame($comment->getId(), $id);
$this->assertSame($comment->getParentId(), '2');
$this->assertSame($comment->getTopmostParentId(), '1');
@ -152,14 +153,14 @@ class ManagerTest extends TestCase {
// Verifying the root comment
$this->assertTrue(isset($tree['comment']));
$this->assertTrue($tree['comment'] instanceof \OCP\Comments\IComment);
$this->assertTrue($tree['comment'] instanceof IComment);
$this->assertSame($tree['comment']->getId(), strval($headId));
$this->assertTrue(isset($tree['replies']));
$this->assertSame(count($tree['replies']), 3);
// one level deep
foreach ($tree['replies'] as $reply) {
$this->assertTrue($reply['comment'] instanceof \OCP\Comments\IComment);
$this->assertTrue($reply['comment'] instanceof IComment);
$this->assertSame($reply['comment']->getId(), strval($id));
$this->assertSame(count($reply['replies']), 0);
$id--;
@ -174,7 +175,7 @@ class ManagerTest extends TestCase {
// Verifying the root comment
$this->assertTrue(isset($tree['comment']));
$this->assertTrue($tree['comment'] instanceof \OCP\Comments\IComment);
$this->assertTrue($tree['comment'] instanceof IComment);
$this->assertSame($tree['comment']->getId(), strval($id));
$this->assertTrue(isset($tree['replies']));
$this->assertSame(count($tree['replies']), 0);
@ -200,14 +201,14 @@ class ManagerTest extends TestCase {
// Verifying the root comment
$this->assertTrue(isset($tree['comment']));
$this->assertTrue($tree['comment'] instanceof \OCP\Comments\IComment);
$this->assertTrue($tree['comment'] instanceof IComment);
$this->assertSame($tree['comment']->getId(), strval($headId));
$this->assertTrue(isset($tree['replies']));
$this->assertSame(count($tree['replies']), 2);
// one level deep
foreach ($tree['replies'] as $reply) {
$this->assertTrue($reply['comment'] instanceof \OCP\Comments\IComment);
$this->assertTrue($reply['comment'] instanceof IComment);
$this->assertSame($reply['comment']->getId(), strval($idToVerify));
$this->assertSame(count($reply['replies']), 0);
$idToVerify--;
@ -223,7 +224,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(is_array($comments));
$this->assertSame(count($comments), 1);
$this->assertTrue($comments[0] instanceof \OCP\Comments\IComment);
$this->assertTrue($comments[0] instanceof IComment);
$this->assertSame($comments[0]->getMessage(), 'nice one');
}
@ -243,7 +244,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(is_array($comments));
foreach ($comments as $comment) {
$this->assertTrue($comment instanceof \OCP\Comments\IComment);
$this->assertTrue($comment instanceof IComment);
$this->assertSame($comment->getMessage(), 'nice one');
$this->assertSame($comment->getId(), strval($idToVerify));
$idToVerify--;
@ -282,7 +283,7 @@ class ManagerTest extends TestCase {
$this->assertTrue(is_array($comments));
foreach ($comments as $comment) {
$this->assertTrue($comment instanceof \OCP\Comments\IComment);
$this->assertTrue($comment instanceof IComment);
$this->assertSame($comment->getMessage(), 'nice one');
$this->assertSame($comment->getId(), strval($idToVerify));
$this->assertTrue(intval($comment->getId()) >= 4);
@ -334,6 +335,7 @@ class ManagerTest extends TestCase {
$this->addDatabaseEntry(0, 0, null, null, $fileIds[$i]);
}
$this->addDatabaseEntry(0, 0, (new \DateTime())->modify('-2 days'), null, $fileIds[0]);
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
@ -368,6 +370,10 @@ class ManagerTest extends TestCase {
/**
* @dataProvider invalidCreateArgsProvider
* @expectedException \InvalidArgumentException
* @param string $aType
* @param string $aId
* @param string $oType
* @param string $oId
*/
public function testCreateCommentInvalidArguments($aType, $aId, $oType, $oId) {
$manager = $this->getManager();
@ -381,7 +387,7 @@ class ManagerTest extends TestCase {
$objectId = 'bielefeld';
$comment = $this->getManager()->create($actorType, $actorId, $objectType, $objectId);
$this->assertTrue($comment instanceof \OCP\Comments\IComment);
$this->assertTrue($comment instanceof IComment);
$this->assertSame($comment->getActorType(), $actorType);
$this->assertSame($comment->getActorId(), $actorId);
$this->assertSame($comment->getObjectType(), $objectType);
@ -405,7 +411,7 @@ class ManagerTest extends TestCase {
$id = strval($this->addDatabaseEntry(0, 0));
$comment = $manager->get($id);
$this->assertTrue($comment instanceof \OCP\Comments\IComment);
$this->assertTrue($comment instanceof IComment);
$done = $manager->delete($id);
$this->assertTrue($done);
$manager->get($id);
@ -515,6 +521,8 @@ class ManagerTest extends TestCase {
/**
* @dataProvider invalidActorArgsProvider
* @expectedException \InvalidArgumentException
* @param string $type
* @param string $id
*/
public function testDeleteReferencesOfActorInvalidInput($type, $id) {
$manager = $this->getManager();
@ -551,7 +559,7 @@ class ManagerTest extends TestCase {
public function testDeleteReferencesOfActorWithUserManagement() {
$user = \OC::$server->getUserManager()->createUser('xenia', '123456');
$this->assertTrue($user instanceof \OCP\IUser);
$this->assertTrue($user instanceof IUser);
$manager = \OC::$server->getCommentsManager();
$comment = $manager->create('users', $user->getUID(), 'files', 'file64');
@ -565,8 +573,8 @@ class ManagerTest extends TestCase {
$user->delete();
$comment = $manager->get($commentID);
$this->assertSame($comment->getActorType(), \OCP\Comments\ICommentsManager::DELETED_USER);
$this->assertSame($comment->getActorId(), \OCP\Comments\ICommentsManager::DELETED_USER);
$this->assertSame($comment->getActorType(), ICommentsManager::DELETED_USER);
$this->assertSame($comment->getActorId(), ICommentsManager::DELETED_USER);
}
public function invalidObjectArgsProvider() {
@ -581,6 +589,8 @@ class ManagerTest extends TestCase {
/**
* @dataProvider invalidObjectArgsProvider
* @expectedException \InvalidArgumentException
* @param string $type
* @param string $id
*/
public function testDeleteCommentsAtObjectInvalidInput($type, $id) {
$manager = $this->getManager();
@ -607,7 +617,7 @@ class ManagerTest extends TestCase {
foreach ($ids as $id) {
try {
$manager->get(strval($id));
} catch (\OCP\Comments\NotFoundException $e) {
} catch (NotFoundException $e) {
$verified++;
}
}
@ -620,6 +630,7 @@ class ManagerTest extends TestCase {
}
public function testSetMarkRead() {
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
@ -636,6 +647,7 @@ class ManagerTest extends TestCase {
}
public function testSetMarkReadUpdate() {
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
@ -655,6 +667,7 @@ class ManagerTest extends TestCase {
}
public function testReadMarkDeleteUser() {
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')
@ -672,6 +685,7 @@ class ManagerTest extends TestCase {
}
public function testReadMarkDeleteObject() {
/** @var IUser|\PHPUnit_Framework_MockObject_MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('getUID')