Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
16 kB
3
Indexable
Never
/** @format */

require("dotenv").config();
const express = require("express");
const router = express.Router();
const Multer = require("multer");
const uuid = require("uuid");
const uuidv1 = uuid.v1;
const { Storage } = require("@google-cloud/storage");
const { default: mongoose } = require("mongoose");
const { config } = require("dotenv");
const sharp = require("sharp");
const Aerospike = require("aerospike");
const { getAerospikeClient } = require("../../../../databases/aerospike");
const maps = Aerospike.maps;
const { removeStopwords, eng, fra } = require("stopword");
const now = require("nano-time");

const multer = Multer({
  storage: Multer.memoryStorage(),
  limits: {
    fileSize: 500 * 1024 * 1024,
  },
});
// const bucket = storage.bucket("dexbros_files");

/**
 * @START
 */
const {
  createPostLike,
  viewFullPost,
  handleDislike,
  handleHaha,
  handleAngry,
  fetchLikeUser,
  fetchPosts,
  fetchSubPosts,
  fetchBlockFeed,
  fetchSinglePost,
  spamPost,
  bookmarkPost,
  repostPost,
  editPost,
  pinnedPost,
  deletePost,
  hideUnhidePost,
  ctrlCreateNewBlockPost,
  donatePost,
  fetchAnalytics,
  createComment,
  fetchComments,
  fetchSingleCommentMeta,
  fetchMyComments,
  likeComment,
  removeLike,
  reportComment,
  pinnedComment,
  editComment,
  deleteComment,
  hideComment,
  handleRepostBlockComment,
  fetchFlaggedUsersList,
  createReply,
  replyReply,
  fetchReplies,
  //getRepliesReply,
  hideCommentReply,
  deleteReply,
  likeReply,
  dislikeReply,
  spamReply,
  innerReplyLike,
  createEvent,
  fetchEvents,
  joinEvent,
  fetchEvent,
  deleteEvent,
  editReply,
  eventInterest,
  handleHideEvent,
  eventNotInterest,
  eventjoin,
  blockFeed,
  eventFeed,
  reportEvent,
  reportPost,
  getPostAnalytics,
  fetchFullPostInModal,
  addPostLike,
  removePostLike,
  updateNewsPost,
  upvoteNewsPost,
  downvoteNewsPost,
  fakeNewsPost,
  flagPost,
  excitedAnnouncementPost,
  disapointedAnnouncementPost,
  misleadingAnnouncementPost,
  fetchUpvoteUsers,
  fetchExcitedUsers,
  sharePost,
  fetchPostEarning,
  fetchDonateUsers,
  createOrUpdateBlockPostBoost,
  getBlockPostBoost,
  pinAndUnpinComment,
  fetchCommentsMostReactions,
  BlockCmntRepostWithQuote,
  handleSpamComment,
} = require("../../../controller/post/blockPost/blockPostController");
const createHttpError = require("http-errors");

router.get("/get_feed", blockFeed);

//for full url view not popup
router.get("/view/full/post/:id", viewFullPost);

router.put("/like/:id", createPostLike);

// router.put("/dislike/:id", handleDislike);

// router.put("/haha/:id", handleHaha);

// *** Create angry emoji
// router.put("/angry/:id", handleAngry);

// router.get("/:id/liked_user", fetchLikeUser);

// fetch group posts
router.get("/:id", fetchPosts);
router.get("/subs-post/:id", fetchSubPosts);

// fetch like user
router.get("/like/users/:id", fetchLikeUser);

// fetch block feed
router.get("/block/feed", fetchBlockFeed);

// Fetch single post
// router.get("/single/:id", fetchSinglePost);

router.put("/spam/:id", spamPost);

router.put("/bookmark/:id", bookmarkPost);

// Create Post Edit route
router.put("/edit/:id", editPost);

// Create Pinned Post route
router.put("/pinned/:id", pinnedPost);

// Create Delete Post route
router.put("/delete/:id", deletePost);

// POST HIDE & UNHIDE ROUTE
router.put("/hide/:id", hideUnhidePost);

// ******* CREATE GROUP POST API REDESIGN ******* //
router.post("/create/post/:id", multer.single("image"), ctrlCreateNewBlockPost);

router.post("/donate/:id", donatePost);

router.get("/fetch/analytics/:id", fetchAnalytics);

//**************** GROUP POST COMMENT **************//
router.post("/comments/:id", multer.single("cmnt_img"), createComment);

router.get("/comments/:id", fetchComments);

router.get("/comment/meta/:id", fetchSingleCommentMeta)

router.get("/my_comments/:id", fetchMyComments);

router.put("/comment/:type/:id/:username/:likeCount/:p_type", likeComment);

//router.put("/comment/like/remove/:id", removeLike);
//router.put("/comment/like/remove/:id", likeComment);

router.put("/comment/spam/:id", handleSpamComment);
// 5. pin a comment
router.put("/comment/pinned/:id/:postId", pinAndUnpinComment);

