Commit 8c6a77d0 authored by soheib's avatar soheib
Browse files

latest

parent 8995857d
import { Controller } from '@nestjs/common';
@Controller('instagram')
export class InstagramController {}
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'
@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...');
}
async getLikesFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
const getLikesProccess = spawn('python3', ['src/service/getLikes.py', `${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}`);
return err
});
getLikesProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
return "successfull"
});
}
async getCommentsFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
const getCommentsProccess = spawn('python3', ['src/service/getComments.py', `${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}`);
return err
});
getCommentsProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
return "successfull"
});
}
async getFollowersFromInstaLoader(username: string, password: string, profile: string) {
const getFollowersProccess = spawn('python3', ['src/service/getFollowers.py', `${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}`);
return err
});
getFollowersProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
return "successfull"
});
}
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
import sys
username = str(sys.argv[1])
password = str(sys.argv[2])
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 = str(sys.argv[3])
PROFILE = str(sys.argv[4])
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://azadi:azadi%404010@185.231.180.248:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "azadi-gold-backend"
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://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 = 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()
index: number;
@Prop()
username: string;
// @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;
}
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 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 =
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
}
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
},
]
}
\ No newline at end of file
This diff is collapsed.
export class WeeklySearchDto {
username: string
profile_username: string
}
\ No newline at end of file
import { Body, Query, Controller, Get, Post } from '@nestjs/common';
import { LotteryService } from './lottery.service';
@Controller('lottery')
export class LotteryController {
constructor(private lotteryService: LotteryService) { }
//weekly lottery apies:
@Post('weekly/search')
async getUserResults(@Body() username: string) {
return await this.lotteryService.getUserScore(username);
}
@Post('weekly/calculate-score')
async getFollowers() {
return await this.lotteryService.addResultsToDB();
}
@Get('weekly/get-lottory-result')
async getResultDb() {
return await this.lotteryService.getResultDb();
}
}
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CommentSchema } from 'src/instagram/models/comment.schema';
import { FollowerSchema } from 'src/instagram/models/follower.schema';
import { LikeSchema } from 'src/instagram/models/like.schema';
import { LottoryResultSchema } from 'src/instagram/models/LottoryResult.schema';
import { UserSchema } from 'src/instagram/models/user.schema';
import { LotteryController } from './lottery.controller';
import { LotteryService } from './lottery.service';
import { ScoreService } from './score.service';
@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: [LotteryController],
providers: [LotteryService, ScoreService]
})
export class LotteryModule { }
import { HttpException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CommentDocument } from 'src/instagram/models/comment.schema';
import { FollowerDocument } from 'src/instagram/models/follower.schema';
import { LikeDocument } from 'src/instagram/models/like.schema';
import { UserDocument } from 'src/instagram/models/user.schema';
import addToStoryData from '../instagram/values/add-to-story-data'
import { ScoreService } from './score.service';
@Injectable()
export class LotteryService {
constructor(
private scoreService: ScoreService,
@InjectModel('User')
private userModel: Model<UserDocument>,
@InjectModel('Follower')
private followerModel: Model<FollowerDocument>,
@InjectModel('Like')
private likeModel: Model<LikeDocument>,
@InjectModel('Comment')
private commentModel: Model<CommentDocument>,
@InjectModel('LottryResult')
private lotteryResultModel: Model<CommentDocument>
) { }
async getUserScore(username: string, profileUsername: string, postArray: string[]) {
let likesScore = await this.scoreService.getUserLikesScore(username, profileUsername, postArray)
let commentScore = await this.scoreService.getUserCommentsScore(username, profileUsername, postArray)
let addToStoryScore = await this.scoreService.getTagsScore(username)
return { likesScore, commentScore, addToStoryScore, totalScore: likesScore + commentScore + addToStoryScore }
}
async addResultsToDB(profileUsername: string, postArray: string[]) {
await this.lotteryResultModel.deleteMany({})
let foundUsernameInComment = await this.commentModel.distinct('owner_username')
let foundUsernameInLike = await this.likeModel.distinct('username')
let foundUsernames = new Array<string>()
foundUsernameInComment.forEach((username) => {
if (!foundUsernames.includes(username)) {
foundUsernames.push(username)
}
})
foundUsernameInLike.forEach((username) => {
if (!foundUsernames.includes(username)) {
foundUsernames.push(username)
}
})
console.log(foundUsernames);
const comptitionArray = new Array<any>();
let index = 1000;
let totalItems = foundUsernames.length
let count = 0
for await (const username of foundUsernames) {
let userScore = await this.scoreService.calculateUserScore(username, profileUsername, postArray)
for (let u = 0; u < userScore; u++) {
comptitionArray.push({
index,
username: username,
})
index++;
console.log(`username:${username} , index: ${index}, score:${userScore}`);
}
console.log(`user index:${count} , total items: ${totalItems}`);
count++
}
await this.lotteryResultModel.insertMany(comptitionArray);
return 'successfull';
}
async getResultDb() {
return await this.lotteryResultModel
.find()
.select({ username: 1, index: 1 });
}
}
import { HttpException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { CommentDocument } from 'src/instagram/models/comment.schema';
import { FollowerDocument } from 'src/instagram/models/follower.schema';
import { LikeDocument } from 'src/instagram/models/like.schema';
import { UserDocument } from 'src/instagram/models/user.schema';
import addToStoryData from '../instagram/values/add-to-story-data'
@Injectable()
export class ScoreService {
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>,
@InjectModel('LottryResult')
private lotteryResultModel: Model<CommentDocument>
) { }
async getUserLikesScore(username: string, profileUsername: string, postArray: string[]) {
let foundUser = await this.userModel.findOne({ username })
let foundProfile = await this.userModel.findOne({ username: profileUsername })
let foundFollower = await this.followerModel.findOne({
$and: [
{ user_id: foundUser._id },
{ account_id: foundProfile._id }
]
})
if (foundFollower) {
let foundLikes = await this.likeModel.find({ username })
return foundLikes.length
}
else {
return 0
}
}
async getUserCommentsScore(username: string, profileUsername: string, postArray: string[]) {
let userCommentScore = new Array<{ post_id: string, post_score: number }>()
postArray.forEach((post) => {
userCommentScore.push({
post_id: post,
post_score: 0
})
})
let foundUserComments = await this.commentModel.find({ owner_username: username })
for await (const comment of foundUserComments) {
userCommentScore.forEach(element => {
if (comment.post_id.toString() === element.post_id.toString() && element.post_score < 3) {
element.post_score++
}
})
}
let score = 0
userCommentScore.forEach(element => {
score += element.post_score
})
return score
}
async getTagsScore(username: string) {
let addToStoryScore = 0
let foundUser = addToStoryData.addToStoryData.find((user) => {
return user.username === username
})
if (foundUser) {
addToStoryScore = foundUser.count
}
return addToStoryScore
}
async calculateUserScore(username: string, profileUsername: string, postArray: string[]) {
let likesScore = await this.getUserLikesScore(username, profileUsername, postArray)
let commentScore = await this.getUserCommentsScore(username, profileUsername, postArray)
let addToStoryScore = await this.getTagsScore(username)
return likesScore + commentScore + addToStoryScore
}
}
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