Untitled

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

//** @format */

const jwt = require("jsonwebtoken");
const { Storage } = require("@google-cloud/storage");
const Aerospike = require("aerospike");
const lists = Aerospike.lists;
const maps = Aerospike.maps;
const { getAerospikeClient } = require("../../../../databases/aerospike");
const { removeStopwords, eng, fra } = require("stopword");
const now = require("nano-time");
const batchType = Aerospike.batchType;
var createError = require("http-errors");
const { uploadImage } = require("../../../helper/uploadBucket");
const { populate } = require("../../../helper/populate");
const createNodeCache = require("../../../../node-cache");
const cacheGetTrending = createNodeCache(60 * 10);
const { sendMessage } = require("../../../../kafka/old_folders/producer.js");
const { sendNotificationMessage } = require("../../../../kafka/producerNoti");
const {
  getRange,
  setDataWithTTL,
  getData,
} = require("../../../helper/redisHelper");

const {
  socialBookmarkPost,
  socialPinnedPost,
  socialCreatePost,
  socialBookmark,
  socialHidePost,
  socialPostEdit,
  socialPostSpam,
  socialFlagPost,
  handleRepostPost,
  socialNewsFetch,
  socialfetchUserRelatedPosts,
  userProfilePosts,
  socialTreandingWords,
  socialTreandingCoinNames,
  socialDonatNft,
  socialDonationHistory,
  fetchDonationDetails,
  socialSharePost,
  socialSharePostPrivacy,
  socialCommentPostPrivacy,
  socialPostToNft,
  socialFetchFullPost,
  createNewGeneralPost,
  fetchSocialPostWithComment,
  updatePostViewCount,
  fetchActivityList,
  handleUploadNFT,
  handleFetchNFTs,
  handleLikeNFT,
  handleCreateNFTComment,
  handleNFTCommentPin,
  handleFetchNFTComments,
  updateNFTComment,
  deleteNFTComment,
  likeNFTComment,
  createNFTReply,
  likeNFTReply,
  editNFTReply,
  handleGetReplies,
  handleDeleteReply,
  handleReportPost,
  handleCreateNewPoll,
  handlePollVote,
  handleAddPostLike,
  handleRemovePostLike,
  fetchBlockFeedPosts,
  handleGetVoterLists,
  handleGetVotersList,
  handleGetMentionPosts,
  handleGetCoinPrice,
  handleFetchTrendingPosts,
  handleFetchTrendingCoinPost,
  handleFetchLikedUsers,
  handleGetAnalytics,
  handleDonateNFT,
  handleDislikeInnerReply,
  handleLikeInnerReply,
  handleSpamInnerReply,
  handleSearchPost,
  socialfetchUserFollowingsPosts,
  socialfetchUserAllPosts,
} = require("../../../model/post/generalPost/postModel");

const {
  createPostComment,
  socialPinnedComment,
  socialDeleteComment,
  socialEditComment,
  socialSpamComment,
  socialLikeComment,
  socialRemoveLikeComment,
  fetchSocialComments,
  fetchSocialMyComments,
} = require("../../../model/comment/generalComment/generalCommentModel.js");

const {
  socialCreatReply,
  socialCreatReplyInsideReply,
  socialFetchCommentReply,
  socialHideReply,
  socialDeleteReply,
  socialDislikeReply,
  socialLikeReply,
} = require("../../../model/reply/generalReply/generalReplyModel.js");

class PostController {
  constructor() {
    // console.log("Post controller init");
  }