// 6. Edit  comment
router.put("/comment/edit/:id", multer.single("img"), editComment);

// 7. Delete Comment
router.put("/comment/delete/:id/:type", deleteComment);

// 8. Hide comment
router.put("/comment/hide/:id", hideComment);

//9. repost comment
router.put('/comment/repost/:id',handleRepostBlockComment)

//10. users those are did flag on a single comment
router.get("/comment/users/spam/:id", fetchFlaggedUsersList);

//11. comment's most two reactions
router.get("/comment/most/reactions/:id",fetchCommentsMostReactions );

//12. comment's repost with quote
router.post("/comment/repost/quote/:id", BlockCmntRepostWithQuote);

// ******************* Replies ******************* //

// ******* CREATE GROUP COMMENT REPLY
router.post("/comment/reply/:id", createReply);
router.post("/reply/reply/:id", replyReply);

// *** Fetch all replies
router.get("/comment/reply/:id", fetchReplies);

//router.get("/comment/replies/reply/:id", getRepliesReply);

// *** Group comment reply HIDE
router.put("/comment/reply/hide/:id", hideCommentReply);

router.put("/comment/reply/delete/:id", deleteReply);

router.put("/comment/reply/edit/:id", editReply);

// *** Group comment reply LIKE
router.put("/comment/reply/like/:id", likeReply);

router.put("/comment/reply/dislike/:id", dislikeReply);

router.put("/comment/reply/spam/:id", spamReply);

// **** Group Event
router.post("/event/create", multer.single("eventimage"), createEvent);

router.get("/events/:id", fetchEvents);

router.put("/event/join/:id", joinEvent);

router.get("/event/:id", fetchEvent);

router.put("/event/delete/:id", deleteEvent);
router.put("/event/edit/:id", async (req, res) => {
  if (!req.params.id) {
    throw createHttpError.BadRequest("Invalid ID");
  } else {
    const client = await getAerospikeClient();
    const key = new Aerospike.Key(
      process.env.CLUSTER_NAME,
      process.env.SET_BLOCK_EVENT,
      req.params.id
    );
    const ops = [
      Aerospike.operations.write("tit", req.body.title),
      Aerospike.operations.write("des", req.body.description),
      Aerospike.operations.write("s_d", req.body.startdate),
      Aerospike.operations.write("e_d", req.body.enddate),
      Aerospike.operations.write("price", req.body.price),
      Aerospike.operations.write("time", req.body.time),
      Aerospike.operations.write("timezone", req.body.timezone),
    ];
    await client.operate(key, ops);
    try {
      return { msg: "Event has been updated" };
    } catch (err) {
      throw createHttpError.BadRequest("ERROR");
    }
  }
});

router.put("/event/interest/:id", eventInterest);

router.put("/event/hide/:id", handleHideEvent);

router.put("/event/not_interest/:id", eventNotInterest);

router.get("/block/event/feed", eventFeed);
router.put("/event/report/:id", reportEvent);
router.put("/report/:id", reportPost);

