Search in sources :

Example 6 with Question

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

the class AdminController method importPostsFromSO.

private void importPostsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport) throws ParseException {
    logger.info("Importing {} posts...", objs.size());
    for (Map<String, Object> obj : objs) {
        Post p;
        if ("question".equalsIgnoreCase((String) obj.get("postType"))) {
            p = new Question();
            p.setTitle((String) obj.get("title"));
            String t = StringUtils.stripStart(StringUtils.stripEnd((String) obj.getOrDefault("tags", ""), "|"), "|");
            p.setTags(Arrays.asList(t.split("\\|")));
            p.setAnswercount(((Integer) obj.getOrDefault("answerCount", 0)).longValue());
            Integer answerId = (Integer) obj.getOrDefault("acceptedAnswerId", null);
            p.setAnswerid(answerId != null ? "post_" + answerId : null);
        } else {
            p = new Reply();
            Integer parentId = (Integer) obj.getOrDefault("parentId", null);
            p.setParentid(parentId != null ? "post_" + parentId : null);
        }
        p.setId("post_" + (Integer) obj.getOrDefault("id", Utils.getNewId()));
        p.setBody((String) obj.get("bodyMarkdown"));
        p.setVotes((Integer) obj.getOrDefault("score", 0));
        p.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
        Integer creatorId = (Integer) obj.getOrDefault("ownerUserId", null);
        if (creatorId == null || creatorId == -1) {
            p.setCreatorid(utils.getSystemUser().getId());
        } else {
            // add prefix to avoid conflicts
            p.setCreatorid(Profile.id("user_" + creatorId));
        }
        toImport.add(p);
    }
    pc.createAll(toImport);
}
Also used : Post(com.erudika.scoold.core.Post) Reply(com.erudika.scoold.core.Reply) ParaObject(com.erudika.para.core.ParaObject) Question(com.erudika.scoold.core.Question)

