Search in sources :

Example 56 with Profile

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

Example 57 with Profile

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

the class VoteController method processVoteRequest.

boolean processVoteRequest(boolean isUpvote, ParaObject votable, HttpServletRequest req) {
    Profile author = null;
    Profile authUser = utils.getAuthUser(req);
    boolean result = false;
    boolean update = false;
    if (votable == null || authUser == null) {
        return false;
    }
    try {
        List<ParaObject> voteObjects = pc.readAll(Arrays.asList(votable.getCreatorid(), new Vote(authUser.getId(), votable.getId(), Votable.VoteValue.UP).getId(), new Vote(authUser.getId(), votable.getId(), Votable.VoteValue.DOWN).getId()));
        author = (Profile) voteObjects.stream().filter((p) -> p instanceof Profile).findFirst().orElse(null);
        Integer votes = votable.getVotes() != null ? votable.getVotes() : 0;
        boolean upvoteExists = voteObjects.stream().anyMatch((v) -> v instanceof Vote && ((Vote) v).isUpvote());
        boolean downvoteExists = voteObjects.stream().anyMatch((v) -> v instanceof Vote && ((Vote) v).isDownvote());
        boolean isVoteCorrection = (isUpvote && downvoteExists) || (!isUpvote && upvoteExists);
        if (isUpvote && voteUp(votable, authUser.getId())) {
            votes++;
            result = true;
            update = updateReputationOnUpvote(votable, votes, authUser, author, isVoteCorrection);
        } else if (!isUpvote && voteDown(votable, authUser.getId())) {
            votes--;
            result = true;
            hideCommentAndReport(votable, votes, votable.getId(), req);
            update = updateReputationOnDownvote(votable, votes, authUser, author, isVoteCorrection);
        }
    } catch (Exception ex) {
        logger.error(null, ex);
        result = false;
    }
    utils.addBadgeOnce(authUser, SUPPORTER, authUser.getUpvotes() >= SUPPORTER_IFHAS);
    utils.addBadgeOnce(authUser, CRITIC, authUser.getDownvotes() >= CRITIC_IFHAS);
    utils.addBadgeOnce(authUser, VOTER, authUser.getTotalVotes() >= VOTER_IFHAS);
    if (update) {
        pc.updateAll(Arrays.asList(author, authUser));
    }
    return result;
}
Also used : Vote(com.erudika.para.core.Vote) ParaObject(com.erudika.para.core.ParaObject) Profile(com.erudika.scoold.core.Profile)

Example 58 with Profile

use of com.erudika.scoold.core.Profile 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() : "");
}
Also used : SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) ParaClient(com.erudika.para.client.ParaClient) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) HashSet(java.util.HashSet) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) Model(org.springframework.ui.Model) Map(java.util.Map) GetMapping(org.springframework.web.bind.annotation.GetMapping) LinkedList(java.util.LinkedList) Config(com.erudika.para.core.utils.Config) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) ParaObject(com.erudika.para.core.ParaObject) PEOPLELINK(com.erudika.scoold.ScooldServer.PEOPLELINK) HttpServletResponse(javax.servlet.http.HttpServletResponse) Utils(com.erudika.para.core.utils.Utils) HttpUtils(com.erudika.scoold.utils.HttpUtils) List(java.util.List) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) HashMap(java.util.HashMap) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) Pager(com.erudika.para.core.utils.Pager) ParaObject(com.erudika.para.core.ParaObject) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 59 with Profile

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

the class PeopleController method get.

