Search in sources :

Example 1 with UnapprovedQuestion

use of com.erudika.scoold.core.UnapprovedQuestion in project scoold by Erudika.

the class ScooldUtils method sendNewPostNotifications.

@SuppressWarnings("unchecked")
public void sendNewPostNotifications(Post question, HttpServletRequest req) {
    if (question == null) {
        return;
    }
    // the current user - same as utils.getAuthUser(req)
    Profile postAuthor = question.getAuthor() != null ? question.getAuthor() : pc.read(question.getCreatorid());
    if (!question.getType().equals(Utils.type(UnapprovedQuestion.class))) {
        if (!isNewPostNotificationAllowed()) {
            return;
        }
        Map<String, Object> model = new HashMap<String, Object>();
        Map<String, String> lang = getLang(req);
        String name = postAuthor.getName();
        String body = Utils.markdownToHtml(question.getBody());
        String picture = Utils.formatMessage("<img src='{0}' width='25'>", escapeHtmlAttribute(avatarRepository.getLink(postAuthor, AvatarFormat.Square25)));
        String postURL = getServerURL() + question.getPostLink(false, false);
        String tagsString = Optional.ofNullable(question.getTags()).orElse(Collections.emptyList()).stream().map(t -> "<span class=\"tag\">" + escapeHtml(t) + "</span>").collect(Collectors.joining("&nbsp;"));
        String subject = Utils.formatMessage(lang.get("notification.newposts.subject"), name, Utils.abbreviate(question.getTitle(), 255));
        model.put("subject", escapeHtml(subject));
        model.put("logourl", getSmallLogoUrl());
        model.put("heading", Utils.formatMessage(lang.get("notification.newposts.heading"), picture, escapeHtml(name)));
        model.put("body", Utils.formatMessage("<h2><a href='{0}'>{1}</a></h2><div>{2}</div><br>{3}", postURL, escapeHtml(question.getTitle()), body, tagsString));
        Set<String> emails = new HashSet<String>(getNotificationSubscribers(EMAIL_ALERTS_PREFIX + "new_post_subscribers"));
        emails.addAll(getFavTagsSubscribers(question.getTags()));
        sendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model));
    } else if (postsNeedApproval() && question instanceof UnapprovedQuestion) {
        Report rep = new Report();
        rep.setDescription("New question awaiting approval");
        rep.setSubType(Report.ReportType.OTHER);
        rep.setLink(question.getPostLink(false, false));
        rep.setAuthorName(postAuthor.getName());
        rep.create();
    }
}
Also used : Question(com.erudika.scoold.core.Question) Arrays(java.util.Arrays) Webhook(com.erudika.para.core.Webhook) ServletException(javax.servlet.ServletException) Date(java.util.Date) HttpUtils.getCookieValue(com.erudika.scoold.utils.HttpUtils.getCookieValue) JOSEException(com.nimbusds.jose.JOSEException) LoggerFactory(org.slf4j.LoggerFactory) Vote(com.erudika.para.core.Vote) Scanner(java.util.Scanner) ParaClient(com.erudika.para.client.ParaClient) Revision(com.erudika.scoold.core.Revision) StringUtils(org.apache.commons.lang3.StringUtils) Base64(org.apache.commons.codec.binary.Base64) MACVerifier(com.nimbusds.jose.crypto.MACVerifier) Matcher(java.util.regex.Matcher) Locale(java.util.Locale) Map(java.util.Map) ParseException(java.text.ParseException) Config(com.erudika.para.core.utils.Config) ConstraintViolation(javax.validation.ConstraintViolation) ValidationUtils(com.erudika.para.core.validation.ValidationUtils) ParaObject(com.erudika.para.core.ParaObject) Predicate(java.util.function.Predicate) HttpHeaders(org.springframework.http.HttpHeaders) AvatarFormat(com.erudika.scoold.utils.avatars.AvatarFormat) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConfigObject(com.typesafe.config.ConfigObject) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Emailer(com.erudika.para.core.email.Emailer) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) Comment(com.erudika.scoold.core.Comment) List(java.util.List) JWSSigner(com.nimbusds.jose.JWSSigner) Tag(com.erudika.para.core.Tag) GravatarAvatarGenerator(com.erudika.scoold.utils.avatars.GravatarAvatarGenerator) Optional(java.util.Optional) DEFAULT_SPACE(com.erudika.scoold.core.Post.DEFAULT_SPACE) Para(com.erudika.para.core.utils.Para) Pattern(java.util.regex.Pattern) Feedback(com.erudika.scoold.core.Feedback) Sysprop(com.erudika.para.core.Sysprop) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) ALL_MY_SPACES(com.erudika.scoold.core.Post.ALL_MY_SPACES) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AvatarRepositoryProxy(com.erudika.scoold.utils.avatars.AvatarRepositoryProxy) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) Pager(com.erudika.para.core.utils.Pager) ENTHUSIAST(com.erudika.scoold.core.Profile.Badge.ENTHUSIAST) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) Named(javax.inject.Named) LinkedList(java.util.LinkedList) TEACHER(com.erudika.scoold.core.Profile.Badge.TEACHER) UnapprovedReply(com.erudika.scoold.core.UnapprovedReply) LinkedHashSet(java.util.LinkedHashSet) MACSigner(com.nimbusds.jose.crypto.MACSigner) JWSVerifier(com.nimbusds.jose.JWSVerifier) RegExUtils(org.apache.commons.lang3.RegExUtils) Logger(org.slf4j.Logger) AvatarRepository(com.erudika.scoold.utils.avatars.AvatarRepository) Address(com.erudika.para.core.Address) Post(com.erudika.scoold.core.Post) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) User(com.erudika.para.core.User) Utils(com.erudika.para.core.utils.Utils) Report(com.erudika.scoold.core.Report) Component(org.springframework.stereotype.Component) TreeMap(java.util.TreeMap) ScooldServer(com.erudika.scoold.ScooldServer) NumberUtils(org.apache.commons.lang3.math.NumberUtils) Reply(com.erudika.scoold.core.Reply) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) InputStream(java.io.InputStream) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Report(com.erudika.scoold.core.Report) ParaObject(com.erudika.para.core.ParaObject) ConfigObject(com.typesafe.config.ConfigObject) Profile(com.erudika.scoold.core.Profile) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 2 with UnapprovedQuestion

