Commit c670bdce authored by soheib's avatar soheib
Browse files

update services

parent 18cf3ef6
...@@ -14,7 +14,7 @@ import { LottoryResultSchema } from './instagram/models/LottoryResult.schema' ...@@ -14,7 +14,7 @@ import { LottoryResultSchema } from './instagram/models/LottoryResult.schema'
@Module({ @Module({
imports: [ imports: [
MongooseModule.forRoot( MongooseModule.forRoot(
'mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=admin', '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([ MongooseModule.forFeature([
{ name: 'User', schema: UserSchema }, { name: 'User', schema: UserSchema },
......
...@@ -12,6 +12,7 @@ import { LikeDocument } from './models/like.schema'; ...@@ -12,6 +12,7 @@ import { LikeDocument } from './models/like.schema';
import { UserDocument } from './models/user.schema'; import { UserDocument } from './models/user.schema';
import FollowrData from './values/followers _data' import FollowrData from './values/followers _data'
import { spawn } from 'child_process' import { spawn } from 'child_process'
import * as path from "path"
@Injectable() @Injectable()
export class InstagramService implements OnApplicationBootstrap { export class InstagramService implements OnApplicationBootstrap {
...@@ -54,9 +55,8 @@ export class InstagramService implements OnApplicationBootstrap { ...@@ -54,9 +55,8 @@ export class InstagramService implements OnApplicationBootstrap {
async getLikesFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) { async getLikesFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
let status: string = "" let paths = path.resolve("src","instagram","instaloader-service","getLikes.py")
let err_message: string const getLikesProccess = spawn('python3', [`${paths}`, `${username}`, `${password}`, `${post_short_code}`, `${profile}`,]);
const getLikesProccess = spawn('python3', ['src/service/getLikes.py', `${username}`, `${password}`, `${post_short_code}`, `${profile}`,]);
getLikesProccess.stdout.on('data', function (data) { getLikesProccess.stdout.on('data', function (data) {
console.log('start collecting likes from python script ...'); console.log('start collecting likes from python script ...');
...@@ -65,26 +65,18 @@ export class InstagramService implements OnApplicationBootstrap { ...@@ -65,26 +65,18 @@ export class InstagramService implements OnApplicationBootstrap {
getLikesProccess.on('error', (err) => { getLikesProccess.on('error', (err) => {
console.log(`child process has error ${err}`) console.log(`child process has error ${err}`)
status = "error"
err_message = err.message
}); });
getLikesProccess.on('close', (code) => { getLikesProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`); console.log(`child process close all stdio with code ${code}`);
status = "successfull"
}); });
if(status === "error"){
return {message: err_message}
}
if(status === "successfull"){
return {message: "successfull"}
}
} }
async getCommentsFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) { async getCommentsFromInstaLoader(username: string, password: string, post_short_code: string, profile: string) {
let status: string = "" let paths = path.resolve("src","instagram","instaloader-service","getComments.py")
let err_message: string
const getCommentsProccess = spawn('python3', ['src/service/getComments.py', `${username}`, `${password}`, `${post_short_code}`, `${profile}`]); const getCommentsProccess = spawn('python3', [`'${paths}`, `${username}`, `${password}`, `${post_short_code}`, `${profile}`]);
getCommentsProccess.stdout.on('data', function (data) { getCommentsProccess.stdout.on('data', function (data) {
console.log('start collecting comments from python script ...'); console.log('start collecting comments from python script ...');
...@@ -93,26 +85,16 @@ export class InstagramService implements OnApplicationBootstrap { ...@@ -93,26 +85,16 @@ export class InstagramService implements OnApplicationBootstrap {
getCommentsProccess.on('error', (err) => { getCommentsProccess.on('error', (err) => {
console.log(`child process has error ${err}`); console.log(`child process has error ${err}`);
status = "error"
err_message = err.message
}); });
getCommentsProccess.on('close', (code) => { getCommentsProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`); console.log(`child process close all stdio with code ${code}`);
status = "successfull"
}); });
if(status === "error"){
return {message: err_message}
}
if(status === "successfull"){
return {message: "successfull"}
}
} }
async getFollowersFromInstaLoader(username: string, password: string, profile: string) { async getFollowersFromInstaLoader(username: string, password: string, profile: string) {
let status: string = "" let paths = path.resolve("src","instagram","instaloader-service","getFollowers.py")
let err_message: string const getFollowersProccess = spawn('python3', [`${paths}`, `${username}`, `${password}`, `${profile}`]);
const getFollowersProccess = spawn('python3', ['src/service/getFollowers.py', `${username}`, `${password}`, `${profile}`]);
getFollowersProccess.stdout.on('data', function (data) { getFollowersProccess.stdout.on('data', function (data) {
console.log('start collecting followers from python script ...'); console.log('start collecting followers from python script ...');
...@@ -121,20 +103,11 @@ export class InstagramService implements OnApplicationBootstrap { ...@@ -121,20 +103,11 @@ export class InstagramService implements OnApplicationBootstrap {
getFollowersProccess.on('error', (err) => { getFollowersProccess.on('error', (err) => {
console.log(`child process has error ${err}`); console.log(`child process has error ${err}`);
status = "error"
err_message = err.message
}); });
getFollowersProccess.on('close', (code) => { getFollowersProccess.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`); console.log(`child process close all stdio with code ${code}`);
status = "successfull"
}); });
if(status === "error"){
return {message: err_message}
}
if(status === "successfull"){
return {message: "successfull"}
}
} }
async findOrCreateUser(username: string) { async findOrCreateUser(username: string) {
......
...@@ -2,12 +2,12 @@ import instaloader ...@@ -2,12 +2,12 @@ import instaloader
import pymongo import pymongo
import sys import sys
username = str(sys.argv[1]) username = "kakasrm"
password = str(sys.argv[2]) password = "kaka1374"
mongo_connection_string = "mongodb://azadi:azadi%404010@185.231.180.248:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-256" mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "azadi-gold-backend" database_name = "instagram-lottry"
post_short_code = str(sys.argv[3]) post_short_code = "CShKEJijy4v"
PROFILE = str(sys.argv[4]) PROFILE = "azadi.gold"
def __main__(): def __main__():
......
...@@ -4,8 +4,8 @@ import sys ...@@ -4,8 +4,8 @@ import sys
username = str(sys.argv[1]) username = str(sys.argv[1])
password = str(sys.argv[2]) 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" mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "azadi-gold-backend" database_name = "instagram-lottry"
PROFILE = str(sys.argv[3]) PROFILE = str(sys.argv[3])
......
...@@ -5,8 +5,8 @@ import sys ...@@ -5,8 +5,8 @@ import sys
username = str(sys.argv[1]) username = str(sys.argv[1])
password = str(sys.argv[2]) 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" mongo_connection_string = "mongodb://instagram:wcD3B5sGw0yQ@185.231.180.248:27017/instagram-lottry?authSource=admin&authMechanism=SCRAM-SHA-256"
database_name = "azadi-gold-backend" database_name = "instagram-lottry"
post_short_code = str(sys.argv[3]) post_short_code = str(sys.argv[3])
PROFILE = str(sys.argv[4]) PROFILE = str(sys.argv[4])
......
...@@ -6,9 +6,13 @@ export type LottoryResultDocument = LottoryResult & Document; ...@@ -6,9 +6,13 @@ export type LottoryResultDocument = LottoryResult & Document;
@Schema({ timestamps: true }) @Schema({ timestamps: true })
export class LottoryResult { export class LottoryResult {
@Prop() @Prop()
index: number; _id: Types.ObjectId
@Prop() @Prop()
username: string; index: string;
@Prop({ type: Types.ObjectId, ref: 'User' })
user_id: Types.ObjectId
// @Prop() // @Prop()
// tagged_user: string; // tagged_user: string;
@Prop() @Prop()
......
...@@ -29,6 +29,8 @@ export class LotteryController { ...@@ -29,6 +29,8 @@ export class LotteryController {
@Post('weekly/change-status') @Post('weekly/change-status')
async changeStatus(@Body() changeStatusDto: ChangeStatusDto) { async changeStatus(@Body() changeStatusDto: ChangeStatusDto) {
console.log('here');
return await this.lotteryService.changeStatus(changeStatusDto) return await this.lotteryService.changeStatus(changeStatusDto)
} }
} }
import { HttpException, Injectable } from '@nestjs/common'; import { HttpException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose'; import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose'; import { Model, Types } from 'mongoose';
import { of } from 'rxjs' import { of } from 'rxjs'
import { CommentDocument } from 'src/instagram/models/comment.schema'; import { CommentDocument } from 'src/instagram/models/comment.schema';
import { FollowerDocument } from 'src/instagram/models/follower.schema'; import { FollowerDocument } from 'src/instagram/models/follower.schema';
...@@ -39,52 +39,55 @@ export class LotteryService { ...@@ -39,52 +39,55 @@ export class LotteryService {
async addResultsToDB(profileUsername: string, postArray: string[]) { async addResultsToDB(profileUsername: string, postArray: string[]) {
await this.lotteryResultModel.deleteMany({}) await this.lotteryResultModel.deleteMany({})
let foundUsernameInComment = await this.commentModel.distinct('owner_username') let foundPost
let foundUsernameInLike = await this.likeModel.distinct('username') let foundUsernameInComment = await this.commentModel.distinct('user_id')
let foundUsernames = new Array<string>() let foundUsernameInLike = await this.likeModel.distinct('user_id')
foundUsernameInComment.forEach((username) => { let foundUser_id = new Array<any>()
if (!foundUsernames.includes(username)) { foundUsernameInComment.forEach((user_id) => {
foundUsernames.push(username) if (!foundUser_id.includes(user_id)) {
foundUser_id.push(user_id)
} }
}) })
foundUsernameInLike.forEach((username) => { foundUsernameInLike.forEach((user_id) => {
if (!foundUsernames.includes(username)) { if (!foundUser_id.includes(user_id)) {
foundUsernames.push(username) foundUser_id.push(user_id)
} }
}) })
console.log(foundUsernames); console.log(foundUser_id);
const comptitionArray = new Array<any>(); const comptitionArray = new Array<any>();
let index = 1000; let index = 1000;
let totalItems = foundUsernames.length let totalItems = foundUser_id.length
let count = 0 let count = 0
for await (const username of foundUsernames) { for await (const user_id of foundUser_id) {
let userScore = await this.scoreService.calculateUserScore(username, profileUsername, postArray) let userScore = await this.scoreService.calculateUserScore(user_id, profileUsername, postArray)
for (let u = 0; u < userScore; u++) { for (let u = 0; u < userScore; u++) {
comptitionArray.push({ await this.lotteryResultModel.create({
index, _id: new Types.ObjectId(),
username: username, index: `LT_${index}`,
user_id: user_id,
status: 'valid'
}) })
index++; index++;
console.log(`username:${username} , index: ${index}, score:${userScore}`); console.log(`user_id:${user_id} , index: ${index}, score:${userScore}`);
} }
console.log(`user index:${count} , total items: ${totalItems}`); console.log(`user index:${count} , total items: ${totalItems}`);
count++ count++
} }
await this.lotteryResultModel.insertMany(comptitionArray);
return 'successfull'; return 'successfull';
} }
async getResultDb() { async getResultDb() {
return await this.lotteryResultModel return await this.lotteryResultModel
.find() .find().populate("user_id",{"username":1},"User").sort({"status":1})
.select({ username: 1, index: 1 , status: 1}); .select({ username: 1, index: 1 , status: 1});
} }
async changeStatus(changeStatus: ChangeStatusDto){ async changeStatus(changeStatus: ChangeStatusDto){
let foundUser = await this.userModel.findOne({username: changeStatus.username})
let foundLottryResults = await this.lotteryResultModel.find({ let foundLottryResults = await this.lotteryResultModel.find({
username: changeStatus.username user_id: foundUser._id
}) })
for await (const result of foundLottryResults) { for await (const result of foundLottryResults) {
result.status = "online" result.status = "online"
......
...@@ -24,25 +24,15 @@ export class ScoreService { ...@@ -24,25 +24,15 @@ export class ScoreService {
) { } ) { }
async getUserLikesScore(username: string, profileUsername: string, postArray: string[]) { async getUserLikesScore(user_id: string, profileUsername: string, postArray: string[]) {
let foundUser = await this.userModel.findOne({ username })
let foundProfile = await this.userModel.findOne({ username: profileUsername }) let foundLikes = await this.likeModel.find({ user_id: new Types.ObjectId(user_id) })
let foundFollower = await this.followerModel.findOne({ return foundLikes.length
$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[]) { async getUserCommentsScore(user_id: string, profileUsername: string, postArray: string[]) {
let userCommentScore = new Array<{ post_id: string, post_score: number }>() let userCommentScore = new Array<{ post_id: string, post_score: number }>()
...@@ -53,7 +43,7 @@ export class ScoreService { ...@@ -53,7 +43,7 @@ export class ScoreService {
}) })
}) })
let foundUserComments = await this.commentModel.find({ owner_username: username }) let foundUserComments = await this.commentModel.find({ user_id: new Types.ObjectId(user_id) })
for await (const comment of foundUserComments) { for await (const comment of foundUserComments) {
......
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