Commit c22fd7fd authored by velayat's avatar velayat
Browse files

soheib cant push his changes so i did it for him

parent c670bdce
import { Body, Controller, Get, Post } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) { }
}
// @Get('get-followers')
// async getFollowers() {
// return await this.appService.getFollowers();
// }
// @Post()
// async getUserScore(@Body() getUserScoreDto: GetUserScore) {
// return await this.appService.calculateUserScore(getUserScoreDto.username);
// }
// @Get('calculate-result')
// async calculateResult() {
// return await this.appService.getResults();
// }
// @Get('get-results')
// async getResults() {
// return await this.appService.getFinalResults();
// }
// @Post('search')
// async getUserResults(@Body('username') username: string) {
// return await this.appService.getUserResult(username);
// }
// @Get('shuffle')
// async shuffle() {
// return await this.appService.getShuffleData();
// }
// @Get('add-lottory-result')
// async addResultDb() {
// return await this.appService.addResultsToDB();
// }
import { Body, Controller, Get, Post } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) { }
}
// @Get('get-followers')
// async getFollowers() {
// return await this.appService.getFollowers();
// }
// @Post()
// async getUserScore(@Body() getUserScoreDto: GetUserScore) {
// return await this.appService.calculateUserScore(getUserScoreDto.username);
// }
// @Get('calculate-result')
// async calculateResult() {
// return await this.appService.getResults();
// }
// @Get('get-results')
// async getResults() {
// return await this.appService.getFinalResults();
// }
// @Post('search')
// async getUserResults(@Body('username') username: string) {
// return await this.appService.getUserResult(username);
// }
// @Get('shuffle')
// async shuffle() {
// return await this.appService.getShuffleData();
// }
// @Get('add-lottory-result')
// async addResultDb() {
// return await this.appService.addResultsToDB();
// }
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { InstagramModule } from './instagram/instagram.module';
import { LotteryModule } from './lottery/lottery.module';
import { InstagramService } from './instagram/instagram.service';
import { UserSchema } from './instagram/models/user.schema'
import { FollowerSchema } from './instagram/models/follower.schema'
import { LikeSchema } from './instagram/models/like.schema'
import { CommentSchema } from './instagram/models/comment.schema'
import { LottoryResultSchema } from './instagram/models/LottoryResult.schema'
@Module({
imports: [
MongooseModule.forRoot(
'mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256&connectTimeoutMS=10000&readPreference=primary&serverSelectionTimeoutMS=5000&appname=MongoDB%20Compass&directConnection=true&ssl=false',
),
MongooseModule.forFeature([
{ name: 'User', schema: UserSchema },
]),
MongooseModule.forFeature([
{ name: 'Follower', schema: FollowerSchema },
]),
MongooseModule.forFeature([
{ name: 'Like', schema: LikeSchema },
]),
MongooseModule.forFeature([
{ name: 'Comment', schema: CommentSchema },
]),
MongooseModule.forFeature([
{ name: 'LottryResult', schema: LottoryResultSchema },
]),
InstagramModule,
LotteryModule,
],
controllers: [AppController],
providers: [AppService, InstagramService],
})
export class AppModule { }
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { InstagramModule } from './instagram/instagram.module';
import { LotteryModule } from './lottery/lottery.module';
import { InstagramService } from './instagram/instagram.service';
import { UserSchema } from './instagram/models/user.schema'
import { FollowerSchema } from './instagram/models/follower.schema'
import { LikeSchema } from './instagram/models/like.schema'
import { CommentSchema } from './instagram/models/comment.schema'
import { LottoryResultSchema } from './instagram/models/LottoryResult.schema'
@Module({
imports: [
MongooseModule.forRoot(
'mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256&connectTimeoutMS=10000&readPreference=primary&serverSelectionTimeoutMS=5000&appname=MongoDB%20Compass&directConnection=true&ssl=false',
),
MongooseModule.forFeature([
{ name: 'User', schema: UserSchema },
]),
MongooseModule.forFeature([
{ name: 'Follower', schema: FollowerSchema },
]),
MongooseModule.forFeature([
{ name: 'Like', schema: LikeSchema },
]),
MongooseModule.forFeature([
{ name: 'Comment', schema: CommentSchema },
]),
MongooseModule.forFeature([
{ name: 'LottryResult', schema: LottoryResultSchema },
]),
InstagramModule,
LotteryModule,
],
controllers: [AppController],
providers: [AppService, InstagramService],
})
export class AppModule { }
import {
HttpException,
Injectable,
OnApplicationBootstrap,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import * as _ from 'lodash';
import { CommentDocument } from './instagram/models/comment.schema';
import { LottoryResultDocument } from './instagram/models/LottoryResult.schema';
import { FollowerDocument } from './instagram/models/follower.schema';
import { LikeDocument } from './instagram/models/like.schema';
import { UserDocument } from './instagram/models/user.schema';
@Injectable()
export class AppService {
constructor() { }
}
// private async login(username, password) {
// try {
// const client = new Instagram({ username, password });
// await client.login();
// console.log(`user logged in. details :\n
// username: ${username},
// password: ${password},
// `);
// return client;
// } catch (err) {
// console.log(err);
// }
// }
// async getFollowers(postShortCode = 'CRWNkkchs2x') {
// try {
// const username = 'shahriarvelayat';
// const password = 'shve8864@@';
// const client = new Instagram({ username, password });
// await client.login();
// console.log('user logged in...');
// let hasNextPage = true;
// let requestCount = 0;
// let followersCount = 0;
// let cursor = '';
// const reqList = await this.requestModel.find({
// $and: [{ createdAt: -1 }, { type: 'follower' }],
// });
// console.log('Request History:', reqList.length);
// if (reqList.length != 0) {
// const nextCursor = await this.getFollowersNextCursor(
// client,
// reqList[0].cursor,
// );
// cursor = nextCursor;
// }
// while (hasNextPage) {
// console.log('seted cursor', cursor);
// console.log('sending request....');
// const collectedFollower = await this.sendFollowerRequest(
// client,
// cursor,
// );
// console.log('request sended. request count:', requestCount);
// requestCount++;
// await this.requestModel.create({
// _id: new Types.ObjectId(),
// cursor: cursor,
// type: 'follower',
// });
// cursor = collectedFollower.cursor;
// hasNextPage = collectedFollower.hasNextPage;
// console.log('==================================');
// console.log('nextCursor:', cursor);
// console.log('has a next page', hasNextPage);
// for await (const follower of collectedFollower.followers) {
// const check = await this.followerModel.findOne({
// $and: [
// { username: follower.username },
// { user_id: follower.user_id },
// ],
// });
// if (!check) {
// await this.followerModel.create({
// _id: new Types.ObjectId(),
// username: follower.username,
// user_id: follower.user_id,
// full_name: follower.full_name,
// bussines_username: 'azadi.gold',
// follower_object: follower.follower_obejct,
// follow_date: this.getFollowerDateOfFollow(follower.username),
// });
// followersCount += 1;
// } else {
// console.log(follower.username, ' exist');
// }
// }
// console.log(followersCount, 'follower imported');
// console.log(
// '================ end of this Request Proccess ==================',
// );
// }
// return { totalAdded: followersCount };
// } catch (err) {
// console.log(err);
// }
// }
// async getFollowersNextCursor(client, cursor: string) {
// const azadiGoldUser = await client.getUserByUsername({
// username: 'azadi.gold',
// });
// const followers = await client.getFollowers({
// userId: azadiGoldUser.id,
// after: cursor,
// });
// return followers.page_info.end_cursor;
// }
// async sendFollowerRequest(client, cursor) {
// try {
// const Infollowers: IFollower[] = new Array<IFollower>();
// const azadiGoldUser = await client.getUserByUsername({
// username: 'azadi.gold',
// });
// const followers = await client.getFollowers({
// userId: azadiGoldUser.id,
// after: cursor,
// });
// await this.delay(_.random(5000, 10000));
// console.log('=============incoming followers=============', followers);
// for (const user of followers.data) {
// Infollowers.push({
// user_id: user.id,
// username: user.username,
// full_name: user.full_name,
// follower_obejct: user,
// });
// }
// return {
// followers: Infollowers,
// cursor: followers.page_info.end_cursor,
// hasNextPage: followers.page_info.has_next_page,
// };
// } catch (err) {
// console.log(err);
// throw new HttpException(err.message, 500);
// }
// }
// getFollowerDateOfFollow(username: string) {
// let follower_objectResult: any = 0;
// FollowerPrivateData.relationships_followers.forEach((follower_object) => {
// if (
// follower_object.string_list_data[0]['value'].toString() ===
// username.toString()
// ) {
// follower_objectResult =
// follower_object.string_list_data[0]['timestamp'];
// }
// });
// if (follower_objectResult === 0) {
// console.log(username, 'is not in list');
// follower_objectResult = Date.now() / 1000;
// } else {
// console.log(username, 'is in list');
// }
// return follower_objectResult;
// }
// async delay(ms) {
// // return await for better async stack trace support in case of errors.
// console.log('delay time:', ms);
// return await new Promise((resolve) => setTimeout(resolve, ms));
// }
// async calculateUserScore(owner_username: string) {
// const foundUserComments = await this.commentModel
// .find({ owner_username })
// .sort({ createdAt: 1 });
// const isUserFollowPage = await this.checkUserFollowingStatus(
// owner_username,
// );
// let ownerUserFollowStatus: boolean;
// if (isUserFollowPage) {
// ownerUserFollowStatus = true;
// } else {
// ownerUserFollowStatus = false;
// }
// const UseCleanComment = new CleanedComments();
// UseCleanComment.mentions = new Array<MentionDocument>();
// UseCleanComment.owner_username = owner_username;
// foundUserComments.forEach((comment) => {
// const rawComment = comment.text;
// const commentTextArray = rawComment.split(' ');
// commentTextArray.forEach((commentSubStr) => {
// let check = false;
// if (commentSubStr.includes('@')) {
// if (UseCleanComment.mentions.length != 0) {
// UseCleanComment.mentions.forEach((mention) => {
// if (
// commentSubStr == mention.mentioned_username ||
// commentSubStr == owner_username
// ) {
// check = true;
// }
// });
// } else {
// if (commentSubStr == owner_username) {
// check = true;
// }
// }
// if (check == false) {
// UseCleanComment.mentions.push({
// mentioned_username: commentSubStr,
// date: comment.date,
// });
// }
// }
// });
// });
// const allUserMentions = new Array<UserAllMention>();
// for await (const mentionedUser of UseCleanComment.mentions) {
// console.log('mentionedUser', mentionedUser);
// const newMentionData = new UserAllMention();
// newMentionData.comment_status = new Array<CommentStatus>();
// const foundAccount = await this.checkUserFollowingStatus(
// mentionedUser.mentioned_username.split('@')[1],
// );
// if (!foundAccount) {
// (newMentionData.mentioned_username = mentionedUser.mentioned_username),
// (newMentionData.page_follow_date = null),
// (newMentionData.comment_date = mentionedUser.date),
// newMentionData.comment_status.push(CommentStatus.notFollower);
// allUserMentions.push(newMentionData);
// } else {
// newMentionData.mentioned_username = foundAccount.username;
// newMentionData.mentioned_user_id = foundAccount.user_id;
// newMentionData.page_follow_date = foundAccount.follow_date;
// newMentionData.comment_date = mentionedUser.date;
// const checkUserFollowedPageBefore =
// await this.checkUserFollowedPageBefore(
// newMentionData.comment_date,
// newMentionData.page_follow_date,
// );
// console.log('++++++++++++++++++', checkUserFollowedPageBefore);
// if (checkUserFollowedPageBefore === true) {
// console.log('followed before');
// newMentionData.comment_status.push(CommentStatus.isAFollowerBefore);
// }
// console.log('*************', newMentionData.mentioned_username);
// const checkUserMentionedBefore = await this.checkUserMentionedBefore(
// newMentionData.mentioned_username,
// newMentionData.comment_date,
// );
// if (
// checkUserMentionedBefore == true &&
// !newMentionData.comment_status
// ) {
// newMentionData.comment_status.push(CommentStatus.isMentionedBefore);
// }
// if (
// checkUserFollowedPageBefore == false &&
// checkUserMentionedBefore == false
// ) {
// newMentionData.comment_status.push(CommentStatus.isValid);
// }
// allUserMentions.push(newMentionData);
// }
// }
// return {
// mentions: allUserMentions,
// };
// }
// async getResults() {
// const foundUsernames = await this.commentModel.distinct('owner_username');
// // console.log('total users for ranking:', foundUsernames.length);
// for await (const username of foundUsernames) {
// const mentions = await this.calculateUserScore(username);
// console.log('--------------', mentions.mentions);
// let valid_mentions = 0;
// let followed_before = 0;
// let mentions_before = 0;
// let pending_mentions = 0;
// const valid_users = new Array<string>();
// const mentions_before_users = new Array<string>();
// const followed_before_users = new Array<string>();
// const pending_users = new Array<string>();
// mentions.mentions.forEach((mention) => {
// if (mention.comment_status.includes(CommentStatus.isValid)) {
// valid_mentions++;
// valid_users.push(mention.mentioned_username);
// } else if (
// mention.comment_status.includes(CommentStatus.isMentionedBefore)
// ) {
// mentions_before++;
// mentions_before_users.push(mention.mentioned_username);
// } else if (
// mention.comment_status.includes(CommentStatus.isAFollowerBefore)
// ) {
// followed_before++;
// followed_before_users.push(mention.mentioned_username);
// } else if (mention.comment_status.includes(CommentStatus.notFollower)) {
// pending_mentions++;
// pending_users.push(mention.mentioned_username);
// }
// });
// await this.delay(_.random(500, 1000));
// const foundUser = await this.resultModel.findOne({ username: username });
// if (!foundUser) {
// await this.resultModel.create({
// username: username,
// valid_mentions,
// mentions_before,
// followed_before,
// pending_mentions,
// score: valid_mentions + 1,
// valid_users: valid_users,
// followed_before_users: followed_before_users,
// mentions_before_users: mentions_before_users,
// pending_users: pending_users,
// });
// } else {
// await this.resultModel.updateOne(
// { _id: foundUser._id },
// {
// username: username,
// valid_mentions,
// mentions_before,
// followed_before,
// pending_mentions,
// score: valid_mentions + 1,
// valid_users: valid_users,
// followed_before_users: followed_before_users,
// mentions_before_users: mentions_before_users,
// pending_users: pending_users,
// },
// );
// }
// }
// return 'records updated successfully';
// }
// async checkUserMentionedBefore(username, comment_date) {
// const foundCommentsWithThisMention = await this.commentModel.find({
// text: new RegExp(`@${username}`),
// });
// let isValid = false;
// if (foundCommentsWithThisMention.length != 0) {
// foundCommentsWithThisMention.forEach((comment) => {
// if (comment_date > comment.date) {
// isValid = true;
// }
// });
// }
// return isValid;
// }
// async checkUserFollowingStatus(username: string) {
// const res = await this.followerModel.findOne({ username: username });
// return res;
// }
// async checkUserFollowedPageBefore(
// comment_date: number,
// followed_date: number,
// ) {
// if (comment_date < followed_date) {
// return false;
// } else {
// return true;
// }
// }
// async getFinalResults() {
// const results = await this.resultModel.find().sort({ score: -1 });
// const last_update = await this.resultModel.find().sort({ updatedAt: -1 });
// const last_create = await this.resultModel.find().sort({ createdAt: -1 });
// let date: number;
// if (last_update[0]['updatedAt'] >= last_create[0]['createdAt']) {
// date = last_update[0]['updatedAt'];
// } else {
// date = last_create[0]['createdAt'];
// }
// const finalResult = new Array<ResultResponse>();
// for await (const userRes of results) {
// const response: ResultResponse = new ResultResponse();
// response.users = new Array<any>();
// userRes.pending_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.notFollower,
// });
// });
// userRes.mentions_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isMentionedBefore,
// });
// });
// userRes.followed_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isAFollowerBefore,
// });
// });
// userRes.valid_users.forEach((user) => {
// response.users.push({ userId: user, status: CommentStatus.isValid });
// });
// (response.username = userRes.username),
// (response.valid_mentions = userRes.valid_mentions),
// (response.before_mentions = userRes.mentions_before),
// (response.followed_before_mentions = userRes.followed_before),
// (response.pending_mentions = userRes.pending_mentions),
// (response.score = userRes.score);
// finalResult.push(response);
// }
// return {
// finalResult,
// last_update: date,
// };
// }
// async getUserResult(username: string) {
// username = username.toLowerCase();
// const userRes = await this.resultModel.findOne({ username });
// const userIndexs = await this.lotoryResultModel.find({ username });
// if (!userRes) return 'User not found';
// const response: ResultResponse = new ResultResponse();
// response.users = new Array<any>();
// response.lottory_chances_codes = new Array<string>();
// userRes.pending_users.forEach((user) => {
// response.users.push({ userId: user, status: CommentStatus.notFollower });
// });
// userRes.mentions_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isMentionedBefore,
// });
// });
// userRes.followed_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isAFollowerBefore,
// });
// });
// userRes.valid_users.forEach((user) => {
// response.users.push({ userId: user, status: CommentStatus.isValid });
// });
// (response.username = userRes.username),
// (response.valid_mentions = userRes.valid_mentions),
// (response.before_mentions = userRes.mentions_before),
// (response.followed_before_mentions = userRes.followed_before),
// (response.pending_mentions = userRes.pending_mentions),
// (response.last_update = userRes['updatedAt']),
// (response.score = userRes.score);
// userIndexs.forEach((index) => {
// response.lottory_chances_codes.push(index.index.toString());
// });
// return {
// response,
// };
// }
// shuffle(array) {
// let currentIndex = array.length,
// randomIndex;
// // While there remain elements to shuffle...
// while (0 !== currentIndex) {
// // Pick a remaining element...
// randomIndex = Math.floor(Math.random() * currentIndex);
// currentIndex--;
// // And swap it with the current element.
// [array[currentIndex], array[randomIndex]] = [
// array[randomIndex],
// array[currentIndex],
// ];
// }
// return array;
// }
// async getShuffleData() {
// const comptitionArray = new Array<string>();
// const foundUsernames = await this.resultModel.find();
// console.log(foundUsernames);
// let score = 0;
// for await (const user of foundUsernames) {
// score += user.score;
// for (let index = 0; index < user.score; index++) {
// comptitionArray.push(user.username);
// }
// }
// const res = this.shuffle(comptitionArray);
// console.log('score is', score);
// return res;
// }
// async addResultsToDB() {
// // await this.lotoryResultModel.deleteMany();
// const comptitionArray = new Array<any>();
// const foundUsernames = await this.resultModel
// .find({})
// .sort({});
// let index = 1000;
// for await (const user of foundUsernames) {
// console.log(index)
// for (let u = 0; u < user.valid_users.length; u++) {
// const isChanceExist = await this.lotoryResultModel
// .findOne({
// username: user.username,
// tagged_user: user.valid_users[u],
// })
// .exec();
// if (!isChanceExist)
// comptitionArray.push({
// index,
// username: user.username,
// tagged_user: user.valid_users[u],
// status:"valid"
// });
// index++;
// }
// const isUserChanceExist = await this.lotoryResultModel.findOne({
// username: user.username,
// tagged_user: user.username,
// });
// if (!isUserChanceExist)
// comptitionArray.push({
// index,
// username: user.username,
// tagged_user: user.username,
// status:"valid"
// });
// index++;
// }
// await this.lotoryResultModel.insertMany(comptitionArray);
// return 'successfull';
// }
// export class ResultResponse {
// last_update: Date;
// username: string;
// valid_mentions: number;
// followed_before_mentions: number;
// before_mentions: number;
// pending_mentions: number;
// score: number;
// users?: Array<any>;
// lottory_chances_codes: Array<string>;
// }
import {
HttpException,
Injectable,
OnApplicationBootstrap,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import * as _ from 'lodash';
import { CommentDocument } from './instagram/models/comment.schema';
import { LottoryResultDocument } from './instagram/models/LottoryResult.schema';
import { FollowerDocument } from './instagram/models/follower.schema';
import { LikeDocument } from './instagram/models/like.schema';
import { UserDocument } from './instagram/models/user.schema';
@Injectable()
export class AppService {
constructor() { }
}
// private async login(username, password) {
// try {
// const client = new Instagram({ username, password });
// await client.login();
// console.log(`user logged in. details :\n
// username: ${username},
// password: ${password},
// `);
// return client;
// } catch (err) {
// console.log(err);
// }
// }
// async getFollowers(postShortCode = 'CRWNkkchs2x') {
// try {
// const username = 'shahriarvelayat';
// const password = 'shve8864@@';
// const client = new Instagram({ username, password });
// await client.login();
// console.log('user logged in...');
// let hasNextPage = true;
// let requestCount = 0;
// let followersCount = 0;
// let cursor = '';
// const reqList = await this.requestModel.find({
// $and: [{ createdAt: -1 }, { type: 'follower' }],
// });
// console.log('Request History:', reqList.length);
// if (reqList.length != 0) {
// const nextCursor = await this.getFollowersNextCursor(
// client,
// reqList[0].cursor,
// );
// cursor = nextCursor;
// }
// while (hasNextPage) {
// console.log('seted cursor', cursor);
// console.log('sending request....');
// const collectedFollower = await this.sendFollowerRequest(
// client,
// cursor,
// );
// console.log('request sended. request count:', requestCount);
// requestCount++;
// await this.requestModel.create({
// _id: new Types.ObjectId(),
// cursor: cursor,
// type: 'follower',
// });
// cursor = collectedFollower.cursor;
// hasNextPage = collectedFollower.hasNextPage;
// console.log('==================================');
// console.log('nextCursor:', cursor);
// console.log('has a next page', hasNextPage);
// for await (const follower of collectedFollower.followers) {
// const check = await this.followerModel.findOne({
// $and: [
// { username: follower.username },
// { user_id: follower.user_id },
// ],
// });
// if (!check) {
// await this.followerModel.create({
// _id: new Types.ObjectId(),
// username: follower.username,
// user_id: follower.user_id,
// full_name: follower.full_name,
// bussines_username: 'azadi.gold',
// follower_object: follower.follower_obejct,
// follow_date: this.getFollowerDateOfFollow(follower.username),
// });
// followersCount += 1;
// } else {
// console.log(follower.username, ' exist');
// }
// }
// console.log(followersCount, 'follower imported');
// console.log(
// '================ end of this Request Proccess ==================',
// );
// }
// return { totalAdded: followersCount };
// } catch (err) {
// console.log(err);
// }
// }
// async getFollowersNextCursor(client, cursor: string) {
// const azadiGoldUser = await client.getUserByUsername({
// username: 'azadi.gold',
// });
// const followers = await client.getFollowers({
// userId: azadiGoldUser.id,
// after: cursor,
// });
// return followers.page_info.end_cursor;
// }
// async sendFollowerRequest(client, cursor) {
// try {
// const Infollowers: IFollower[] = new Array<IFollower>();
// const azadiGoldUser = await client.getUserByUsername({
// username: 'azadi.gold',
// });
// const followers = await client.getFollowers({
// userId: azadiGoldUser.id,
// after: cursor,
// });
// await this.delay(_.random(5000, 10000));
// console.log('=============incoming followers=============', followers);
// for (const user of followers.data) {
// Infollowers.push({
// user_id: user.id,
// username: user.username,
// full_name: user.full_name,
// follower_obejct: user,
// });
// }
// return {
// followers: Infollowers,
// cursor: followers.page_info.end_cursor,
// hasNextPage: followers.page_info.has_next_page,
// };
// } catch (err) {
// console.log(err);
// throw new HttpException(err.message, 500);
// }
// }
// getFollowerDateOfFollow(username: string) {
// let follower_objectResult: any = 0;
// FollowerPrivateData.relationships_followers.forEach((follower_object) => {
// if (
// follower_object.string_list_data[0]['value'].toString() ===
// username.toString()
// ) {
// follower_objectResult =
// follower_object.string_list_data[0]['timestamp'];
// }
// });
// if (follower_objectResult === 0) {
// console.log(username, 'is not in list');
// follower_objectResult = Date.now() / 1000;
// } else {
// console.log(username, 'is in list');
// }
// return follower_objectResult;
// }
// async delay(ms) {
// // return await for better async stack trace support in case of errors.
// console.log('delay time:', ms);
// return await new Promise((resolve) => setTimeout(resolve, ms));
// }
// async calculateUserScore(owner_username: string) {
// const foundUserComments = await this.commentModel
// .find({ owner_username })
// .sort({ createdAt: 1 });
// const isUserFollowPage = await this.checkUserFollowingStatus(
// owner_username,
// );
// let ownerUserFollowStatus: boolean;
// if (isUserFollowPage) {
// ownerUserFollowStatus = true;
// } else {
// ownerUserFollowStatus = false;
// }
// const UseCleanComment = new CleanedComments();
// UseCleanComment.mentions = new Array<MentionDocument>();
// UseCleanComment.owner_username = owner_username;
// foundUserComments.forEach((comment) => {
// const rawComment = comment.text;
// const commentTextArray = rawComment.split(' ');
// commentTextArray.forEach((commentSubStr) => {
// let check = false;
// if (commentSubStr.includes('@')) {
// if (UseCleanComment.mentions.length != 0) {
// UseCleanComment.mentions.forEach((mention) => {
// if (
// commentSubStr == mention.mentioned_username ||
// commentSubStr == owner_username
// ) {
// check = true;
// }
// });
// } else {
// if (commentSubStr == owner_username) {
// check = true;
// }
// }
// if (check == false) {
// UseCleanComment.mentions.push({
// mentioned_username: commentSubStr,
// date: comment.date,
// });
// }
// }
// });
// });
// const allUserMentions = new Array<UserAllMention>();
// for await (const mentionedUser of UseCleanComment.mentions) {
// console.log('mentionedUser', mentionedUser);
// const newMentionData = new UserAllMention();
// newMentionData.comment_status = new Array<CommentStatus>();
// const foundAccount = await this.checkUserFollowingStatus(
// mentionedUser.mentioned_username.split('@')[1],
// );
// if (!foundAccount) {
// (newMentionData.mentioned_username = mentionedUser.mentioned_username),
// (newMentionData.page_follow_date = null),
// (newMentionData.comment_date = mentionedUser.date),
// newMentionData.comment_status.push(CommentStatus.notFollower);
// allUserMentions.push(newMentionData);
// } else {
// newMentionData.mentioned_username = foundAccount.username;
// newMentionData.mentioned_user_id = foundAccount.user_id;
// newMentionData.page_follow_date = foundAccount.follow_date;
// newMentionData.comment_date = mentionedUser.date;
// const checkUserFollowedPageBefore =
// await this.checkUserFollowedPageBefore(
// newMentionData.comment_date,
// newMentionData.page_follow_date,
// );
// console.log('++++++++++++++++++', checkUserFollowedPageBefore);
// if (checkUserFollowedPageBefore === true) {
// console.log('followed before');
// newMentionData.comment_status.push(CommentStatus.isAFollowerBefore);
// }
// console.log('*************', newMentionData.mentioned_username);
// const checkUserMentionedBefore = await this.checkUserMentionedBefore(
// newMentionData.mentioned_username,
// newMentionData.comment_date,
// );
// if (
// checkUserMentionedBefore == true &&
// !newMentionData.comment_status
// ) {
// newMentionData.comment_status.push(CommentStatus.isMentionedBefore);
// }
// if (
// checkUserFollowedPageBefore == false &&
// checkUserMentionedBefore == false
// ) {
// newMentionData.comment_status.push(CommentStatus.isValid);
// }
// allUserMentions.push(newMentionData);
// }
// }
// return {
// mentions: allUserMentions,
// };
// }
// async getResults() {
// const foundUsernames = await this.commentModel.distinct('owner_username');
// // console.log('total users for ranking:', foundUsernames.length);
// for await (const username of foundUsernames) {
// const mentions = await this.calculateUserScore(username);
// console.log('--------------', mentions.mentions);
// let valid_mentions = 0;
// let followed_before = 0;
// let mentions_before = 0;
// let pending_mentions = 0;
// const valid_users = new Array<string>();
// const mentions_before_users = new Array<string>();
// const followed_before_users = new Array<string>();
// const pending_users = new Array<string>();
// mentions.mentions.forEach((mention) => {
// if (mention.comment_status.includes(CommentStatus.isValid)) {
// valid_mentions++;
// valid_users.push(mention.mentioned_username);
// } else if (
// mention.comment_status.includes(CommentStatus.isMentionedBefore)
// ) {
// mentions_before++;
// mentions_before_users.push(mention.mentioned_username);
// } else if (
// mention.comment_status.includes(CommentStatus.isAFollowerBefore)
// ) {
// followed_before++;
// followed_before_users.push(mention.mentioned_username);
// } else if (mention.comment_status.includes(CommentStatus.notFollower)) {
// pending_mentions++;
// pending_users.push(mention.mentioned_username);
// }
// });
// await this.delay(_.random(500, 1000));
// const foundUser = await this.resultModel.findOne({ username: username });
// if (!foundUser) {
// await this.resultModel.create({
// username: username,
// valid_mentions,
// mentions_before,
// followed_before,
// pending_mentions,
// score: valid_mentions + 1,
// valid_users: valid_users,
// followed_before_users: followed_before_users,
// mentions_before_users: mentions_before_users,
// pending_users: pending_users,
// });
// } else {
// await this.resultModel.updateOne(
// { _id: foundUser._id },
// {
// username: username,
// valid_mentions,
// mentions_before,
// followed_before,
// pending_mentions,
// score: valid_mentions + 1,
// valid_users: valid_users,
// followed_before_users: followed_before_users,
// mentions_before_users: mentions_before_users,
// pending_users: pending_users,
// },
// );
// }
// }
// return 'records updated successfully';
// }
// async checkUserMentionedBefore(username, comment_date) {
// const foundCommentsWithThisMention = await this.commentModel.find({
// text: new RegExp(`@${username}`),
// });
// let isValid = false;
// if (foundCommentsWithThisMention.length != 0) {
// foundCommentsWithThisMention.forEach((comment) => {
// if (comment_date > comment.date) {
// isValid = true;
// }
// });
// }
// return isValid;
// }
// async checkUserFollowingStatus(username: string) {
// const res = await this.followerModel.findOne({ username: username });
// return res;
// }
// async checkUserFollowedPageBefore(
// comment_date: number,
// followed_date: number,
// ) {
// if (comment_date < followed_date) {
// return false;
// } else {
// return true;
// }
// }
// async getFinalResults() {
// const results = await this.resultModel.find().sort({ score: -1 });
// const last_update = await this.resultModel.find().sort({ updatedAt: -1 });
// const last_create = await this.resultModel.find().sort({ createdAt: -1 });
// let date: number;
// if (last_update[0]['updatedAt'] >= last_create[0]['createdAt']) {
// date = last_update[0]['updatedAt'];
// } else {
// date = last_create[0]['createdAt'];
// }
// const finalResult = new Array<ResultResponse>();
// for await (const userRes of results) {
// const response: ResultResponse = new ResultResponse();
// response.users = new Array<any>();
// userRes.pending_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.notFollower,
// });
// });
// userRes.mentions_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isMentionedBefore,
// });
// });
// userRes.followed_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isAFollowerBefore,
// });
// });
// userRes.valid_users.forEach((user) => {
// response.users.push({ userId: user, status: CommentStatus.isValid });
// });
// (response.username = userRes.username),
// (response.valid_mentions = userRes.valid_mentions),
// (response.before_mentions = userRes.mentions_before),
// (response.followed_before_mentions = userRes.followed_before),
// (response.pending_mentions = userRes.pending_mentions),
// (response.score = userRes.score);
// finalResult.push(response);
// }
// return {
// finalResult,
// last_update: date,
// };
// }
// async getUserResult(username: string) {
// username = username.toLowerCase();
// const userRes = await this.resultModel.findOne({ username });
// const userIndexs = await this.lotoryResultModel.find({ username });
// if (!userRes) return 'User not found';
// const response: ResultResponse = new ResultResponse();
// response.users = new Array<any>();
// response.lottory_chances_codes = new Array<string>();
// userRes.pending_users.forEach((user) => {
// response.users.push({ userId: user, status: CommentStatus.notFollower });
// });
// userRes.mentions_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isMentionedBefore,
// });
// });
// userRes.followed_before_users.forEach((user) => {
// response.users.push({
// userId: user,
// status: CommentStatus.isAFollowerBefore,
// });
// });
// userRes.valid_users.forEach((user) => {
// response.users.push({ userId: user, status: CommentStatus.isValid });
// });
// (response.username = userRes.username),
// (response.valid_mentions = userRes.valid_mentions),
// (response.before_mentions = userRes.mentions_before),
// (response.followed_before_mentions = userRes.followed_before),
// (response.pending_mentions = userRes.pending_mentions),
// (response.last_update = userRes['updatedAt']),
// (response.score = userRes.score);
// userIndexs.forEach((index) => {
// response.lottory_chances_codes.push(index.index.toString());
// });
// return {
// response,
// };
// }
// shuffle(array) {
// let currentIndex = array.length,
// randomIndex;
// // While there remain elements to shuffle...
// while (0 !== currentIndex) {
// // Pick a remaining element...
// randomIndex = Math.floor(Math.random() * currentIndex);
// currentIndex--;
// // And swap it with the current element.
// [array[currentIndex], array[randomIndex]] = [
// array[randomIndex],
// array[currentIndex],
// ];
// }
// return array;
// }
// async getShuffleData() {
// const comptitionArray = new Array<string>();
// const foundUsernames = await this.resultModel.find();
// console.log(foundUsernames);
// let score = 0;
// for await (const user of foundUsernames) {
// score += user.score;
// for (let index = 0; index < user.score; index++) {
// comptitionArray.push(user.username);
// }
// }
// const res = this.shuffle(comptitionArray);
// console.log('score is', score);
// return res;
// }
// async addResultsToDB() {
// // await this.lotoryResultModel.deleteMany();
// const comptitionArray = new Array<any>();
// const foundUsernames = await this.resultModel
// .find({})
// .sort({});
// let index = 1000;
// for await (const user of foundUsernames) {
// console.log(index)
// for (let u = 0; u < user.valid_users.length; u++) {
// const isChanceExist = await this.lotoryResultModel
// .findOne({
// username: user.username,
// tagged_user: user.valid_users[u],
// })
// .exec();
// if (!isChanceExist)
// comptitionArray.push({
// index,
// username: user.username,
// tagged_user: user.valid_users[u],
// status:"valid"
// });
// index++;
// }
// const isUserChanceExist = await this.lotoryResultModel.findOne({
// username: user.username,
// tagged_user: user.username,
// });
// if (!isUserChanceExist)
// comptitionArray.push({
// index,
// username: user.username,
// tagged_user: user.username,
// status:"valid"
// });
// index++;
// }
// await this.lotoryResultModel.insertMany(comptitionArray);
// return 'successfull';
// }
// export class ResultResponse {
// last_update: Date;
// username: string;
// valid_mentions: number;
// followed_before_mentions: number;
// before_mentions: number;
// pending_mentions: number;
// score: number;
// users?: Array<any>;
// lottory_chances_codes: Array<string>;
// }
export class GetCommentsDto{
username: string
password: string
profile: string
post_short_code: string
export class GetCommentsDto{
username: string
password: string
profile: string
post_short_code: string
}
\ No newline at end of file
export class GetFollowersDto{
username: string
password: string
profile: string
export class GetFollowersDto{
username: string
password: string
profile: string
}
\ No newline at end of file
export class GetLikesDto{
username: string
password: string
profile: string
post_short_code: string
export class GetLikesDto{
username: string
password: string
profile: string
post_short_code: string
}
\ No newline at end of file
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { GetCommentsDto } from './dto/get-comments-dto'
import { GetFollowersDto } from './dto/get-followers-dto'
import { GetLikesDto } from './dto/get-likes-dto'
import { InstagramService } from './instagram.service'
@Controller('instagram')
export class InstagramController {
constructor(private instagramService: InstagramService) { }
@Get('get-json-followers')
async getJsonDataFollowers() {
await this.instagramService.getFollowersFromJsonData()
return "proccess started successfully"
}
@Post('get-followers')
async getFollowers(@Body() getFollowers: GetFollowersDto) {
return await this.instagramService.getFollowersFromInstaLoader(getFollowers.username,
getFollowers.password,getFollowers.profile)
}
@Post('get-likes')
async getLikes(@Body() getLikes: GetLikesDto) {
return this.instagramService.getLikesFromInstaLoader(getLikes.username,
getLikes.password,getLikes.post_short_code ,getLikes.profile)
}
@Post('get-comments')
async getComments(@Body() getComments: GetCommentsDto) {
return await this.instagramService.getCommentsFromInstaLoader(getComments.username,
getComments.password,getComments.post_short_code ,getComments.profile
)
}
}
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { GetCommentsDto } from './dto/get-comments-dto'
import { GetFollowersDto } from './dto/get-followers-dto'
import { GetLikesDto } from './dto/get-likes-dto'
import { InstagramService } from './instagram.service'
@Controller('instagram')
export class InstagramController {
constructor(private instagramService: InstagramService) { }
@Get('get-json-followers')
async getJsonDataFollowers() {
await this.instagramService.getFollowersFromJsonData()
return "proccess started successfully"
}
@Post('get-followers')
async getFollowers(@Body() getFollowers: GetFollowersDto) {
return await this.instagramService.getFollowersFromInstaLoader(getFollowers.username,
getFollowers.password,getFollowers.profile)
}
@Post('get-likes')
async getLikes(@Body() getLikes: GetLikesDto) {
return this.instagramService.getLikesFromInstaLoader(getLikes.username,
getLikes.password,getLikes.post_short_code ,getLikes.profile)
}
@Post('get-comments')
async getComments(@Body() getComments: GetCommentsDto) {
return await this.instagramService.getCommentsFromInstaLoader(getComments.username,
getComments.password,getComments.post_short_code ,getComments.profile
)
}
}
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { InstagramController } from './instagram.controller';
import { InstagramService } from './instagram.service';
import { CommentSchema } from './models/comment.schema';
import { FollowerSchema } from './models/follower.schema';
import { LikeSchema } from './models/like.schema';
import { LottoryResultSchema } from './models/LottoryResult.schema';
import { UserSchema } from './models/user.schema';
@Module({
imports: [
MongooseModule.forFeature([
{ name: 'User', schema: UserSchema },
]),
MongooseModule.forFeature([
{ name: 'Follower', schema: FollowerSchema },
]),
MongooseModule.forFeature([
{ name: 'Like', schema: LikeSchema },
]),
MongooseModule.forFeature([
{ name: 'Comment', schema: CommentSchema },
]),
MongooseModule.forFeature([
{ name: 'LottryResult', schema: LottoryResultSchema },
]),
],
controllers: [InstagramController],
providers: [InstagramService]
})
export class InstagramModule { }
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { InstagramController } from './instagram.controller';
import { InstagramService } from './instagram.service';
import { CommentSchema } from './models/comment.schema';
import { FollowerSchema } from './models/follower.schema';
import { LikeSchema } from './models/like.schema';
import { LottoryResultSchema } from './models/LottoryResult.schema';
import { UserSchema } from './models/user.schema';
@Module({
imports: [
MongooseModule.forFeature([
{ name: 'User', schema: UserSchema },
]),
MongooseModule.forFeature([
{ name: 'Follower', schema: FollowerSchema },
]),
MongooseModule.forFeature([
{ name: 'Like', schema: LikeSchema },
]),
MongooseModule.forFeature([
{ name: 'Comment', schema: CommentSchema },
]),
MongooseModule.forFeature([
{ name: 'LottryResult', schema: LottoryResultSchema },
]),
],
controllers: [InstagramController],
providers: [InstagramService]
})
export class InstagramModule { }
import {
HttpException,
Injectable,
OnApplicationBootstrap,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import * as _ from 'lodash';
import { CommentDocument } from './models/comment.schema';
import { FollowerDocument } from './models/follower.schema';
import { LikeDocument } from './models/like.schema';
import { UserDocument } from './models/user.schema';
import FollowrData from './values/followers _data'
import { spawn } from 'child_process'
import * as path from "path"
@Injectable()
export class InstagramService implements OnApplicationBootstrap {
constructor(
@InjectModel('User')
private userModel: Model<UserDocument>,
@InjectModel('Follower')
private followerModel: Model<FollowerDocument>,
@InjectModel('Like')
private likeModel: Model<LikeDocument>,
@InjectModel('Comment')
private commentModel: Model<CommentDocument>,
) { }
async onApplicationBootstrap() {
}
async getFollowersFromJsonData() {
console.log('start proccess...');
let accountUsername = FollowrData.account_username
let account = await this.findOrCreateUser(accountUsername)
for await (const follower of FollowrData.relationships_followers) {
let user = await this.findOrCreateUser(follower.string_list_data[0].value.toString())
let foundFollower = await this.followerModel.findOne({ $and: [{ user_id: user._id }, { account_id: account._id }] })
if (!foundFollower) {
let importedFollower = await this.followerModel.create({
_id: Types.ObjectId(),
user_id: user._id,
account_id: account._id,
follow_date: follower.string_list_data[0].timestamp
})
}
}
console.log('end of proccess...')
return {message: "successfull"}
}
async getLikesFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
let paths = path.resolve("src","instagram","instaloader-service","getLikes.py")
const getLikesProccess = spawn('python3', [`${paths}`, `${username}`, `${password}`, `${post_short_code}`, `${profile}`,]);
getLikesProccess.stdout.on('data', function (data) {
console.log('start collecting likes from python script ...');
console.log(data.toString())
});
getLikesProccess.on('error', (err) => {
console.log(`child process has error ${err}`)
});
getLikesProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
}
async getCommentsFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
let paths = path.resolve("src","instagram","instaloader-service","getComments.py")
const getCommentsProccess = spawn('python3', [`'${paths}`, `${username}`, `${password}`, `${post_short_code}`, `${profile}`]);
getCommentsProccess.stdout.on('data', function (data) {
console.log('start collecting comments from python script ...');
console.log(data.toString())
});
getCommentsProccess.on('error', (err) => {
console.log(`child process has error ${err}`);
});
getCommentsProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
}
async getFollowersFromInstaLoader(username: string, password: string, profile: string) {
let paths = path.resolve("src","instagram","instaloader-service","getFollowers.py")
const getFollowersProccess = spawn('python3', [`${paths}`, `${username}`, `${password}`, `${profile}`]);
getFollowersProccess.stdout.on('data', function (data) {
console.log('start collecting followers from python script ...');
console.log(data.toString())
});
getFollowersProccess.on('error', (err) => {
console.log(`child process has error ${err}`);
});
getFollowersProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
}
async findOrCreateUser(username: string) {
let user: UserDocument
let foundUser = await this.userModel.findOne({ username })
if (!foundUser) {
let createdUser = await this.userModel.create({
_id: Types.ObjectId(),
username: username
})
user = createdUser
}
else {
user = foundUser
}
return user
}
}
import {
HttpException,
Injectable,
OnApplicationBootstrap,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import * as _ from 'lodash';
import { CommentDocument } from './models/comment.schema';
import { FollowerDocument } from './models/follower.schema';
import { LikeDocument } from './models/like.schema';
import { UserDocument } from './models/user.schema';
import FollowrData from './values/followers _data'
import { spawn } from 'child_process'
import * as path from "path"
@Injectable()
export class InstagramService implements OnApplicationBootstrap {
constructor(
@InjectModel('User')
private userModel: Model<UserDocument>,
@InjectModel('Follower')
private followerModel: Model<FollowerDocument>,
@InjectModel('Like')
private likeModel: Model<LikeDocument>,
@InjectModel('Comment')
private commentModel: Model<CommentDocument>,
) { }
async onApplicationBootstrap() {
}
async getFollowersFromJsonData() {
console.log('start proccess...');
let accountUsername = FollowrData.account_username
let account = await this.findOrCreateUser(accountUsername)
for await (const follower of FollowrData.relationships_followers) {
let user = await this.findOrCreateUser(follower.string_list_data[0].value.toString())
let foundFollower = await this.followerModel.findOne({ $and: [{ user_id: user._id }, { account_id: account._id }] })
if (!foundFollower) {
let importedFollower = await this.followerModel.create({
_id: Types.ObjectId(),
user_id: user._id,
account_id: account._id,
follow_date: follower.string_list_data[0].timestamp
})
}
}
console.log('end of proccess...')
return {message: "successfull"}
}
async getLikesFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
let paths = path.resolve("src","instagram","instaloader-service","getLikes.py")
const getLikesProccess = spawn('python3', [`${paths}`, `${username}`, `${password}`, `${post_short_code}`, `${profile}`,]);
getLikesProccess.stdout.on('data', function (data) {
console.log('start collecting likes from python script ...');
console.log(data.toString())
});
getLikesProccess.on('error', (err) => {
console.log(`child process has error ${err}`)
});
getLikesProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
}
async getCommentsFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
let paths = path.resolve("src","instagram","instaloader-service","getComments.py")
const getCommentsProccess = spawn('python3', [`'${paths}`, `${username}`, `${password}`, `${post_short_code}`, `${profile}`]);
getCommentsProccess.stdout.on('data', function (data) {
console.log('start collecting comments from python script ...');
console.log(data.toString())
});
getCommentsProccess.on('error', (err) => {
console.log(`child process has error ${err}`);
});
getCommentsProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
}
async getFollowersFromInstaLoader(username: string, password: string, profile: string) {
let paths = path.resolve("src","instagram","instaloader-service","getFollowers.py")
const getFollowersProccess = spawn('python3', [`${paths}`, `${username}`, `${password}`, `${profile}`]);
getFollowersProccess.stdout.on('data', function (data) {
console.log('start collecting followers from python script ...');
console.log(data.toString())
});
getFollowersProccess.on('error', (err) => {
console.log(`child process has error ${err}`);
});
getFollowersProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
}
async findOrCreateUser(username: string) {
let user: UserDocument
let foundUser = await this.userModel.findOne({ username })
if (!foundUser) {
let createdUser = await this.userModel.create({
_id: Types.ObjectId(),
username: username
})
user = createdUser
}
else {
user = foundUser
}
return user
}
}
import instaloader
import pymongo
username = "kakasrm"
password = "kaka1374"
mongo_connection_string = "mongodb://azadi:azadi%404010@185.231.180.248:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "azadi-gold-backend"
post_short_code = "CSCUev0swJO"
PROFILE = "azadi.gold"
def __main__():
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get likes of given post short code
getLikes(db, post, PROFILE)
# get comments of given post short code
# getComments(db, post, PROFILE)
# get Followers of given profile
# getFollowers(db, profile, PROFILE)
# get tagged Posts of given profile
# getTaggedPosts(db, profile)
def getComments(db, post, profile):
col = db["comments"]
post_col = db["posts"]
account_col = db['users']
print('start getting comments')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile}, )
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one({"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for comment in post.get_comments():
print("Searching : ", comment.id)
search = col.find_one({"comment_id": comment.id})
try:
if search is not None and search["comment_id"]:
print(comment.id, " Already Exist")
else:
user_id = None
found_username = account_col.find_one({'username': comment.owner.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one({"username": comment.owner.username,
"instagram_user_id": comment.owner.userid})
user_id = created_user.inserted_id
print(comment.owner.username, 'added to users')
temp = {"comment_id": comment.id, "user_id": user_id, "post_id": post_id,
"text": comment.text, "date": comment.created_at_utc.timestamp()}
x = col.update(temp, temp, upsert=True)
print(comment.id, " added")
except:
print("Error")
def getLikes(db, post, profile):
col = db["likes"]
post_col = db["posts"]
account_col = db['users']
print('start getting likes')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile},)
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one({"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for like in post.get_likes():
print('======', like)
print("Searching : ", like.username, post_id)
search = col.find_one(
{"username": like.username, "post_id": post_id})
try:
if search is not None:
print(like.username, " Already like post : ", post_id)
else:
user_id = None
found_username = account_col.find_one({'username': like.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": like.username})
user_id = created_user.inserted_id
print(like.username, 'added to users')
temp = {"user_id": user_id,
"post_id": post_id}
x = col.update(temp, temp, upsert=True)
print(like.username, " like post : ", post_short_code)
except:
print("Error")
def getFollowers(db, profile, profile_username):
col = db["followers"]
account_col = db['users']
account_id = None
found_username = account_col.find_one({'username': profile_username})
if found_username is not None:
print(found_username['username'], 'is already exists')
account_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": profile_username, type: "business"})
account_id = created_user.inserted_id
print(profile_username, 'added to users')
for follower in profile.get_followers():
print("Searching in ", profile, " for :", follower.username)
search = col.find_one({"username": follower.username})
try:
if search is not None:
print(follower.username, " Already Exist in : ",
profile, "Followers")
else:
user_id = None
found_username = account_col.find_one({'username': follower.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": follower.username,
"instagram_user_id": follower.userid, "full_name": follower.full_name})
user_id = created_user.inserted_id
print(follower.username, 'added to users')
temp = {"username": follower.username, "user_id": user_id,
"account_id": account_id, "follow_date": "", "profile_pic": follower.profile_pic_url, }
x = col.update(temp, temp, upsert=True)
print(follower.username, " followed : ", profile)
except:
print("Error")
def getTaggedPosts(db, profile):
col = db["tagged"]
for tagged_post in profile.get_tagged_posts():
print("Searching in ", profile,
" for tagged post with id :", tagged_post.shortcode)
search = col.find_one({"short_code": tagged_post.shortcode})
try:
if search is not None:
print(tagged_post.shortcode, " Already Exist in : tagged_posts")
else:
temp = {"username": tagged_post.username, "user_id": tagged_post.userid,
"post_short_code": tagged_post.shortcode,
"business_username": PROFILE, "post_date": tagged_post.date_utc}
x = col.update(temp, temp, upsert=True)
print(tagged_post.shortcode, " added")
except:
print("Error")
__main__()
import instaloader
import pymongo
username = "kakasrm"
password = "kaka1374"
mongo_connection_string = "mongodb://azadi:azadi%404010@185.231.180.248:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "azadi-gold-backend"
post_short_code = "CSCUev0swJO"
PROFILE = "azadi.gold"
def __main__():
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get likes of given post short code
getLikes(db, post, PROFILE)
# get comments of given post short code
# getComments(db, post, PROFILE)
# get Followers of given profile
# getFollowers(db, profile, PROFILE)
# get tagged Posts of given profile
# getTaggedPosts(db, profile)
def getComments(db, post, profile):
col = db["comments"]
post_col = db["posts"]
account_col = db['users']
print('start getting comments')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile}, )
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one({"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for comment in post.get_comments():
print("Searching : ", comment.id)
search = col.find_one({"comment_id": comment.id})
try:
if search is not None and search["comment_id"]:
print(comment.id, " Already Exist")
else:
user_id = None
found_username = account_col.find_one({'username': comment.owner.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one({"username": comment.owner.username,
"instagram_user_id": comment.owner.userid})
user_id = created_user.inserted_id
print(comment.owner.username, 'added to users')
temp = {"comment_id": comment.id, "user_id": user_id, "post_id": post_id,
"text": comment.text, "date": comment.created_at_utc.timestamp()}
x = col.update(temp, temp, upsert=True)
print(comment.id, " added")
except:
print("Error")
def getLikes(db, post, profile):
col = db["likes"]
post_col = db["posts"]
account_col = db['users']
print('start getting likes')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile},)
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one({"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for like in post.get_likes():
print('======', like)
print("Searching : ", like.username, post_id)
search = col.find_one(
{"username": like.username, "post_id": post_id})
try:
if search is not None:
print(like.username, " Already like post : ", post_id)
else:
user_id = None
found_username = account_col.find_one({'username': like.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": like.username})
user_id = created_user.inserted_id
print(like.username, 'added to users')
temp = {"user_id": user_id,
"post_id": post_id}
x = col.update(temp, temp, upsert=True)
print(like.username, " like post : ", post_short_code)
except:
print("Error")
def getFollowers(db, profile, profile_username):
col = db["followers"]
account_col = db['users']
account_id = None
found_username = account_col.find_one({'username': profile_username})
if found_username is not None:
print(found_username['username'], 'is already exists')
account_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": profile_username, type: "business"})
account_id = created_user.inserted_id
print(profile_username, 'added to users')
for follower in profile.get_followers():
print("Searching in ", profile, " for :", follower.username)
search = col.find_one({"username": follower.username})
try:
if search is not None:
print(follower.username, " Already Exist in : ",
profile, "Followers")
else:
user_id = None
found_username = account_col.find_one({'username': follower.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": follower.username,
"instagram_user_id": follower.userid, "full_name": follower.full_name})
user_id = created_user.inserted_id
print(follower.username, 'added to users')
temp = {"username": follower.username, "user_id": user_id,
"account_id": account_id, "follow_date": "", "profile_pic": follower.profile_pic_url, }
x = col.update(temp, temp, upsert=True)
print(follower.username, " followed : ", profile)
except:
print("Error")
def getTaggedPosts(db, profile):
col = db["tagged"]
for tagged_post in profile.get_tagged_posts():
print("Searching in ", profile,
" for tagged post with id :", tagged_post.shortcode)
search = col.find_one({"short_code": tagged_post.shortcode})
try:
if search is not None:
print(tagged_post.shortcode, " Already Exist in : tagged_posts")
else:
temp = {"username": tagged_post.username, "user_id": tagged_post.userid,
"post_short_code": tagged_post.shortcode,
"business_username": PROFILE, "post_date": tagged_post.date_utc}
x = col.update(temp, temp, upsert=True)
print(tagged_post.shortcode, " added")
except:
print("Error")
__main__()
import instaloader
import pymongo
import sys
username = "kakasrm"
password = "kaka1374"
mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "instagram-lottry"
post_short_code = "CShKEJijy4v"
PROFILE = "azadi.gold"
def __main__():
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get comments of given post short code
getComments(db, post, PROFILE)
def getComments(db, post, profile):
col = db["comments"]
post_col = db["posts"]
account_col = db['users']
print('start getting comments')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile}, )
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one(
{"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for comment in post.get_comments():
print("Searching : ", comment.id)
search = col.find_one({"comment_id": comment.id})
try:
if search is not None and search["comment_id"]:
print(comment.id, " Already Exist")
else:
user_id = None
found_username = account_col.find_one(
{'username': comment.owner.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one({"username": comment.owner.username,
"instagram_user_id": comment.owner.userid})
user_id = created_user.inserted_id
print(comment.owner.username, 'added to users')
temp = {"comment_id": comment.id, "user_id": user_id, "post_id": post_id,
"text": comment.text, "date": comment.created_at_utc.timestamp()}
x = col.update(temp, temp, upsert=True)
print(comment.id, " added")
except:
print("Error")
__main__()
import instaloader
import pymongo
import sys
username = "kakasrm"
password = "kaka1374"
mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "instagram-lottry"
post_short_code = "CShKEJijy4v"
PROFILE = "azadi.gold"
def __main__():
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get comments of given post short code
getComments(db, post, PROFILE)
def getComments(db, post, profile):
col = db["comments"]
post_col = db["posts"]
account_col = db['users']
print('start getting comments')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile}, )
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one(
{"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for comment in post.get_comments():
print("Searching : ", comment.id)
search = col.find_one({"comment_id": comment.id})
try:
if search is not None and search["comment_id"]:
print(comment.id, " Already Exist")
else:
user_id = None
found_username = account_col.find_one(
{'username': comment.owner.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one({"username": comment.owner.username,
"instagram_user_id": comment.owner.userid})
user_id = created_user.inserted_id
print(comment.owner.username, 'added to users')
temp = {"comment_id": comment.id, "user_id": user_id, "post_id": post_id,
"text": comment.text, "date": comment.created_at_utc.timestamp()}
x = col.update(temp, temp, upsert=True)
print(comment.id, " added")
except:
print("Error")
__main__()
import instaloader
import pymongo
import sys
username = str(sys.argv[1])
password = str(sys.argv[2])
mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "instagram-lottry"
PROFILE = str(sys.argv[3])
def __main__():
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
# post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get Followers of given profile
getFollowers(db, profile, PROFILE)
def getFollowers(db, profile, profile_username):
col = db["followers"]
account_col = db['users']
account_id = None
found_username = account_col.find_one({'username': profile_username})
if found_username is not None:
print(found_username['username'], 'is already exists')
account_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": profile_username, type: "business"})
account_id = created_user.inserted_id
print(profile_username, 'added to users')
for follower in profile.get_followers():
print("Searching in ", profile, " for :", follower.username)
search = col.find_one({"username": follower.username})
try:
if search is not None:
print(follower.username, " Already Exist in : ",
profile, "Followers")
else:
user_id = None
found_username = account_col.find_one(
{'username': follower.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": follower.username,
"instagram_user_id": follower.userid, "full_name": follower.full_name})
user_id = created_user.inserted_id
print(follower.username, 'added to users')
temp = {"username": follower.username, "user_id": user_id,
"account_id": account_id, "follow_date": "", "profile_pic": follower.profile_pic_url, }
x = col.update(temp, temp, upsert=True)
print(follower.username, " followed : ", profile)
except:
print("Error")
__main__()
import instaloader
import pymongo
import sys
username = str(sys.argv[1])
password = str(sys.argv[2])
mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "instagram-lottry"
PROFILE = str(sys.argv[3])
def __main__():
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
# post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get Followers of given profile
getFollowers(db, profile, PROFILE)
def getFollowers(db, profile, profile_username):
col = db["followers"]
account_col = db['users']
account_id = None
found_username = account_col.find_one({'username': profile_username})
if found_username is not None:
print(found_username['username'], 'is already exists')
account_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": profile_username, type: "business"})
account_id = created_user.inserted_id
print(profile_username, 'added to users')
for follower in profile.get_followers():
print("Searching in ", profile, " for :", follower.username)
search = col.find_one({"username": follower.username})
try:
if search is not None:
print(follower.username, " Already Exist in : ",
profile, "Followers")
else:
user_id = None
found_username = account_col.find_one(
{'username': follower.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": follower.username,
"instagram_user_id": follower.userid, "full_name": follower.full_name})
user_id = created_user.inserted_id
print(follower.username, 'added to users')
temp = {"username": follower.username, "user_id": user_id,
"account_id": account_id, "follow_date": "", "profile_pic": follower.profile_pic_url, }
x = col.update(temp, temp, upsert=True)
print(follower.username, " followed : ", profile)
except:
print("Error")
__main__()
import instaloader
import pymongo
import sys
username = str(sys.argv[1])
password = str(sys.argv[2])
mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "instagram-lottry"
post_short_code = str(sys.argv[3])
PROFILE = str(sys.argv[4])
def __main__():
print(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get likes of given post short code
getLikes(db, post, PROFILE)
def getLikes(db, post, profile):
col = db["likes"]
post_col = db["posts"]
account_col = db['users']
print('start getting likes')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile},)
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one(
{"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for like in post.get_likes():
print('======', like)
print("Searching : ", like.username, post_id)
search = col.find_one(
{"username": like.username, "post_id": post_id})
try:
if search is not None:
print(like.username, " Already like post : ", post_id)
else:
user_id = None
found_username = account_col.find_one(
{'username': like.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": like.username})
user_id = created_user.inserted_id
print(like.username, 'added to users')
temp = {"user_id": user_id,
"post_id": post_id}
x = col.update(temp, temp, upsert=True)
print(like.username, " like post : ", post_short_code)
except:
print("Error")
__main__()
import instaloader
import pymongo
import sys
username = str(sys.argv[1])
password = str(sys.argv[2])
mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "instagram-lottry"
post_short_code = str(sys.argv[3])
PROFILE = str(sys.argv[4])
def __main__():
print(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
print("connecting to the instagram ....")
L = instaloader.Instaloader()
L.login(username, password)
profile = instaloader.Profile.from_username(L.context, PROFILE)
print("connected to the instagram :) ")
print("Load post data ....")
post = instaloader.Post.from_shortcode(L.context, post_short_code)
print("Post data loaded :) ")
print("connecting to the database ....")
client = pymongo.MongoClient(mongo_connection_string)
db = client[database_name]
# get likes of given post short code
getLikes(db, post, PROFILE)
def getLikes(db, post, profile):
col = db["likes"]
post_col = db["posts"]
account_col = db['users']
print('start getting likes')
account_id = None
post_id = None
found_account = account_col.find_one({"username": profile},)
if found_account is not None:
print(found_account['username'], 'is already exists')
account_id = found_account['_id']
else:
created_account = account_col.insert_one({"username": profile})
account_id = created_account.inserted_id
print(profile, 'added to users')
found_post = post_col.find_one({"url": post_short_code})
if found_post is not None:
print(found_post['url'], 'is already exists')
post_id = found_post['_id']
else:
created_post = post_col.insert_one(
{"url": post_short_code, "user_id": account_id})
post_id = created_post.inserted_id
print(post_short_code, 'added to posts')
for like in post.get_likes():
print('======', like)
print("Searching : ", like.username, post_id)
search = col.find_one(
{"username": like.username, "post_id": post_id})
try:
if search is not None:
print(like.username, " Already like post : ", post_id)
else:
user_id = None
found_username = account_col.find_one(
{'username': like.username})
if found_username is not None:
print(found_username['username'], 'is already exists')
user_id = found_username['_id']
else:
created_user = account_col.insert_one(
{"username": like.username})
user_id = created_user.inserted_id
print(like.username, 'added to users')
temp = {"user_id": user_id,
"post_id": post_id}
x = col.update(temp, temp, upsert=True)
print(like.username, " like post : ", post_short_code)
except:
print("Error")
__main__()
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type LottoryResultDocument = LottoryResult & Document;
@Schema({ timestamps: true })
export class LottoryResult {
@Prop()
_id: Types.ObjectId
@Prop()
index: string;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
// @Prop()
// tagged_user: string;
@Prop()
status: string;
}
export const LottoryResultSchema = SchemaFactory.createForClass(LottoryResult);
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type LottoryResultDocument = LottoryResult & Document;
@Schema({ timestamps: true })
export class LottoryResult {
@Prop()
_id: Types.ObjectId
@Prop()
index: string;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
// @Prop()
// tagged_user: string;
@Prop()
status: string;
}
export const LottoryResultSchema = SchemaFactory.createForClass(LottoryResult);
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type CommentDocument = Comment & Document;
@Schema({ timestamps: true })
export class Comment {
@Prop()
_id: Types.ObjectId;
@Prop()
comment_id: string;
@Prop()
text: string;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
@Prop({ type: Types.ObjectId, ref: 'Post' })
post_id: Types.ObjectId
@Prop()
date: number;
@Prop({ type: Object })
comment_object: Object;
}
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type CommentDocument = Comment & Document;
@Schema({ timestamps: true })
export class Comment {
@Prop()
_id: Types.ObjectId;
@Prop()
comment_id: string;
@Prop()
text: string;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
@Prop({ type: Types.ObjectId, ref: 'Post' })
post_id: Types.ObjectId
@Prop()
date: number;
@Prop({ type: Object })
comment_object: Object;
}
export const CommentSchema = SchemaFactory.createForClass(Comment);
\ No newline at end of file
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type FollowerDocument = Follower & Document;
@Schema({ timestamps: true })
export class Follower {
@Prop()
_id: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
@Prop({ type: Types.ObjectId, ref: 'User' })
account_id: Types.ObjectId
@Prop()
follow_date: number;
}
export const FollowerSchema =
SchemaFactory.createForClass(Follower);
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type FollowerDocument = Follower & Document;
@Schema({ timestamps: true })
export class Follower {
@Prop()
_id: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
@Prop({ type: Types.ObjectId, ref: 'User' })
account_id: Types.ObjectId
@Prop()
follow_date: number;
}
export const FollowerSchema =
SchemaFactory.createForClass(Follower);
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type LikeDocument = Like & Document;
@Schema({ timestamps: true })
export class Like {
@Prop()
_id: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
@Prop({ type: Types.ObjectId, ref: 'Post' })
post_id: Types.ObjectId
}
export const LikeSchema =
SchemaFactory.createForClass(Like);
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type LikeDocument = Like & Document;
@Schema({ timestamps: true })
export class Like {
@Prop()
_id: Types.ObjectId;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
@Prop({ type: Types.ObjectId, ref: 'Post' })
post_id: Types.ObjectId
}
export const LikeSchema =
SchemaFactory.createForClass(Like);
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type PostDocument = Post & Document;
@Schema({ timestamps: true })
export class Post {
@Prop()
_id: Types.ObjectId
@Prop()
url: string
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
}
export const PostSchema =
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type PostDocument = Post & Document;
@Schema({ timestamps: true })
export class Post {
@Prop()
_id: Types.ObjectId
@Prop()
url: string
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
}
export const PostSchema =
SchemaFactory.createForClass(Post)
\ No newline at end of file
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type UserDocument = User & Document;
export enum AccountType {
business = "business",
customer = "customer"
}
@Schema({ timestamps: true })
export class User {
@Prop()
_id: Types.ObjectId
@Prop()
username: string
@Prop()
instagram_user_id: string
@Prop()
full_name: string
@Prop({ enum: AccountType })
type: string
@Prop()
mobile: string
}
export const UserSchema =
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
export type UserDocument = User & Document;
export enum AccountType {
business = "business",
customer = "customer"
}
@Schema({ timestamps: true })
export class User {
@Prop()
_id: Types.ObjectId
@Prop()
username: string
@Prop()
instagram_user_id: string
@Prop()
full_name: string
@Prop({ enum: AccountType })
type: string
@Prop()
mobile: string
}
export const UserSchema =
SchemaFactory.createForClass(User)
\ No newline at end of file
export default {
addToStoryData : [
{
username: "soma.ye2103",
count: 5
},
{
username: "zahra_51512",
count: 1
},
{
username: "nafas3633m",
count: 1
},
{
username: "jafar.amr",
count: 1
},
{
username: "sougool5382",
count: 1
},
{
username: "maryam.maryammy",
count: 1
},
{
username: "toktam.yobi80",
count: 1
},
{
username: "roghayeh_b8082",
count: 1
},
{
username: "turky.yyy",
count: 1
},
{
username: "liligoli",
count: 1
},
{
username: "soh.ila50",
count: 1
},
{
username: "_mrs_kz_z",
count: 1
},
]
export default {
addToStoryData : [
{
username: "soma.ye2103",
count: 5
},
{
username: "zahra_51512",
count: 1
},
{
username: "nafas3633m",
count: 1
},
{
username: "jafar.amr",
count: 1
},
{
username: "sougool5382",
count: 1
},
{
username: "maryam.maryammy",
count: 1
},
{
username: "toktam.yobi80",
count: 1
},
{
username: "roghayeh_b8082",
count: 1
},
{
username: "turky.yyy",
count: 1
},
{
username: "liligoli",
count: 1
},
{
username: "soh.ila50",
count: 1
},
{
username: "_mrs_kz_z",
count: 1
},
]
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment