use of com.erudika.para.core.utils.Config in project scoold by Erudika.
the class ScooldUtils method sendCommentNotifications.
public void sendCommentNotifications(Post parentPost, Comment comment, Profile commentAuthor, HttpServletRequest req) {
// send email notification to author of post except when the comment is by the same person
if (parentPost != null && comment != null) {
// parent author is not current user (authUser)
parentPost.setAuthor(pc.read(Profile.id(parentPost.getCreatorid())));
Map<String, Object> payload = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(comment, false));
payload.put("parent", parentPost);
payload.put("author", commentAuthor);
triggerHookEvent("comment.create", payload);
// get the last 5-6 commentators who want to be notified - https://github.com/Erudika/scoold/issues/201
Pager p = new Pager(1, Config._TIMESTAMP, false, 5);
boolean isCommentatorThePostAuthor = StringUtils.equals(parentPost.getCreatorid(), comment.getCreatorid());
Set<String> last5ids = pc.findChildren(parentPost, Utils.type(Comment.class), "!(" + Config._CREATORID + ":\"" + comment.getCreatorid() + "\")", p).stream().map(c -> c.getCreatorid()).distinct().collect(Collectors.toSet());
if (!isCommentatorThePostAuthor && !last5ids.contains(parentPost.getCreatorid())) {
last5ids = new HashSet<>(last5ids);
last5ids.add(parentPost.getCreatorid());
}
Map<String, String> lang = getLang(req);
List<Profile> last5commentators = pc.readAll(new ArrayList<>(last5ids));
last5commentators = last5commentators.stream().filter(u -> u.getCommentEmailsEnabled()).collect(Collectors.toList());
pc.readAll(last5commentators.stream().map(u -> u.getCreatorid()).collect(Collectors.toList())).forEach(author -> {
if (isCommentNotificationAllowed()) {
Map<String, Object> model = new HashMap<String, Object>();
String name = commentAuthor.getName();
String body = Utils.markdownToHtml(comment.getComment());
String pic = Utils.formatMessage("<img src='{0}' width='25'>", escapeHtmlAttribute(avatarRepository.getLink(commentAuthor, AvatarFormat.Square25)));
String postURL = getServerURL() + parentPost.getPostLink(false, false);
String subject = Utils.formatMessage(lang.get("notification.comment.subject"), name, parentPost.getTitle());
model.put("subject", escapeHtml(subject));
model.put("logourl", getSmallLogoUrl());
model.put("heading", Utils.formatMessage(lang.get("notification.comment.heading"), Utils.formatMessage("<a href='{0}'>{1}</a>", postURL, escapeHtml(parentPost.getTitle()))));
model.put("body", Utils.formatMessage("<h2>{0} {1}:</h2><div class='panel'>{2}</div>", pic, escapeHtml(name), body));
emailer.sendEmail(Arrays.asList(((User) author).getEmail()), subject, compileEmailTemplate(model));
}
});
}
}
use of com.erudika.para.core.utils.Config in project scoold by Erudika.
the class ScooldUtils method fullQuestionsSearch.
public List<Post> fullQuestionsSearch(String query, Pager... pager) {
String typeFilter = Config._TYPE + ":(" + String.join(" OR ", Utils.type(Question.class), Utils.type(Reply.class), Utils.type(Comment.class)) + ")";
String qs = StringUtils.isBlank(query) || query.startsWith("*") ? typeFilter : query + " AND " + typeFilter;
List<ParaObject> mixedResults = pc.findQuery("", qs, pager);
Predicate<ParaObject> isQuestion = obj -> obj.getType().equals(Utils.type(Question.class));
Map<String, ParaObject> idsToQuestions = new HashMap<>(mixedResults.stream().filter(isQuestion).collect(Collectors.toMap(q -> q.getId(), q -> q)));
Set<String> toRead = new LinkedHashSet<>();
mixedResults.stream().filter(isQuestion.negate()).forEach(obj -> {
if (!idsToQuestions.containsKey(obj.getParentid())) {
toRead.add(obj.getParentid());
}
});
// find all parent posts but this excludes parents of parents - i.e. won't work for comments in answers
List<Post> parentPostsLevel1 = pc.readAll(new ArrayList<>(toRead));
parentPostsLevel1.stream().filter(isQuestion).forEach(q -> idsToQuestions.put(q.getId(), q));
toRead.clear();
// read parents of parents if any
parentPostsLevel1.stream().filter(isQuestion.negate()).forEach(obj -> {
if (!idsToQuestions.containsKey(obj.getParentid())) {
toRead.add(obj.getParentid());
}
});
List<Post> parentPostsLevel2 = pc.readAll(new ArrayList<>(toRead));
parentPostsLevel2.stream().forEach(q -> idsToQuestions.put(q.getId(), q));
ArrayList<Post> results = new ArrayList<Post>(idsToQuestions.size());
for (ParaObject result : idsToQuestions.values()) {
if (result instanceof Post) {
results.add((Post) result);
}
}
return results;
}
use of com.erudika.para.core.utils.Config in project scoold by Erudika.
the class AdminController method importAccountsFromSO.
private void importAccountsFromSO(List<Map<String, Object>> objs) {
logger.info("Importing {} accounts...", objs.size());
List<Map<String, String>> toPatch = new LinkedList<>();
Map<String, String> accounts = objs.stream().collect(Collectors.toMap(k -> ((Integer) k.get("accountId")).toString(), v -> (String) v.get("verifiedEmail")));
// find all user objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
List<User> users;
do {
users = pc.findQuery(Utils.type(User.class), "*", pager);
if (!users.isEmpty()) {
users.stream().forEach(u -> {
if (accounts.containsKey(u.getCreatorid())) {
u.setEmail(accounts.get(u.getCreatorid()));
Map<String, String> user = new HashMap<>();
user.put(Config._ID, u.getId());
user.put(Config._EMAIL, u.getEmail());
user.put(Config._IDENTIFIER, u.getEmail());
toPatch.add(user);
}
});
}
pc.invokePatch("_batch", toPatch, Map.class);
toPatch.clear();
} while (!users.isEmpty());
}
use of com.erudika.para.core.utils.Config in project scoold by Erudika.
the class TagsController method rename.
@PostMapping
public String rename(@RequestParam String tag, @RequestParam String newtag, HttpServletRequest req, HttpServletResponse res, Model model) {
Profile authUser = utils.getAuthUser(req);
int count = 0;
if (utils.isMod(authUser)) {
Tag updated;
Tag oldTag = new Tag(tag);
Tag newTag = new Tag(newtag);
Tag t = pc.read(Utils.type(Tag.class), oldTag.getId());
if (t != null && !oldTag.getTag().equals(newTag.getTag())) {
if (oldTag.getTag().equals(newTag.getTag())) {
t.setCount(pc.getCount(Utils.type(Question.class), Collections.singletonMap(Config._TAGS, oldTag.getTag())).intValue());
updated = pc.update(t);
} else {
pc.delete(t);
t.setId(newtag);
logger.info("User {} ({}) is renaming tag '{}' to '{}'.", authUser.getName(), authUser.getCreatorid(), oldTag.getTag(), t.getTag());
t.setCount(pc.getCount(Utils.type(Question.class), Collections.singletonMap(Config._TAGS, newTag.getTag())).intValue());
Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
List<Question> questionslist;
do {
questionslist = pc.findTagged(Utils.type(Question.class), new String[] { oldTag.getTag() }, pager);
for (Question q : questionslist) {
t.setCount(t.getCount() + 1);
q.setTags(Optional.ofNullable(q.getTags()).orElse(Collections.emptyList()).stream().map(ts -> {
if (ts.equals(newTag.getTag())) {
t.setCount(t.getCount() - 1);
}
return ts.equals(oldTag.getTag()) ? t.getTag() : ts;
}).distinct().collect(Collectors.toList()));
logger.debug("Updated {} out of {} questions with new tag {}.", questionslist.size(), pager.getCount(), t.getTag());
}
if (!questionslist.isEmpty()) {
pc.updateAll(questionslist);
}
} while (!questionslist.isEmpty());
// overwrite new tag object
updated = pc.create(t);
}
model.addAttribute("tag", updated);
count = t.getCount();
}
}
if (utils.isAjaxRequest(req)) {
res.setStatus(200);
res.setContentType("application/json");
try {
res.getWriter().println("{\"count\":" + count + ", \"tag\":\"" + new Tag(newtag).getTag() + "\"}");
} catch (IOException ex) {
}
return "blank";
} else {
return "redirect:" + TAGSLINK + "?" + req.getQueryString();
}
}
use of com.erudika.para.core.utils.Config in project scoold by Erudika.
the class PeopleController method bulkEdit.
@PostMapping("/bulk-edit")
public String bulkEdit(@RequestParam(required = false) String[] selectedUsers, @RequestParam(required = false) final String[] selectedSpaces, HttpServletRequest req) {
Profile authUser = utils.getAuthUser(req);
boolean isAdmin = utils.isAdmin(authUser);
String operation = req.getParameter("operation");
String selection = req.getParameter("selection");
if (isAdmin && ("all".equals(selection) || selectedUsers != null)) {
// find all user objects even if there are more than 10000 users in the system
Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
List<Profile> profiles;
LinkedList<Map<String, Object>> toUpdate = new LinkedList<>();
List<String> spaces = (selectedSpaces == null || selectedSpaces.length == 0) ? Collections.emptyList() : Arrays.asList(selectedSpaces);
do {
String query = (selection == null || "selected".equals(selection)) ? Config._ID + ":(\"" + String.join("\" \"", selectedUsers) + "\")" : "*";
profiles = pc.findQuery(Utils.type(Profile.class), query, pager);
profiles.stream().filter(p -> !utils.isMod(p)).forEach(p -> {
if ("add".equals(operation)) {
p.getSpaces().addAll(spaces);
} else if ("remove".equals(operation)) {
p.getSpaces().removeAll(spaces);
} else {
p.setSpaces(new HashSet<String>(spaces));
}
Map<String, Object> profile = new HashMap<>();
profile.put(Config._ID, p.getId());
profile.put("spaces", p.getSpaces());
toUpdate.add(profile);
});
} while (!profiles.isEmpty());
// always patch outside the loop because we modify _docid values!!!
LinkedList<Map<String, Object>> batch = new LinkedList<>();
while (!toUpdate.isEmpty()) {
batch.add(toUpdate.pop());
if (batch.size() >= 100) {
// partial batch update
pc.invokePatch("_batch", batch, Map.class);
batch.clear();
}
}
if (!batch.isEmpty()) {
pc.invokePatch("_batch", batch, Map.class);
}
}
return "redirect:" + PEOPLELINK + (isAdmin ? "?" + req.getQueryString() : "");
}
Aggregations