// **** Post NFT donation
router.post("/donate/:id", async (req, res) => {
  const client = await getAerospikeClient();
  const id = req.params.id;
  if (!id) {
    return res.status(400).json({ msg: "Invalid request" });
  } else {
    const post_meta_key = new Aerospike.Key(
      process.env.CLUSTER_NAME,
      process.env.SET_GROUP_POST_META,
      id
    );

    const post_key = new Aerospike.Key(
      process.env.CLUSTER_NAME,
      process.env.SET_POSTS,
      id
    );

    const data = await client.get(post_key);
    try {
      const notificationData = {
        id: id,
        ty: 7,
        vi: false,
        wo: req.user.handleUn,
        ti: Date.now(),
        nm: `${req.user.fn} ${req.user.ln}`,
        pi: req.user.p_i,
        amount: req.query.amount,
      };
      // *** Send notification data into kafka broker
      await sendNotificationMessage("post_notification", notificationData);
      client.exists(post_meta_key, async (err, result) => {
        if (err) {
          return res.status(400).json({ msg: err.message });
        } else {
          if (!result) {
            return res.status(400).json({ msg: "No post found" });
          } else {
            // ** Generating time stamp
            const time = Date.now().toString();
            let record = await client.get(post_meta_key);

            const bins = {
              id: time,
              amount: req.query.amount,
              s_name: `${req.user.fn} ${req.user.ln}`,
              s_handleUn: req.user.handleUn,
              s_pic: req.user.p_i || "",
              r_username: req.query.handleUn,
              postId: id,
              message: req.query.message || "",
            };
            const earn_key = new Aerospike.Key(
              process.env.CLUSTER_NAME,
              process.env.SET_EARNING,
              time
            );
            const user_earning_key = new Aerospike.Key(
              process.env.CLUSTER_NAME,
              process.env.SET_USER_EARNING,
              time
            );

            // *** Earn Bin
            const earn_bin = [
              Aerospike.operations.write("_id", time),
              Aerospike.operations.write("receiver", req.query.handleUn),
              Aerospike.operations.write("sender", req.user.handleUn),
              Aerospike.operations.write("amount", req.query.amount),
              Aerospike.operations.write("type", "post"),
              Aerospike.operations.write("id", id || ""),
            ];
            await client.operate(user_earning_key, earn_bin);

            client.put(earn_key, bins, async (err, result) => {
              if (err) {
                return res.status(400).json({ msg: err.message });
              } else {
                let record = await client.get(post_meta_key);
                if (record.bins.earn) {
                  console.log("Have ", record.bins.earn);
                  const ops = [
                    Aerospike.maps
                      .getByKey("earn", time)
                      .andReturn(Aerospike.maps.returnType.KEY_VALUE),
                  ];

                  client.operate(post_meta_key, ops, async (err, result) => {
                    if (err) {
                      return res.status(400).json({ msg: err.message });
                    } else {
                      if (result.bins.earn[0] === time) {
                        const value =
                          Number(result.bins.earn[1]) +
                          Number(req.query.amount);

                        const ops = [
                          Aerospike.maps.put("earn", time, value, {
                            order: maps.order.KEY_ORDERED,
                          }),
                        ];
                        let data = await client.operate(post_meta_key, ops);
                        try {
                          const getPost = await client.get(post_key);
                          const total =
                            getPost.bins.earn + Number(req.query.amount);

                          const ops = [
                            Aerospike.operations.write("earn", total),
                          ];

                          await client.operate(post_key, ops);
                          return res.status(200).json({ msg: "Success" });
                        } catch (error) {
                          return res.status(400).json({ msg: error.message });
                        }
                      } else {
                        const ops = [
                          Aerospike.maps.put("earn", time, req.query.amount, {
                            order: maps.order.KEY_ORDERED,
                          }),
                        ];
                        let result = await client.operate(post_meta_key, ops);
                        try {
                          // let result = await client.put(user_earning_key, earn_bin);
                          try {
                            const getPost = await client.get(post_key);
                            const total =
                              Number(getPost.bins.earn) +
                              Number(req.query.amount);

                            console.log(">> Total earning: ", total);
                            const ops = [
                              Aerospike.operations.write("earn", total),
                            ];
                            await client.operate(post_key, ops);
                            return res.status(200).json({ msg: "Success" });
                          } catch (error) {
                            return res.status(400).json({ msg: error.message });
                          }
                        } catch (error) {
                          return res.status(400).json({ msg: error.message });
                        }
                      }
                    }
                  });
                } else {
                  const ops = [
                    Aerospike.maps.put("earn", time, req.query.amount, {
                      order: maps.order.KEY_ORDERED,
                    }),
                  ];
                  let result = await client.operate(post_meta_key, ops);
                  try {
                    // let result = await client.put(user_earning_key, earn_bin);
                    try {
                      const ops = [Aerospike.operations.write("earn", total)];
                      await client.operate(post_key, ops);
                      return res
                        .status(200)
                        .json({ msg: "Successfully donated" });
                    } catch (error) {
                      return res.status(400).json({ msg: err.message });
                    }
                  } catch (error) {
                    return res.status(400).json({ msg: error.message });
                  }
                }
              }
            });
          }
        }
      });
    } catch (error) {
      return res.status(400).json({ msg: error.message });
    }
  }
});

// *** GET full group post for analytics
router.get("/analytics/:id", getPostAnalytics);

router.get("/full-post/:id", fetchFullPostInModal);

router.put("/emoji/add/like/:id", addPostLike);

router.put("/emoji/remove/like/:id", removePostLike);

// *** Block post News POST
router.put("/news-post/:id", updateNewsPost);

// *** Block News Post Upvote
router.put("/upvote/:id", upvoteNewsPost);

// *** Block News Post Downvote
router.put("/downvote/:id", downvoteNewsPost);

// *** Block News Post Fake
router.put("/fake/:id", fakeNewsPost);

// *** Block Post FLAG
router.put("/flag/:id", flagPost);

// *** Block Announcement Post Excited
router.put("/exicted/:id", excitedAnnouncementPost);

// *** Block Announcement Post Disapointed
router.put("/disapointed/:id", disapointedAnnouncementPost);

// *** Block Announcement Post Misleading
router.put("/misleading/:id", misleadingAnnouncementPost);

// *** Block fetch upvote users/
router.get("/upvote/:id", fetchUpvoteUsers);

// *** Block fetch Excited users/
router.get("/excited/:id", fetchExcitedUsers);

// *** Block Post share POST
router.put("/share/:id", sharePost);

// *** Fetch block post earning
router.get("/fetch/earnings/:id", fetchPostEarning);

// *** Fetch who is dontaing my block POST
router.get("/fetch/donate/users/:id", fetchDonateUsers);

// *** Create Repost Post route
router.put("/repost/:id", repostPost);

router.post("/boost/:id", createOrUpdateBlockPostBoost);

router.get("/fetch/boost", getBlockPostBoost);

module.exports = router;
Leave a Comment