use of com.erudika.scoold.core.UnapprovedQuestion in project scoold by Erudika.

the class QuestionsController method getQuestions.

public List<Question> getQuestions(String sortby, String filter, HttpServletRequest req, Model model) {
    Pager itemcount = getPagerFromCookie(req, utils.getPager("page", req));
    List<Question> questionslist = Collections.emptyList();
    String type = Utils.type(Question.class);
    Profile authUser = utils.getAuthUser(req);
    String currentSpace = utils.getSpaceIdFromCookie(authUser, req);
    String query = getQuestionsQuery(req, authUser, sortby, currentSpace, itemcount);
    if (!StringUtils.isBlank(filter) && authUser != null) {
        if ("favtags".equals(filter)) {
            if (!authUser.hasFavtags() && req.getParameterValues("favtags") != null) {
                // API override
                authUser.setFavtags(Arrays.asList(req.getParameterValues("favtags")));
            }
            if (isSpaceFilteredRequest(authUser, currentSpace) && authUser.hasFavtags()) {
                questionslist = pc.findQuery(type, getSpaceFilteredFavtagsQuery(currentSpace, authUser), itemcount);
            } else {
                questionslist = pc.findTermInList(type, Config._TAGS, authUser.getFavtags(), itemcount);
            }
        } else if ("local".equals(filter)) {
            String latlng = Optional.ofNullable(authUser.getLatlng()).orElse(req.getParameter("latlng"));
            String[] ll = latlng == null ? new String[0] : latlng.split(",");
            if (ll.length == 2) {
                double lat = NumberUtils.toDouble(ll[0]);
                double lng = NumberUtils.toDouble(ll[1]);
                questionslist = pc.findNearby(type, query, 25, lat, lng, itemcount);
            }
        }
        model.addAttribute("localFilterOn", "local".equals(filter));
        model.addAttribute("tagFilterOn", "favtags".equals(filter));
        model.addAttribute("filter", "/" + Utils.stripAndTrim(filter));
    } else {
        questionslist = pc.findQuery(type, query, itemcount);
    }
    if (utils.postsNeedApproval() && utils.isMod(authUser)) {
        Pager p = new Pager(itemcount.getPage(), itemcount.getLimit());
        List<UnapprovedQuestion> uquestionslist = pc.findQuery(Utils.type(UnapprovedQuestion.class), query, p);
        List<Question> qlist = new LinkedList<>(uquestionslist);
        itemcount.setCount(itemcount.getCount() + p.getCount());
        qlist.addAll(questionslist);
        questionslist = qlist;
    }
    utils.fetchProfiles(questionslist);
    model.addAttribute("itemcount", itemcount);
    model.addAttribute("questionslist", questionslist);
    return questionslist;
}
Also used : UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Pager(com.erudika.para.core.utils.Pager) Question(com.erudika.scoold.core.Question) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList)