  // *** Update post count
  async updateViewCount(req, res, next) {
    try {
      const data = await updatePostViewCount(req.body);
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Create new post
  async ctrlCreateNewPost(req, res, next) {
    // console.log(req.file);
    try {
      console.log(req.user);
      const data = await createNewGeneralPost(
        req.user,
        req.body,
        req.file,
        req.query
      );
      return res.status(201).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Pinned Post
  async pinnedPost(req, res, next) {
    try {
      const data = await socialPinnedPost(req.params.id);
      try {
        res.status(200).json(data);
      } catch (error) {
        throw createError.Conflict(error.message);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Bookmark post
  async bookmarkPost(req, res, next) {
    try {
      const data = await socialBookmark(
        req.params.id,
        req.user.handleUn,
        req.body.btnType
      );
      try {
        res.status(200).json(data);
      } catch (error) {
        throw createError.Conflict(error.message);
      }
    } catch (error) {
      next(error.message);
    }
  }

  // *** Hide post
  async hidePost(req, res, next) {
    try {
      // const client = await getAerospikeClient();
      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await socialHidePost(req.params.id, req.user.handleUn);
        try {
          res.status(200).json(data);
        } catch (error) {
          throw createError.Conflict(error.message);
        }
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch post analytics
  async fetchPostAnalytics(req, res, next) {
    // console.log("Came in backend");
    try {
      const client = await getAerospikeClient();
      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        console.log(req.params.id);
        const post_key = new Aerospike.Key(
          process.env.CLUSTER_NAME,
          process.env.SET_POSTS,
          req.params.id
        );
        const post_meta_key = new Aerospike.Key(
          process.env.CLUSTER_NAME,
          process.env.SET_POSTS_META,
          req.params.id
        );

        var post;

        client.exists(post_key, async (err, result) => {
          if (err) {
            throw createError.BadRequest(err.message);
          } else {
            if (!result) {
              throw createError.BadRequest(err.message);
            } else {
              const mapOps = [
                Aerospike.maps
                  .getByKey("analytics", req.query.date)
                  .andReturn(maps.returnType.KEY_VALUE),
              ];
              client.operate(post_meta_key, mapOps, async (err, result) => {
                const post = await client.get(post_meta_key);
                if (err) {
                  throw createError.BadRequest(err.message);
                } else {
                  console.log({
                    metaData: post,
                    analytics: result.bins.analytics,
                  });
                  return res
                    .status(200)
                    .json({ metaData: post, analytics: result.bins.analytics });
                }
              });
            }
          }
        });
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Post edit
  async postEdit(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await socialPostEdit(
          req.body,
          req.params.id,
          req.user.handleUn
        );
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Post delete
  async deletePost(req, res, next) {
    console.log("req.params.id", req.params.id);
    try {
      const client = await getAerospikeClient();
      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        // const post_key = new Aerospike.Key(
        //   process.env.CLUSTER_NAME,
        //   process.env.SET_POSTS,
        //   req.params.id.toString()
        // );
        const post_meta_key = new Aerospike.Key(
          process.env.CLUSTER_NAME,
          process.env.SET_POSTS_META,
          req.params.id.toString()
        );
        const main_post_key = new Aerospike.Key(
          process.env.CLUSTER_NAME,
          process.env.SET_MAIN_POSTS,
          req.params.id.toString()
        );

        client
          .exists(main_post_key)
          .then((data) => {
            if (data) {
              const ops = [Aerospike.operations.write("isDelete", true)];
              client.operate(main_post_key, ops, async (err, result) => {
                if (err) {
                  throw createError.BadRequest(err.message);
                } else {
                  // await client.operate(main_post_key, ops);
                  return res.status(200).json({ msg: "Post deleted" });
                }
              });
            }
          })
          .catch((err) => {
            throw createError.BadRequest(err.message);
          });
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Post spam
  async spamPost(req, res, next) {
    try {
      const client = await getAerospikeClient();
      var incrmentedBy = 0;

      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await socialPostSpam(req.params.id, req.user.handleUn);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  async flagPost(req, res, next) {
    try {
      const client = await getAerospikeClient();
      var incrmentedBy = 0;

      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await socialFlagPost(req.params.id, req.user);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  async socialRepostPost(req, res, next) {
    try {
      const client = await getAerospikeClient();
      var incrmentedBy = 0;

      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await handleRepostPost(req.params.id, req.user);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch news
  async fetchNews(req, res, next) {
    try {
      const data = await socialNewsFetch();
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch feed posts
  // async fetchFeedPost(req, res, next) {
  //   console.log("CAME TO THIS PONT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>!!!!");
  //   const client = await getAerospikeClient();
  //   var page = req.query.page || 0;
  //   var posts = [];
  //   var temp = [];
  //   var limit = req.query.limit || 5;
  //   let start = Number(limit) * Number(page);
  //   let end =
  //     page > 0 ? Number(limit) * Number(page) * 2 - 1 : Number(limit) - 1;
  //   var result = [];
  //   const data = await getRange("post", start, end);
  //   console.log("test_redis", data);
  //   for (let i = 0; i < data.length; i++) {
  //     if (data[i].trim()) {
  //       temp.push({
  //         key: new Aerospike.Key(
  //           process.env.CLUSTER_NAME,
  //           process.env.SET_POSTS,
  //           data[i]
  //         ),
  //         type: batchType.BATCH_READ,
  //         readAllBins: true,
  //       });
  //     }
  //   }
  //   posts = await client.batchRead(temp);

  //   for (let i = 0; i < posts.length; i++) {
  //     posts[i].record.bins && result.push(posts[i].record.bins);
  //   }
  //   return res.status(200).json(result);
  // }
  async fetchFeedPost(req, res, next) {
    try {
      const data = await socialfetchUserAllPosts(req.query);
      return res.status(200).json(data);
    } catch (error) {
      console.error("Error fetching feed posts", error);
      return res.status(500).json({ error: "Internal Server Error" });
    }
  }

  // *** Fetch for you feed posts
  async fetchForYouFeedPost(req, res, next) {
    try {
      const data = await socialfetchUserRelatedPosts(
        req.query,
        req.user.handleUn
      );
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch for your following feed posts
  async fetchForYourFollowingFeedPost(req, res, next) {
    try {
      const data = await socialfetchUserFollowingsPosts(req.body);
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch user related posts
  async fetchUserRelatedPosts(req, res, next) {
    try {
      console.log(">>>>>>>");
      const handleUn = req.params.handleUn;
      // const client = await getAerospikeClient();
      if (!handleUn) {
        throw createError.BadRequest("User handle name is not present");
      } else {
        const data = await userProfilePosts(req.params.handleUn, req.query);
        return res.status(200).json({ posts: data });
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch all trending key words
  async fetchTrendingWords(req, res, next) {
    try {
      const data = await socialTreandingWords();
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  async trendingCoins(req, res, next) {
    try {
      const data = await socialTreandingCoinNames();

      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch trending post
  async fetchTrendingPosts(req, res, next) {
    try {
      const client = await getAerospikeClient();
      const term = `#${req.query.key}`;
      const result = await handleFetchTrendingPosts(term);

      console.log("RESULTS::::::::" + result);
      return res.status(200).json(result);
    } catch (error) {
      next(error);
    }
  }

  async fetchTrendingCoinPosts(req, res, next) {
    try {
      const term = `${req.query.key}`;
      const result = await handleFetchTrendingCoinPost(term);
      return res.status(200).json(result);
    } catch (error) {
      next(error);
    }
  }

  // *** Donate nft to the user
  /*
  async donateNft(req, res, next) {
    try {
      const client = await getAerospikeClient();

      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in the parameter");
      } else {
        const id = req.params.id;
        const post_meta_key = new Aerospike.Key(
          process.env.CLUSTER_NAME,
          process.env.SET_POSTS_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 {
          let result = await client.operate(map_key, map_ops);
          client.exists(post_meta_key, async (err, result) => {
            if (err) {
              throw createError.BadRequest(err.message);
            } else {
              if (!result) {
                throw createError.BadRequest("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_meta_key = new Aerospike.Key(
                  process.env.CLUSTER_NAME,
                  process.env.SET_USER_META,
                  req.query.handleUn
                );

                client.put(earn_key, bins, async (err, result) => {
                  if (err) {
                    throw createError.BadRequest(err.message);
                  } else {
                    let record = await client.get(post_meta_key);
                    if (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) {
                            throw createError.BadRequest(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);
                                console.log(">> Total earning: ", total);
                                const ops = [
                                  Aerospike.operations.write("earn", total),
                                ];
                                const notificationData = {
                                  id: id,
                                  ty: 5,
                                  vi: false,
                                  wo: req.user.handleUn,
                                  ti: Date.now(),
                                  nm: `${req.user.fn} ${req.user.ln}`,
                                  pi: req.user.p_i,
                                  cat: 1,
                                  amount: req.query.amount,
                                  postId: id,
                                };
                                await sendNotificationMessage(
                                  "post_notification",
                                  notificationData
                                );
                                return res.status(200).json({
                                  msg: "Successfully donated",
                                  notificationData,
                                });
                              } catch (error) {
                                throw createError.BadRequest(error.message);
                              }
                            } else {
                              console.log(
                                "This part - 2 *****************************************************"
                              );
                              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.operate(
                                  user_meta_key,
                                  ops
                                );
                                try {
                                  const notificationData = {
                                    id: id,
                                    ty: 5,
                                    vi: false,
                                    wo: req.user.handleUn,
                                    ti: Date.now(),
                                    nm: `${req.user.fn} ${req.user.ln}`,
                                    pi: req.user.p_i,
                                    cat: 1,
                                    amount: req.query.amount,
                                    postId: id,
                                  };
                                  await sendNotificationMessage(
                                    "post_notification",
                                    notificationData
                                  );
                                  return res.status(200).json({
                                    msg: "Successfully donated",
                                    notificationData,
                                  });
                                } catch (error) {
                                  throw createError.BadRequest(error.message);
                                }
                              } catch (error) {
                                throw createError.BadRequest(error.message);
                              }
                            }
                          }
                        }
                      );
                    }
                    //
                    else {
                      console.log(
                        "This part - 3 *****************************************************"
                      );
                      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.operate(user_meta_key, ops);
                        try {
                          return res.status(200).json({ msg: "Success" });
                        } catch (error) {
                          throw createError.BadRequest(error.message);
                        }
                      } catch (error) {
                        throw createError.BadRequest(error.message);
                      }
                    }
                  }
                });
              }
            }
          });
        } catch (error) {
          return res.status(400).json({ msg: error.message });
        }
      }
    } catch (error) {
      next(error);
    }
  }
  */

  // *** Fetch donation history
  async fetchDonationHistory(req, res, next) {
    try {
      const client = await getAerospikeClient();
      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await socialDonationHistory(req.params.id);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch single donation details
  async fetchSingleDonationDetails(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.Conflict("Post id is not present in parameter");
      } else {
        const data = await fetchDonationDetails(req.params.id);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Create and save nft post
  async createNft(req, res, next) {
    try {
      console.log(req.body);
    } catch (error) {
      next(error);
    }
  }

  // *** Share social post
  async sharePost(req, res, next) {
    const client = await getAerospikeClient();
    try {
      const data = await socialSharePost(req.params.id, req.body, req.user);
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Update post share privacy settings
  async sharePostPrivacy(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Post id is not present in params");
      } else {
        const data = await socialSharePostPrivacy(req.params.id, req.body);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Update post comment privacy settings
  async commentPostPrivacy(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Post id is not present in params");
      } else {
        const data = await socialCommentPostPrivacy(req.params.id, req.body);
        return res.status(200).json(data);
      }
    } catch (error) {
      next(error);
    }
  }

  async emojiERemoveLikePost(req, res, next) {
    try {
      const data = await SocialEmojiRemoveLike(
        req.user.handleUn,
        req.params.id
      );
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch all users who like the post
  async fetchLikedUsers(req, res, next) {
    if (!req.params.id) {
      return res.status(400).json({ msg: "Invalid request" });
    } else {
      const id = req.params.id;
      const type = req.query.type;
      const page = req.query.page;
      const result = await handleFetchLikedUsers(id, type, page);
      return res.status(200).json(result);
      /*
	  const client = await getAerospikeClient();
      let query = client.query(
        process.env.CLUSTER_NAME,
        process.env.SET_POSTS_META
      );
      const tempBin = "ExpVar"; // this bin is to hold expression read operation output
      // query.select("likes", "heart", "haha", "party", "dislike"); //select single bin
      query.where(Aerospike.filter.equal("id", req.params.id));
      const stream = query.foreach();
      var arr = [];
      var temp = [];
      var users = [];

      stream.on("data", function (record) {
        if (req.query.type === "all") {
          arr = [
            ...record.bins.likes,
            ...record.bins.haha,
            ...record.bins.angry,
            ...record.bins.dislikes,
          ];
        }
        // Only likes
        else if (req.query.type === "likes") {
          arr = record.bins.likes;
          console.log("Likes ", arr);
        }
        // Only heart
        if (req.query.type === "heart") {
          arr = record.bins.heart;
          console.log("Heart ", arr);
        }
        // Only party
        else if (req.query.type === "angry") {
          arr = record.bins.angry;
        }
        // only haha
        else if (req.query.type === "haha") {
          arr = record.bins.haha;
        }
        // only dislikes
        else if (req.query.type === "dislikes") {
          arr = record.bins.dislikes;
        }

        for (let i = 0; i < arr.length; i++) {
          temp.push({
            key: new Aerospike.Key(
              process.env.CLUSTER_NAME,
              process.env.SET_USERS,
              arr[i]
            ),
            type: batchType.BATCH_READ,
            readAllBins: false,
            bins: [
              "handleUn",
              "fn",
              "ln",
              "p_i",
              "flwr_c",
              "flw_c",
              "p_bio",
              "city",
              "country",
              "badges",
              "activity_status",
              "status_privacy",
            ],
          });
        }
      });

      stream.on("end", async function (record) {
        client.batchRead(temp, async (err, results) => {
          users = results;
          var page = req.query.page || 1;
          var limit = 5;
          var start = (page - 1) * limit;
          var end = page * limit;

          users = users.splice(start, end);
          return res.status(200).json(users);
        });
      });
	  */
    }
  }

  // **** Search post
  async searchPost(req, res, next) {
    const result = await handleSearchPost(req.query);
    return res.status(200).json(result);
    /*const exp = Aerospike.exp;
    const client = await getAerospikeClient();
    let query = client.query(process.env.CLUSTER_NAME, process.env.SET_POSTS);
    const sortType = req.query.sortType || "recent";
    const page = req.query.page || 1;
    const limit = req.query.limit || 10;

    const tempBin = "ExpVar"; // this bin is to hold expression read operation output
    const input_query = req.query.search;
    const search_query = req.query.search.slice(0, 2);
    //query.where(Aerospike.filter.equal("f_t", search_query));
    const queryPolicy = new Aerospike.QueryPolicy({});
    queryPolicy.filterExpression = exp.cmpRegex(
      Aerospike.regex.ICASE | Aerospike.regex.NEWLINE, // Case-insensitive, multiline match
      input_query, // Search for input_query anywhere in the content
      exp.binStr("content") // The bin to apply the regex on
    );
    var arr = [];

    const stream = query.foreach(queryPolicy);
    stream.on("data", function (record) {
      arr.push(record.bins);
    });
    stream.on("end", async function (posts) {
      return res.status(200).json({ posts: arr });
      if (sortType === "recent") {
        arr = arr.sort((a, b) => b.id - a.id);
      } else {
        arr = arr.sort((a, b) => b.l_c - a.l_c);
      }
      var start = (page - 1) * limit;
      var end = page * limit;
      arr = arr.slice(start, end);
      //resolve({ block: arr });
      return res.status(200).json({ posts: arr });
    });*/
  }

  // Repost post
  /*
  async repostPost(req, res, next) {
    const post_id = now.micro();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const client = await getAerospikeClient();
      const post_key = new Aerospike.Key(
        process.env.CLUSTER_NAME,
        process.env.SET_POSTS,
        post_id.toString()
      );
      const post_meta_key = new Aerospike.Key(
        process.env.CLUSTER_NAME,
        process.env.SET_POSTS_META,
        post_id.toString()
      );
      const original_post_key = new Aerospike.Key(
        process.env.CLUSTER_NAME,
        process.env.SET_POSTS,
        req.params.id
      );

      const original_post_meta_key = new Aerospike.Key(
        process.env.CLUSTER_NAME,
        process.env.SET_POSTS_META,
        req.params.id
      );

      client
        .exists(original_post_key)
        .then(async (data) => {
          const postData = await client.get(original_post_key);
          console.log(postData.bins);
          const bins = {
            id: post_id,
            o_p_id: postData.bins.id,
            content: postData.bins.content,
            image: postData.bins.image || "",
            gif: postData.bins.gif || "",
            l_c: 0,
            d_c: 0,
            book: [],
            pinned: 0,
            u_id: postData.bins.u_id,
            u_fn: postData.bins.u_fn,
            u_ln: postData.bins.u_ln,
            u_dun: postData.bins.u_dun,
            u_img: postData.bins.u_img,
            hide: [],
            s_c: 0,
            c_t: postData.bins.c_t,
            u_t: postData.bins.u_t,
            postOf: postData.bins.postOf,
            c_c: 0,
            is_share: 1,
            is_poll: false,
            share: {
              u_id: req.user.u_id.toString(), // User id
              u_fn: req.user.fn, // Post user first name
              u_ln: req.user.ln, // Posted user last name
              u_dun: req.user.handleUn, // Post user display username
              u_img: req.user.p_i, // Post user profile image
              content: req.body.content,
            },
          };
          const post_meta_bins = {
            id: post_id,
            likes: [],
            dislikes: [],
            spam: [],
            share: [],
          };
          await client.put(post_meta_key, post_meta_bins);
          // console.log(post_bins);
          await client.put(post_key, bins);
          const user_key = new Aerospike.Key(
            process.env.CLUSTER_NAME,
            process.env.SET_USER_META,
            req.user.handleUn
          );
          const user_ops = [
            Aerospike.lists.append(process.env.SET_POSTS, post_id),
          ];
          client.operate(user_key, user_ops, (err, result) => {
            if (err) {
              return res.status(400).json({ msg: err.message });
            } else {
              try {
                const ops = [Aerospike.operations.incr("share_c", 1)];
                client.operate(original_post_key, ops, async (err, result) => {
                  if (err) {
                    return res.status(400).json({ msg: err.message });
                  } else {
                    // ***** ADD ***** //
                    const ops = [Aerospike.lists.append("share", post_id)];
                    let result = await client.operate(
                      original_post_meta_key,
                      ops
                    );
                    return res
                      .status(200)
                      .json({ msg: "Successfully share this post" });
                  }
                });
              } catch (error) {
                return res.status(400).json({ msg: error.message });
              }
            }
          });
        })
        .catch((err) => {
          return res.status(401).json({ msg: err.message });
        });
    }
  }
  */

  // *** fetch post for creating NFT
  async fetchPostToCreatNft(req, res, next) {
    const id = req.params.id;
    console.log("id of post -", id);
    if (!id) {
      return res.status(400).json({ msg: "Invalid request" });
    } else {
      const data = await socialPostToNft(req.params.id);
      return res.status(200).json(data);
    }
  }

  // *** Fetch full post
  async fetchFullPost(req, res, next) {
    console.log("....");
    const data = await socialFetchFullPost(req.params.id);
    return res.status(200).json(data);
  }

  async fetchFullPostWithComment(req, res, next) {
    try {
      const sortedBy = req.query.sortedBy || "pop";
      const page = req.query.page || 1;
      const limit = req.query.limit || 5;

      const data = await fetchSocialPostWithComment(
        req.user.handleUn,
        req.params.id,
        page,
        limit,
        sortedBy
      );

      return res.status(200).json(data);
    } catch (err) {
      next(err);
    }
  }

  /***
   * @SOCIAL_POST_COMMENT
   */
  async createComment(req, res, next) {
    if (!req.params.id) {
      return res.status(400).json({ msg: "Invalid request" });
    } else {
      console.log("createPostComment:", req.body);
      const data = await createPostComment(
        req.params.id,
        req.user,
        req.body,
        req.file,
        req.query
      );
      return res.status(200).json(data);
    }
  }

  // *** Fetch single comment
  async fetchsingleComment(req, res, next) {
    try {
      const data = await fetchSocialComments(
        req.params.id,
        req.user.handleUn,
        req.query.sortedBy,
        req.query.page,
        req.query.limit
      );
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Fetch user comment
  async fetchMyComments(req, res, next) {
    try {
      const data = await fetchSocialMyComments(
        req.params.id,
        req.user.handleUn,
        req.query.sortedBy,
        req.query.page,
        req.query.limit
      );
      return res.status(200).json(data);
    } catch (error) {
      next(error);
    }
  }

  // *** Pinned comment
  async pinnedComment(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialPinnedComment(req.params.id, req.user);
      return res.status(200).json(data);
    }
  }

  // *** Delete comment
  async deleteComment(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialDeleteComment(req.params.id);
      return res.status(200).json(data);
    }
  }

  // *** Edit comment
  async editComment(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialEditComment(req.params.id, req.body);
      return res.status(200).json(data);
    }
  }

  // *** Comment dilike
  async commentDislike(req, res, next) {}

  // *** Comment haha
  async commentHaha(req, res, next) {}

  // *** Comment Angry
  async commentAngry(req, res, next) {}

  // *** Spam comment
  async spamComment(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      console.log(req.params.id);
      const data = await socialSpamComment(req.params.id, req.user.handleUn);
      console.log(data);
      return res.status(200).json(data);
    }
  }

  // *** Comment Like
  async commentLike(req, res, next) {
    if (!req.params.id || !req.params.username || !req.params.type) {
      return res.status(400).json({ msg: "Invalid request" });
    } else {
      const data = await socialLikeComment(
        req.params.id,
        req.params.username,
        req.params.type,
        req.user
      );
      console.log(data);
      return res.status(200).json(data);
    }
  }

  // *** Comment like remove
  async commentLikeRemove(req, res, next) {
    if (!req.params.id) {
      return res.status(400).json({ msg: "Invalid parameter" });
    } else {
      const data = await socialRemoveLikeComment(
        req.params.id,
        req.user.handleUn
      );
      return res.status(200).json(data);
    }
  }

  /**
   * @POST_COMMENT_REPLY
   */

  // *** create comment reply
  async createReply(req, res, data) {
    if (!req.params.id) {
      return res.status(400).json({ msg: "Invalid request" });
    } else {
      const data = await socialCreatReply(req.params.id, req.body, req.user);
      return res.status(200).json(data);
    }
  }

  // *** Reply inside reply
  async createReplyInsideReply(req, res, data) {
    if (!req.params.id) {
      return res.status(400).json({ msg: "Invalid request" });
    } else {
      const data = await socialCreatReplyInsideReply(
        req.params.id,
        req.body,
        req.user
      );
      return res.status(200).json(data);
    }
  }

  // *** Fetch comment reply
  async fetchReplies(req, res, next) {
    console.log(">>>>");
    const client = await getAerospikeClient();
    const batchType = Aerospike.batchType;
    if (!req.params.id) {
      return res.status(400).json({ msg: "Invalid" });
    } else {
      const data = await socialFetchCommentReply(
        req.params.id,
        req.query.page,
        req.query.limit
      );
      return res.status(200).json(data);
    }
  }

  // **** Hide comment replies
  async hideReply(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialHideReply(req.params.id, req.user.handleUn);
      return res.status(200).json(data);
    }
  }

  // *** Spam reply
  /**
   *
   * @SPLIT_THIS_CODE
   */
  async spamReply(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const result = await handleSpamReply(req.params.id, req.user);
      return res.status(200).json(result);
      /*
      const post_comment_reply_key = new Aerospike.Key(
        process.env.CLUSTER_NAME,
        process.env.SET_POST_REPLY,
        req.params.id
      );

      const post_comment_reply_meta_key = new Aerospike.Key(
        process.env.CLUSTER_NAME,
        process.env.SET_POST_REPLY_META,
        req.params.id
      );

      let query = client.query(
        process.env.CLUSTER_NAME,
        process.env.SET_POST_REPLY_META
      );
      const tempBin1 = "ExpVar";
      query.where(Aerospike.filter.equal("id", req.params.id));
      const stream = query.foreach();
      var data;

      stream.on("data", function (record) {
        data = record.bins;
      });
      stream.on("end", function (record) {
        if (data.spam.includes(req.user.handleUn)) {
          const ops = [
            Aerospike.lists.removeByValue("spam", req.user.handleUn),
          ];
          client.operate(post_comment_reply_meta_key, ops, (err, result) => {
            if (err) {
              return res.status(400).json({ msg: err.message });
            } else {
              const ops = [Aerospike.operations.incr("s_c", -1)];
              client.operate(post_comment_reply_key, ops, (err, result) => {
                if (err) {
                  return res.status(400).json({ msg: err.message });
                } else {
                  return res.status(200).json({ msg: "Reply spam removed" });
                }
              });
            }
          });
        } else {
          const ops = [Aerospike.lists.append("spam", req.user.handleUn)];
          client.operate(post_comment_reply_meta_key, ops, (err, result) => {
            if (err) {
              return res.status(400).json({ msg: err.message });
            } else {
              const ops = [Aerospike.operations.incr("s_c", 1)];
              client.operate(post_comment_reply_key, ops, (err, result) => {
                if (err) {
                  return res.status(400).json({ msg: err.message });
                } else {
                  return res.status(200).json({ msg: "Reply spam" });
                }
              });
            }
          });
        }
      });
	  */
    }
  }

  // *** Delete reply
  async deleteReply(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialDeleteReply(req.params.id);
      return res.status(200).json(data);
    }
  }

  // reply dislike
  async dislikeReply(req, res, next) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialDislikeReply(req.params.id, req.user);
      console.log("Result: ", data);
      return res.status(200).json(data);
    }
  }

  // Like reply
  async likeReply(req, res) {
    const client = await getAerospikeClient();
    if (!req.params.id) {
      return res.status(401).json({ msg: "Invalid request" });
    } else {
      const data = await socialLikeReply(req.params.id, req.user);
      console.log("Result: ", data);
      return res.status(200).json(data);
    }
  }

  async getActivity(req, res, next) {
    try {
      const page = req.query.page || 1;
      const limit = req.query.limit || 10;
      const result = await fetchActivityList(page, limit);
      return res.status(200).json(result);
    } catch (error) {
      next(error.message);
    }
  }

  async uploadNFT(req, res, next) {
    // console.log(req.file);
    try {
      const result = await handleUploadNFT(req.body, req.file, req.user);
      return res.status(200).json({ msg: "Updated" });
    } catch (error) {
      next(error.message);
    }
  }

  async fetchNFTs(req, res, next) {
    // console.log(req.file);
    try {
      const result = await handleFetchNFTs(req.body, req.file, req.user);
      return res.status(200).json(result);
    } catch (error) {
      next(error.message);
    }
  }

  async likeNFT(req, res, next) {
    // console.log(req.file);
    try {
      const result = await handleLikeNFT(req.params.id, req.user.handleUn);
      return res.status(200).json(result);
    } catch (error) {
      next(error.message);
    }
  }

  async commentNft(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request ID is not present");
      } else {
        const result = await handleCreateNFTComment(
          req.params.id,
          req.body,
          req.user
        );
        return res.status(200).json(result);
      }
    } catch (err) {
      next(err.message);
    }
  }

  async commentPinNft(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request ID is not present");
      } else {
        const result = await handleNFTCommentPin(req.params.id);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async getNftCommants(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request ID is not present");
      } else {
        const page = req.query.page || 1;
        const limit = req.query.limit || 10;
        const result = await handleFetchNFTComments(req.params.id, page, limit);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async commentEditNFT(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await updateNFTComment(req.params.id, req.body);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async commentDeleteNFT(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await deleteNFTComment(req.params.id, req.body);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async commentLikeNFT(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await likeNFTComment(req.params.id, req.user.handleUn);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async nftCommentReply(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await createNFTReply(req.params.id, req.body, req.user);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async nftCommentReplyLike(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await likeNFTReply(req.params.id, req.user.handleUn);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async nftCommentReplyEdit(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await editNFTReply(req.params.id, req.body);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async getReplies(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const page = req.query.page || 1;
        const limit = req.query.limit || 10;
        const result = await handleGetReplies(req.params.id, page, limit);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async nftCommentReplyDelete(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Request params is not present");
      } else {
        const result = await handleDeleteReply(req.params.id);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async reportPost(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("Event id is not defined");
      } else {
        const result = await handleReportPost(
          req.params.id,
          req.user.handleUn,
          req.body
        );
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error);
    }
  }

  async createNewPoll(req, res, next) {
    try {
      const data = await handleCreateNewPoll(req.user, req.body);
      // console.log("BODY:", req.body);
      return res.status(201).json(data);
    } catch (error) {
      next(error);
    }
  }

  async votePoll(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("ID is note defined");
      } else {
        const result = await handlePollVote(req.params.id, req.body, req.user);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Spam inner reply
  async spamInnerReply(req, res, next) {
    try {
      if (!req.params.id) {
        return res.status(401).json({ msg: "Invalid request" });
      } else {
        const result = await handleSpamInnerReply(req.params.id, req.user);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error);
    }
  }

  // *** Like inner reply
  async likeInnerReply(req, res, next) {
    try {
      const id = req.params.id;
      const user = req.user;
      const result = await handleLikeInnerReply(id, user);
      return res.status(200).json(result);
    } catch (error) {
      next(error);
    }
  }

  // *** Dislike inner reply
  async dislikeInnerReply(req, res, next) {
    try {
      const id = req.params.id;
      const user = req.user;
      const result = await handleDislikeInnerReply(id, user);
      return res.status(200).json(result);
    } catch (error) {
      next(error);
    }
  }

  async addPostLike(req, res, next) {
    try {
      const result = await handleAddPostLike(
        req.params.id,
        req.body.value,
        req.user
      );
      return res.status(200).json(result);
    } catch (error) {
      next(error.message);
    }
  }

  async removePostLike(req, res, next) {
    try {
      const result = await handleRemovePostLike(
        req.params.id,
        req.user.handleUn
      );
      return res.status(200).json(result);
    } catch (error) {
      next(error.message);
    }
  }

  async handleFetchBlockFeedPosts(req, res, next) {
    try {
      const page = req.query.page || 1;
      const limit = req.query.limit || 5;
      const result = await fetchBlockFeedPosts(page, limit, req.user);
      return res.status(200).json(result);
    } catch (error) {
      next(error.message);
    }
  }

  async getvotersLists(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("ID is not defined");
      } else {
        const page = req.query.page || 1;
        const limit = req.query.limit || 5;
        const type = req.query.type || "opt1";
        const id = req.params.id;
        const result = await handleGetVoterLists(id, page, limit, type);
        return res.status(200).json(result);
      }
    } catch (error) {
      next(error.message);
    }
  }

  async getMentionPosts(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("User id is not present");
      } else {
        const page = req.query.page || 1;
        const limit = req.query.limit || 10;
        const result = await handleGetMentionPosts(req.params.id, page, limit);
        return res.status(200).json(result);
      }
    } catch (error) {
      throw createError.BadRequest(error.message);
    }
  }

  async getCoinPrice(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("User id is not present");
      } else {
        const result = await handleGetCoinPrice(req.params.id);
        res.status(200).json(obj);
      }
    } catch (error) {
      throw createError.BadRequest(error.message);
    }
  }

  async getAnalytics(req, res, next) {
    try {
      if (!req.params.id) {
        throw createError.BadRequest("User id is not present");
      } else {
        const result = await handleGetAnalytics(req.params.id);
        res.status(200).json(result);
      }
    } catch (error) {
      throw createError.BadRequest(error.message);
    }
  }

  async donateNFT(req, res, next) {
    try {
      const user = req.user;
      const query = req.query;
      const id = req.params.id;
      const result = await handleDonateNFT(user, query, id);
      return res.status(200).json(result);
    } catch (error) {
      throw createError.BadRequest(error.message);
    }
  }
}

module.exports = new PostController();
Leave a Comment