Search in sources :

Example 1 with Question

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

the class ApiController method listQuestions.

@GetMapping("/posts")
public List<Map<String, Object>> listQuestions(HttpServletRequest req) {
    Model model = new ExtendedModelMap();
    questionsController.getQuestions(req.getParameter("sortby"), req.getParameter("filter"), req, model);
    return ((List<Question>) model.getAttribute("questionslist")).stream().map(p -> {
        Map<String, Object> post = new LinkedHashMap<>(ParaObjectUtils.getAnnotatedFields(p, false));
        post.put("author", p.getAuthor());
        return post;
    }).collect(Collectors.toList());
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Question(com.erudika.scoold.core.Question) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) Webhook(com.erudika.para.core.Webhook) PeopleController(com.erudika.scoold.controllers.PeopleController) WebRequest(org.springframework.web.context.request.WebRequest) LoggerFactory(org.slf4j.LoggerFactory) ParaClient(com.erudika.para.client.ParaClient) Revision(com.erudika.scoold.core.Revision) StringUtils(org.apache.commons.lang3.StringUtils) Model(org.springframework.ui.Model) CommentController(com.erudika.scoold.controllers.CommentController) PutMapping(org.springframework.web.bind.annotation.PutMapping) Map(java.util.Map) Config(com.erudika.para.core.utils.Config) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) ValidationUtils(com.erudika.para.core.validation.ValidationUtils) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) BadRequestException(com.erudika.scoold.utils.BadRequestException) ParaObject(com.erudika.para.core.ParaObject) QuestionsController(com.erudika.scoold.controllers.QuestionsController) Collection(java.util.Collection) Set(java.util.Set) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) UnapprovedQuestion(com.erudika.scoold.core.UnapprovedQuestion) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) REST_ENTITY_ATTRIBUTE(com.erudika.scoold.ScooldServer.REST_ENTITY_ATTRIBUTE) Comment(com.erudika.scoold.core.Comment) List(java.util.List) Tag(com.erudika.para.core.Tag) ReportsController(com.erudika.scoold.controllers.ReportsController) Optional(java.util.Optional) AUTH_USER_ATTRIBUTE(com.erudika.scoold.ScooldServer.AUTH_USER_ATTRIBUTE) ExtendedModelMap(org.springframework.ui.ExtendedModelMap) Sysprop(com.erudika.para.core.Sysprop) TagsController(com.erudika.scoold.controllers.TagsController) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) RevisionsController(com.erudika.scoold.controllers.RevisionsController) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Pager(com.erudika.para.core.utils.Pager) PatchMapping(org.springframework.web.bind.annotation.PatchMapping) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Inject(javax.inject.Inject) AdminController(com.erudika.scoold.controllers.AdminController) HttpServletRequest(javax.servlet.http.HttpServletRequest) Locked(com.erudika.para.core.annotations.Locked) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) GetMapping(org.springframework.web.bind.annotation.GetMapping) UnapprovedReply(com.erudika.scoold.core.UnapprovedReply) ProfileController(com.erudika.scoold.controllers.ProfileController) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Post(com.erudika.scoold.core.Post) VoteController(com.erudika.scoold.controllers.VoteController) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) User(com.erudika.para.core.User) CONTEXT_PATH(com.erudika.scoold.ScooldServer.CONTEXT_PATH) Utils(com.erudika.para.core.utils.Utils) Report(com.erudika.scoold.core.Report) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) ScooldServer(com.erudika.scoold.ScooldServer) NumberUtils(org.apache.commons.lang3.math.NumberUtils) QuestionController(com.erudika.scoold.controllers.QuestionController) Reply(com.erudika.scoold.core.Reply) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) ExtendedModelMap(org.springframework.ui.ExtendedModelMap) Model(org.springframework.ui.Model) List(java.util.List) Map(java.util.Map) ExtendedModelMap(org.springframework.ui.ExtendedModelMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 2 with Question

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

the class SearchController method getFeed.

private SyndFeed getFeed() throws IOException, FeedException {
    List<Post> questions = pc.findQuery(Utils.type(Question.class), "*");
    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    String baseurl = ScooldServer.getServerURL();
    baseurl = baseurl.endsWith("/") ? baseurl : baseurl + "/";
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType("atom_1.0");
    feed.setTitle(Config.APP_NAME + " - Recent questions");
    feed.setLink(baseurl);
    feed.setDescription("A summary of the most recent questions on " + Config.APP_NAME);
    for (Post post : questions) {
        SyndEntry entry;
        SyndContent description;
        String baselink = baseurl.concat("question/").concat(post.getId());
        entry = new SyndEntryImpl();
        entry.setTitle(post.getTitle());
        entry.setLink(baselink);
        entry.setPublishedDate(new Date(post.getTimestamp()));
        entry.setAuthor(baseurl.concat("profile/").concat(post.getCreatorid()));
        entry.setUri(baselink.concat("/").concat(Utils.stripAndTrim(post.getTitle()).replaceAll("\\p{Z}+", "-").toLowerCase()));
        description = new SyndContentImpl();
        description.setType("text/html");
        description.setValue(Utils.markdownToHtml(post.getBody()));
        entry.setDescription(description);
        entries.add(entry);
    }
    feed.setEntries(entries);
    return feed;
}
Also used : Post(com.erudika.scoold.core.Post) SyndEntry(com.sun.syndication.feed.synd.SyndEntry) SyndContentImpl(com.sun.syndication.feed.synd.SyndContentImpl) ArrayList(java.util.ArrayList) Date(java.util.Date) SyndFeed(com.sun.syndication.feed.synd.SyndFeed) SyndContent(com.sun.syndication.feed.synd.SyndContent) SyndEntryImpl(com.sun.syndication.feed.synd.SyndEntryImpl) Question(com.erudika.scoold.core.Question) SyndFeedImpl(com.sun.syndication.feed.synd.SyndFeedImpl)

Example 3 with Question

use of com.erudika.scoold.core.Question 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 4 with Question

use of com.erudika.scoold.core.Question 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 5 with Question

use of com.erudika.scoold.core.Question 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)

Aggregations

Question (com.erudika.scoold.core.Question)13 Pager (com.erudika.para.core.utils.Pager)9 Profile (com.erudika.scoold.core.Profile)9 UnapprovedQuestion (com.erudika.scoold.core.UnapprovedQuestion)7 Tag (com.erudika.para.core.Tag)6 Post (com.erudika.scoold.core.Post)6 IOException (java.io.IOException)6 ParaClient (com.erudika.para.client.ParaClient)5 Config (com.erudika.para.core.utils.Config)5 Utils (com.erudika.para.core.utils.Utils)5 Collections (java.util.Collections)5 List (java.util.List)5 Optional (java.util.Optional)5 Collectors (java.util.stream.Collectors)5 Inject (javax.inject.Inject)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 Address (com.erudika.para.core.Address)4 ParaObject (com.erudika.para.core.ParaObject)4 ArrayList (java.util.ArrayList)4