Example 3 with UnapprovedQuestion

use of com.erudika.scoold.core.UnapprovedQuestion in project scoold by Erudika.

the class QuestionsController method post.

@PostMapping("/questions/ask")
public String post(@RequestParam(required = false) String location, @RequestParam(required = false) String latlng, @RequestParam(required = false) String address, String space, HttpServletRequest req, HttpServletResponse res, Model model) {
    if (utils.isAuthenticated(req)) {
        Profile authUser = utils.getAuthUser(req);
        String currentSpace = utils.getValidSpaceIdExcludingAll(authUser, space, req);
        boolean needsApproval = utils.postNeedsApproval(authUser);
        Question q = utils.populate(req, needsApproval ? new UnapprovedQuestion() : new Question(), "title", "body", "tags|,", "location");
        q.setCreatorid(authUser.getId());
        q.setSpace(currentSpace);
        if (StringUtils.isBlank(q.getTagsString())) {
            q.setTags(Arrays.asList(Config.getConfigParam("default_question_tag", "question")));
        }
        Map<String, String> error = utils.validate(q);
        if (error.isEmpty()) {
            q.setLocation(location);
            q.setAuthor(authUser);
            String qid = q.create();
            utils.sendNewPostNotifications(q, req);
            if (!StringUtils.isBlank(latlng)) {
                Address addr = new Address(qid + Config.SEPARATOR + Utils.type(Address.class));
                addr.setAddress(address);
                addr.setCountry(location);
                addr.setLatlng(latlng);
                addr.setParentid(qid);
                addr.setCreatorid(authUser.getId());
                pc.create(addr);
            }
            authUser.setLastseen(System.currentTimeMillis());
            model.addAttribute("newpost", getNewQuestionPayload(q));
        } else {
            model.addAttribute("error", error);
            model.addAttribute("draftQuestion", q);
            model.addAttribute("defaultTag", "");
            model.addAttribute("path", "questions.vm");
            model.addAttribute("includeGMapsScripts", utils.isNearMeFeatureEnabled());
            model.addAttribute("askSelected", "navbtn-hover");
            return "base";
        }
        if (utils.isAjaxRequest(req)) {
            res.setStatus(200);
            res.setContentType("application/json");
            try {
                res.getWriter().println("{\"url\":\"" + q.getPostLink(false, false) + "\"}");
            } catch (IOException ex) {
            }
            return "blank";
        } else {
            return "redirect:" + q.getPostLink(false, false);
        }
    }
    if (utils.isAjaxRequest(req)) {
        res.setStatus(400);
        return "blank";
    } else {
        return "redirect:" + SIGNINLINK + "?returnto=" + QUESTIONSLINK + "/ask";
    }
}
Also used : UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Address(com.erudika.para.core.Address) Question(com.erudika.scoold.core.Question) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) IOException(java.io.IOException) Profile(com.erudika.scoold.core.Profile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 4 with UnapprovedQuestion

use of com.erudika.scoold.core.UnapprovedQuestion in project scoold by Erudika.

the class QuestionController method get.

@GetMapping({ "/{id}", "/{id}/{title}", "/{id}/{title}/*" })
public String get(@PathVariable String id, @PathVariable(required = false) String title, @RequestParam(required = false) String sortby, HttpServletRequest req, HttpServletResponse res, Model model) {
    Post showPost = pc.read(id);
    if (showPost == null || !ParaObjectUtils.typesMatch(showPost)) {
        return "redirect:" + QUESTIONSLINK;
    }
    Profile authUser = utils.getAuthUser(req);
    if (!utils.canAccessSpace(authUser, showPost.getSpace())) {
        return "redirect:" + (utils.isDefaultSpacePublic() || utils.isAuthenticated(req) ? QUESTIONSLINK : SIGNINLINK + "?returnto=" + req.getRequestURI());
    } else if (!utils.isDefaultSpace(showPost.getSpace()) && pc.read(utils.getSpaceId(showPost.getSpace())) == null) {
        showPost.setSpace(Post.DEFAULT_SPACE);
        pc.update(showPost);
    }
    if (showPost instanceof UnapprovedQuestion && !(utils.isMine(showPost, authUser) || utils.isMod(authUser))) {
        return "redirect:" + QUESTIONSLINK;
    }
    Pager itemcount = utils.getPager("page", req);
    itemcount.setSortby("newest".equals(sortby) ? "timestamp" : "votes");
    List<Reply> answerslist = getAllAnswers(authUser, showPost, itemcount);
    LinkedList<Post> allPosts = new LinkedList<Post>();
    allPosts.add(showPost);
    allPosts.addAll(answerslist);
    utils.fetchProfiles(allPosts);
    utils.getComments(allPosts);
    utils.updateViewCount(showPost, req, res);
    model.addAttribute("path", "question.vm");
    model.addAttribute("title", utils.getLang(req).get("questions.title") + " - " + showPost.getTitle());
    model.addAttribute("description", Utils.abbreviate(Utils.stripAndTrim(showPost.getBody(), " "), 195));
    model.addAttribute("itemcount", itemcount);
    model.addAttribute("showPost", allPosts.removeFirst());
    model.addAttribute("answerslist", allPosts);
    model.addAttribute("similarquestions", utils.getSimilarPosts(showPost, new Pager(10)));
    model.addAttribute("maxCommentLength", Comment.MAX_COMMENT_LENGTH);
    model.addAttribute("includeGMapsScripts", utils.isNearMeFeatureEnabled());
    model.addAttribute("maxCommentLengthError", Utils.formatMessage(utils.getLang(req).get("maxlength"), Comment.MAX_COMMENT_LENGTH));
    return "base";
}
Also used : UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Post(com.erudika.scoold.core.Post) Pager(com.erudika.para.core.utils.Pager) UnapprovedReply(com.erudika.scoold.core.UnapprovedReply) Reply(com.erudika.scoold.core.Reply) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 5 with UnapprovedQuestion

use of com.erudika.scoold.core.UnapprovedQuestion in project scoold by Erudika.

the class QuestionController method modApprove.

@PostMapping("/{id}/approve")
public String modApprove(@PathVariable String id, HttpServletRequest req) {
    Post showPost = pc.read(id);
    Profile authUser = utils.getAuthUser(req);
    if (utils.isMod(authUser)) {
        if (showPost instanceof UnapprovedQuestion) {
            showPost.setType(Utils.type(Question.class));
            pc.create(showPost);
            utils.sendNewPostNotifications(showPost, req);
        } else if (showPost instanceof UnapprovedReply) {
            showPost.setType(Utils.type(Reply.class));
            pc.create(showPost);
        }
    }
    return "redirect:" + showPost.getPostLink(false, false);
}
Also used : UnapprovedReply(com.erudika.scoold.core.UnapprovedReply) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Post(com.erudika.scoold.core.Post) Question(com.erudika.scoold.core.Question) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Profile(com.erudika.scoold.core.Profile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

Profile (com.erudika.scoold.core.Profile)5 UnapprovedQuestion (com.erudika.scoold.core.UnapprovedQuestion)5 Question (com.erudika.scoold.core.Question)4 Pager (com.erudika.para.core.utils.Pager)3 Post (com.erudika.scoold.core.Post)3 UnapprovedReply (com.erudika.scoold.core.UnapprovedReply)3 LinkedList (java.util.LinkedList)3 Address (com.erudika.para.core.Address)2 Reply (com.erudika.scoold.core.Reply)2 IOException (java.io.IOException)2 ParaClient (com.erudika.para.client.ParaClient)1 ParaObject (com.erudika.para.core.ParaObject)1 Sysprop (com.erudika.para.core.Sysprop)1 Tag (com.erudika.para.core.Tag)1 User (com.erudika.para.core.User)1 Vote (com.erudika.para.core.Vote)1 Webhook (com.erudika.para.core.Webhook)1 Emailer (com.erudika.para.core.email.Emailer)1 Config (com.erudika.para.core.utils.Config)1 Para (com.erudika.para.core.utils.Para)1