Example 7 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, HttpServletRequest req, Model model) {
    if (utils.isAuthenticated(req)) {
        Profile authUser = utils.getAuthUser(req);
        Question q = utils.populate(req, new Question(), "title", "body", "tags|,", "location");
        q.setCreatorid(authUser.getId());
        Map<String, String> error = utils.validate(q);
        if (error.isEmpty()) {
            q.setLocation(location);
            String qid = q.create();
            if (!StringUtils.isBlank(latlng)) {
                Address addr = new Address();
                addr.setAddress(address);
                addr.setCountry(location);
                addr.setLatlng(latlng);
                addr.setParentid(qid);
                addr.setCreatorid(authUser.getId());
                pc.create(addr);
            }
            authUser.setLastseen(System.currentTimeMillis());
        } else {
            model.addAttribute("error", error);
            model.addAttribute("path", "questions.vm");
            model.addAttribute("includeGMapsScripts", true);
            model.addAttribute("askSelected", "navbtn-hover");
            return "base";
        }
        return "redirect:" + q.getPostLink(false, false);
    }
    return "redirect:" + signinlink + "?returnto=" + questionslink + "/ask";
}
Also used : Address(com.erudika.para.core.Address) Question(com.erudika.scoold.core.Question) Profile(com.erudika.scoold.core.Profile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 8 with Question

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

the class ScooldUtils method sendUpdatedFavTagsNotifications.

@SuppressWarnings("unchecked")
public void sendUpdatedFavTagsNotifications(Post question, List<String> addedTags, HttpServletRequest req) {
    if (!isFavTagsNotificationAllowed()) {
        return;
    }
    // sends a notification to subscibers of a tag if that tag was added to an existing question
    if (question != null && !question.isReply() && addedTags != null && !addedTags.isEmpty()) {
        // the current user - same as utils.getAuthUser(req)
        Profile postAuthor = question.getAuthor();
        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\">" + (addedTags.contains(t) ? "<b>" + escapeHtml(t) + "<b>" : escapeHtml(t)) + "</span>").collect(Collectors.joining("&nbsp;"));
        String subject = Utils.formatMessage(lang.get("notification.favtags.subject"), name, Utils.abbreviate(question.getTitle(), 255));
        model.put("subject", escapeHtml(subject));
        model.put("logourl", getSmallLogoUrl());
        model.put("heading", Utils.formatMessage(lang.get("notification.favtags.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 = getFavTagsSubscribers(addedTags);
        sendEmailsToSubscribersInSpace(emails, question.getSpace(), subject, compileEmailTemplate(model));
    }
}
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) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ParaObject(com.erudika.para.core.ParaObject) ConfigObject(com.typesafe.config.ConfigObject) Profile(com.erudika.scoold.core.Profile)

Example 9 with Question

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

the class TagsController method delete.

@PostMapping("/delete")
public String delete(@RequestParam String tag, HttpServletRequest req, HttpServletResponse res) {
    Profile authUser = utils.getAuthUser(req);
    if (utils.isMod(authUser)) {
        Tag t = pc.read(Utils.type(Tag.class), new Tag(tag).getId());
        if (t != null) {
            pc.delete(t);
            logger.info("User {} ({}) deleted tag '{}'.", authUser.getName(), authUser.getCreatorid(), t.getTag());
            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[] { t.getTag() }, pager);
                for (Question q : questionslist) {
                    t.setCount(t.getCount() + 1);
                    q.setTags(Optional.ofNullable(q.getTags()).orElse(Collections.emptyList()).stream().filter(ts -> !ts.equals(t.getTag())).distinct().collect(Collectors.toList()));
                    logger.debug("Removed tag {} from {} out of {} questions.", t.getTag(), questionslist.size(), pager.getCount());
                }
                if (!questionslist.isEmpty()) {
                    pc.updateAll(questionslist);
                }
            } while (!questionslist.isEmpty());
        }
    }
    if (utils.isAjaxRequest(req)) {
        res.setStatus(200);
        return "blank";
    } else {
        return "redirect:" + TAGSLINK + "?" + req.getQueryString();
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Question(com.erudika.scoold.core.Question) RequestParam(org.springframework.web.bind.annotation.RequestParam) LoggerFactory(org.slf4j.LoggerFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ParaClient(com.erudika.para.client.ParaClient) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) Model(org.springframework.ui.Model) GetMapping(org.springframework.web.bind.annotation.GetMapping) Config(com.erudika.para.core.utils.Config) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Collectors(java.util.stream.Collectors) Utils(com.erudika.para.core.utils.Utils) List(java.util.List) Tag(com.erudika.para.core.Tag) TAGSLINK(com.erudika.scoold.ScooldServer.TAGSLINK) Optional(java.util.Optional) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) Pager(com.erudika.para.core.utils.Pager) Question(com.erudika.scoold.core.Question) Tag(com.erudika.para.core.Tag) Profile(com.erudika.scoold.core.Profile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 10 with Question

use of com.erudika.scoold.core.Question 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();
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Question(com.erudika.scoold.core.Question) RequestParam(org.springframework.web.bind.annotation.RequestParam) LoggerFactory(org.slf4j.LoggerFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ParaClient(com.erudika.para.client.ParaClient) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MediaType(javax.ws.rs.core.MediaType) Model(org.springframework.ui.Model) GetMapping(org.springframework.web.bind.annotation.GetMapping) Config(com.erudika.para.core.utils.Config) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Collectors(java.util.stream.Collectors) Utils(com.erudika.para.core.utils.Utils) List(java.util.List) Tag(com.erudika.para.core.Tag) TAGSLINK(com.erudika.scoold.ScooldServer.TAGSLINK) Optional(java.util.Optional) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) Pager(com.erudika.para.core.utils.Pager) Question(com.erudika.scoold.core.Question) Tag(com.erudika.para.core.Tag) 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