Search in sources :

Example 6 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method forceDelete.

@PostMapping
public String forceDelete(@RequestParam Boolean confirmdelete, @RequestParam String id, HttpServletRequest req) {
    Profile authUser = utils.getAuthUser(req);
    if (confirmdelete && utils.isAdmin(authUser)) {
        ParaObject object = pc.read(id);
        if (object != null) {
            object.delete();
            logger.info("{} #{} deleted {} #{}", authUser.getName(), authUser.getId(), object.getClass().getName(), object.getId());
        }
    }
    return "redirect:" + Optional.ofNullable(req.getParameter("returnto")).orElse(ADMINLINK);
}
Also used : ParaObject(com.erudika.para.core.ParaObject) Profile(com.erudika.scoold.core.Profile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 7 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method importFromSOArchive.

private List<ParaObject> importFromSOArchive(ZipInputStream zipIn, ZipEntry zipEntry, ObjectReader mapReader, Map<String, String> comments2authors) throws IOException, ParseException {
    if (zipEntry.getName().endsWith(".json")) {
        List<Map<String, Object>> objs = mapReader.readValue(new FilterInputStream(zipIn) {

            public void close() throws IOException {
                zipIn.closeEntry();
            }
        });
        List<ParaObject> toImport = new LinkedList<>();
        switch(zipEntry.getName()) {
            case "posts.json":
                importPostsFromSO(objs, toImport);
                break;
            case "tags.json":
                importTagsFromSO(objs, toImport);
                break;
            case "comments.json":
                importCommentsFromSO(objs, toImport, comments2authors);
                break;
            case "users.json":
                importUsersFromSO(objs, toImport);
                break;
            case "users2badges.json":
                // nice to have...
                break;
            case "accounts.json":
                importAccountsFromSO(objs);
                break;
            default:
                break;
        }
        // IN PRO: rewrite all image links to relative local URLs
        return toImport;
    } else {
        // IN PRO: store files in ./uploads
        return Collections.emptyList();
    }
}
Also used : FilterInputStream(java.io.FilterInputStream) ParaObject(com.erudika.para.core.ParaObject) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedList(java.util.LinkedList)

Example 8 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method restore.

@PostMapping("/import")
public String restore(@RequestParam("file") MultipartFile file, @RequestParam(required = false, defaultValue = "false") Boolean isso, HttpServletRequest req, HttpServletResponse res) {
    Profile authUser = utils.getAuthUser(req);
    if (!utils.isAdmin(authUser)) {
        res.setStatus(403);
        return null;
    }
    ObjectReader reader = ParaObjectUtils.getJsonMapper().readerFor(new TypeReference<List<Map<String, Object>>>() {
    });
    Map<String, String> comments2authors = new LinkedHashMap<>();
    int count = 0;
    int importBatchSize = Config.getConfigInt("import_batch_size", 100);
    String filename = file.getOriginalFilename();
    Sysprop s = new Sysprop();
    s.setType("scooldimport");
    try (InputStream inputStream = file.getInputStream()) {
        if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
            try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
                ZipEntry zipEntry;
                List<ParaObject> toCreate = new LinkedList<ParaObject>();
                while ((zipEntry = zipIn.getNextEntry()) != null) {
                    if (isso) {
                        count += importFromSOArchive(zipIn, zipEntry, reader, comments2authors).size();
                    } else if (zipEntry.getName().endsWith(".json")) {
                        List<Map<String, Object>> objects = reader.readValue(new FilterInputStream(zipIn) {

                            public void close() throws IOException {
                                zipIn.closeEntry();
                            }
                        });
                        objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
                        if (toCreate.size() >= importBatchSize) {
                            pc.createAll(toCreate);
                            toCreate.clear();
                        }
                        count += objects.size();
                    } else {
                        logger.error("Expected JSON but found unknown file type to import: {}", zipEntry.getName());
                    }
                }
                if (!toCreate.isEmpty()) {
                    pc.createAll(toCreate);
                }
                if (isso) {
                    updateSOCommentAuthors(comments2authors);
                }
            }
        } else if (StringUtils.endsWithIgnoreCase(filename, ".json")) {
            List<Map<String, Object>> objects = reader.readValue(inputStream);
            List<ParaObject> toCreate = new LinkedList<ParaObject>();
            objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
            count = objects.size();
            pc.createAll(toCreate);
        }
        s.setCreatorid(authUser.getCreatorid());
        s.setName(authUser.getName());
        s.addProperty("count", count);
        s.addProperty("file", filename);
        logger.info("Imported {} objects to {}. Executed by {}", count, Config.getConfigParam("access_key", "scoold"), authUser.getCreatorid() + " " + authUser.getName());
        if (count > 0) {
            pc.create(s);
        }
    } catch (Exception e) {
        logger.error("Failed to import " + filename, e);
        return "redirect:" + ADMINLINK + "?error=true&imported=" + count;
    }
    return "redirect:" + ADMINLINK + "?success=true&imported=" + count;
}
Also used : SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Question(com.erudika.scoold.core.Question) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) Webhook(com.erudika.para.core.Webhook) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) ParaClient(com.erudika.para.client.ParaClient) StringUtils(org.apache.commons.lang3.StringUtils) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) Model(org.springframework.ui.Model) Locale(java.util.Locale) Map(java.util.Map) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ParseException(java.text.ParseException) Config(com.erudika.para.core.utils.Config) ZipEntry(java.util.zip.ZipEntry) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) ParaObject(com.erudika.para.core.ParaObject) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ConfigValue(com.typesafe.config.ConfigValue) MediaType(org.springframework.http.MediaType) Set(java.util.Set) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) UUID(java.util.UUID) JsonMapper(com.fasterxml.jackson.databind.json.JsonMapper) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) Comment(com.erudika.scoold.core.Comment) List(java.util.List) Tag(com.erudika.para.core.Tag) Optional(java.util.Optional) ADMINLINK(com.erudika.scoold.ScooldServer.ADMINLINK) App(com.erudika.para.core.App) Sysprop(com.erudika.para.core.Sysprop) ZipOutputStream(java.util.zip.ZipOutputStream) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) ZipInputStream(java.util.zip.ZipInputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) ArrayList(java.util.ArrayList) HOMEPAGE(com.erudika.scoold.ScooldServer.HOMEPAGE) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterInputStream(java.io.FilterInputStream) GetMapping(org.springframework.web.bind.annotation.GetMapping) LinkedList(java.util.LinkedList) Logger(org.slf4j.Logger) Post(com.erudika.scoold.core.Post) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) User(com.erudika.para.core.User) Utils(com.erudika.para.core.utils.Utils) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) Reply(com.erudika.scoold.core.Reply) MultipartFile(org.springframework.web.multipart.MultipartFile) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) InputStream(java.io.InputStream) FilterInputStream(java.io.FilterInputStream) ZipInputStream(java.util.zip.ZipInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) ParseException(java.text.ParseException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ZipInputStream(java.util.zip.ZipInputStream) ParaObject(com.erudika.para.core.ParaObject) Sysprop(com.erudika.para.core.Sysprop) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ParaObject(com.erudika.para.core.ParaObject) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 9 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class VoteController method processVoteRequest.

boolean processVoteRequest(boolean isUpvote, String type, String id, HttpServletRequest req) {
    if (StringUtils.isBlank(id) || StringUtils.isBlank(type)) {
        return false;
    }
    ParaObject votable = pc.read(id);
    Profile author = null;
    Profile authUser = utils.getAuthUser(req);
    boolean result = false;
    boolean updateAuthUser = false;
    boolean updateVoter = false;
    if (votable == null || authUser == null) {
        return false;
    }
    try {
        author = pc.read(votable.getCreatorid());
        Integer votes = votable.getVotes() != null ? votable.getVotes() : 0;
        if (isUpvote && (result = pc.voteUp(votable, authUser.getId()))) {
            votes++;
            authUser.incrementUpvotes();
            updateAuthUser = true;
            int reward;
            if (votable instanceof Post) {
                Post p = (Post) votable;
                if (p.isReply()) {
                    utils.addBadge(author, GOODANSWER, votes >= GOODANSWER_IFHAS, false);
                    reward = ANSWER_VOTEUP_REWARD_AUTHOR;
                } else if (p.isQuestion()) {
                    utils.addBadge(author, GOODQUESTION, votes >= GOODQUESTION_IFHAS, false);
                    reward = QUESTION_VOTEUP_REWARD_AUTHOR;
                } else {
                    reward = VOTEUP_REWARD_AUTHOR;
                }
            } else {
                reward = VOTEUP_REWARD_AUTHOR;
            }
            if (author != null && reward > 0) {
                author.addRep(reward);
                updateVoter = true;
            }
        } else if (!isUpvote && (result = pc.voteDown(votable, authUser.getId()))) {
            votes--;
            authUser.incrementDownvotes();
            updateAuthUser = true;
            if (votable instanceof Comment && votes <= -5) {
                //treat comment as offensive or spam - hide
                ((Comment) votable).setHidden(true);
            } else if (votable instanceof Post && votes <= -5) {
                Post p = (Post) votable;
                //mark post for closing
                Report rep = new Report();
                rep.setParentid(id);
                rep.setLink(p.getPostLink(false, false));
                rep.setDescription(utils.getLang(req).get("posts.forclosing"));
                rep.setSubType(Report.ReportType.OTHER);
                rep.setAuthorName("System");
                rep.create();
            }
            if (author != null) {
                author.removeRep(POST_VOTEDOWN_PENALTY_AUTHOR);
                updateVoter = true;
                //small penalty to voter
                authUser.removeRep(POST_VOTEDOWN_PENALTY_VOTER);
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }
    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 (updateVoter) {
        pc.update(author);
    }
    if (updateAuthUser) {
        pc.update(authUser);
    }
    if (updateAuthUser && updateVoter) {
        pc.updateAll(Arrays.asList(author, authUser));
    }
    return result;
}
Also used : Comment(com.erudika.scoold.core.Comment) Report(com.erudika.scoold.core.Report) ParaObject(com.erudika.para.core.ParaObject) Post(com.erudika.scoold.core.Post) Profile(com.erudika.scoold.core.Profile)

Example 10 with ParaObject

use of com.erudika.para.core.ParaObject in project scoold by Erudika.

the class AdminController method importCommentsFromSO.

private void importCommentsFromSO(List<Map<String, Object>> objs, List<ParaObject> toImport, Map<String, String> comments2authors) throws ParseException {
    logger.info("Importing {} comments...", objs.size());
    for (Map<String, Object> obj : objs) {
        Comment c = new Comment();
        c.setId("comment_" + (Integer) obj.get("id"));
        c.setComment((String) obj.get("text"));
        Integer parentId = (Integer) obj.getOrDefault("postId", null);
        c.setParentid(parentId != null ? "post_" + parentId : null);
        c.setTimestamp(DateUtils.parseDate((String) obj.get("creationDate"), soDateFormat1, soDateFormat2).getTime());
        Integer creatorId = (Integer) obj.getOrDefault("userId", null);
        String userid = "user_" + creatorId;
        c.setCreatorid(creatorId != null ? Profile.id(userid) : utils.getSystemUser().getId());
        comments2authors.put(c.getId(), userid);
        toImport.add(c);
    }
    pc.createAll(toImport);
}
Also used : Comment(com.erudika.scoold.core.Comment) ParaObject(com.erudika.para.core.ParaObject)

Aggregations

ParaObject (com.erudika.para.core.ParaObject)17 Profile (com.erudika.scoold.core.Profile)10 Comment (com.erudika.scoold.core.Comment)7 Post (com.erudika.scoold.core.Post)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 LinkedHashMap (java.util.LinkedHashMap)5 LinkedList (java.util.LinkedList)5 Pager (com.erudika.para.core.utils.Pager)4 IOException (java.io.IOException)4 List (java.util.List)4 Tag (com.erudika.para.core.Tag)3 User (com.erudika.para.core.User)3 Question (com.erudika.scoold.core.Question)3 Reply (com.erudika.scoold.core.Reply)3 Map (java.util.Map)3 PostMapping (org.springframework.web.bind.annotation.PostMapping)3 ParaClient (com.erudika.para.client.ParaClient)2 Sysprop (com.erudika.para.core.Sysprop)2 Webhook (com.erudika.para.core.Webhook)2