@GetMapping(path = { "", "/bulk-edit" })
public String get(@RequestParam(required = false, defaultValue = Config._TIMESTAMP) String sortby, @RequestParam(required = false, defaultValue = "*") String q, HttpServletRequest req, Model model) {
    if (!utils.isDefaultSpacePublic() && !utils.isAuthenticated(req)) {
        return "redirect:" + SIGNINLINK + "?returnto=" + PEOPLELINK;
    }
    if (req.getRequestURI().endsWith("/bulk-edit")) {
        return "redirect:" + PEOPLELINK + "?bulk-edit=true";
    }
    Profile authUser = utils.getAuthUser(req);
    Pager itemcount = utils.getPager("page", req);
    itemcount.setSortby(sortby);
    // [space query filter] + original query string
    String qs = utils.sanitizeQueryString(q, req);
    if (req.getParameter("bulkedit") != null && utils.isAdmin(authUser)) {
        qs = q;
    } else {
        qs = qs.replaceAll("properties\\.space:", "properties.spaces:");
    }
    if (!qs.endsWith("*")) {
        // admins are members of every space and always visible
        qs += " OR properties.groups:(admins)";
    }
    List<Profile> userlist = pc.findQuery(Utils.type(Profile.class), qs, itemcount);
    model.addAttribute("path", "people.vm");
    model.addAttribute("title", utils.getLang(req).get("people.title"));
    model.addAttribute("peopleSelected", "navbtn-hover");
    model.addAttribute("itemcount", itemcount);
    model.addAttribute("userlist", userlist);
    if (req.getParameter("bulkedit") != null && utils.isAdmin(authUser)) {
        List<ParaObject> spaces = pc.findQuery("scooldspace", "*", new Pager(Config.DEFAULT_LIMIT));
        model.addAttribute("spaces", spaces);
    }
    return "base";
}
Also used : ParaObject(com.erudika.para.core.ParaObject) Pager(com.erudika.para.core.utils.Pager) Profile(com.erudika.scoold.core.Profile) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 60 with Profile

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

the class ProfileController method edit.

@PostMapping("/{id}")
public String edit(@PathVariable(required = false) String id, @RequestParam(required = false) String name, @RequestParam(required = false) String location, @RequestParam(required = false) String latlng, @RequestParam(required = false) String website, @RequestParam(required = false) String aboutme, @RequestParam(required = false) String picture, HttpServletRequest req, Model model) {
    Profile authUser = utils.getAuthUser(req);
    Profile showUser = getProfileForEditing(id, authUser);
    if (showUser != null) {
        boolean updateProfile = false;
        if (!isMyid(authUser, id)) {
            showUser = utils.getParaClient().read(Profile.id(id));
        }
        if (!StringUtils.equals(showUser.getLocation(), location)) {
            showUser.setLatlng(latlng);
            showUser.setLocation(location);
            updateProfile = true;
        }
        if (!StringUtils.equals(showUser.getWebsite(), website) && (StringUtils.isBlank(website) || Utils.isValidURL(website))) {
            showUser.setWebsite(website);
            updateProfile = true;
        }
        if (!StringUtils.equals(showUser.getAboutme(), aboutme)) {
            showUser.setAboutme(aboutme);
            updateProfile = true;
        }
        updateProfile = updateUserPictureAndName(showUser, picture, name) || updateProfile;
        boolean isComplete = showUser.isComplete() && isMyid(authUser, showUser.getId());
        if (updateProfile || utils.addBadgeOnce(showUser, Badge.NICEPROFILE, isComplete)) {
            showUser.update();
        }
        model.addAttribute("user", showUser);
    }
    return "redirect:" + PROFILELINK + (isMyid(authUser, id) ? "" : "/" + id);
}
Also used : Profile(com.erudika.scoold.core.Profile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

Profile (com.erudika.scoold.core.Profile)85 PostMapping (org.springframework.web.bind.annotation.PostMapping)47 Post (com.erudika.scoold.core.Post)29 ParaObject (com.erudika.para.core.ParaObject)25 User (com.erudika.para.core.User)19 Pager (com.erudika.para.core.utils.Pager)19 HashMap (java.util.HashMap)15 LinkedHashMap (java.util.LinkedHashMap)15 Question (com.erudika.scoold.core.Question)13 Reply (com.erudika.scoold.core.Reply)13 Report (com.erudika.scoold.core.Report)11 IOException (java.io.IOException)11 List (java.util.List)11 Map (java.util.Map)11 UnapprovedReply (com.erudika.scoold.core.UnapprovedReply)10 GetMapping (org.springframework.web.bind.annotation.GetMapping)10 Sysprop (com.erudika.para.core.Sysprop)9 Config (com.erudika.para.core.utils.Config)9 Utils (com.erudika.para.core.utils.Utils)9 Comment (com.erudika.scoold.core.Comment)9