Browse Source

任务列表刷新更新后台已发送数据;渠道多选和随机获取

wuyi 1 năm trước cách đây
mục cha
commit
9e151a1a57

+ 51 - 45
src/rcs-number/impl/mwze167.service.ts

@@ -37,54 +37,54 @@ export class mwze167 extends GetNumberService {
         let operatorName = 'TIM'
         let finalOperatorName = 'TIM'
         try {
-            if (taskId) {
+
+            let channel = null
+            if (channelId) {
+                channel = await this.channelRepository.findOneBy({ id: parseInt(channelId) })
+            } else if (taskId) {
                 const task: Task = await this.taskRepository.findOneBy({ id: parseInt(taskId) })
-                const channel: Channel = await this.channelRepository.findOneBy({ id: task.channelId })
-                cuy = channel.country.toUpperCase()
-                finalOperatorName = channel.operator
+                if (task.channelId) {
+                    const channelArray = task.channelId.split(',').map(Number)
+                    const randomIndex = Math.floor(Math.random() * channelArray.length)
+                    channel = await this.channelRepository.findOneBy({ id: channelArray[randomIndex] })
+                }
+            }
+            if (channel === null) {
+                // 从数据库中获取随机的channel
+                channel = await this.channelRepository.createQueryBuilder('channel')
+                    .orderBy('RAND()')
+                    .limit(1)
+                    .getOne()
+            }
+            cuy = channel.country.toUpperCase()
+            finalOperatorName = channel.operator
 
-                // 延迟
-                await new Promise((resolve) => setTimeout(resolve, 1000))
-                Logger.log(cuy, 'mwze167')
-                Logger.log(channel.operator, 'mwze167')
-                const res = await axiosInstance.get('getMobile', {
-                    params: {
-                        uid,
-                        sign,
-                        pid,
-                        cuy,
-                        size: 1,
-                        ctype: 3
-                    }
-                })
-                const data = res.data
-                Logger.log(data, 'mwze167')
-                number = data.data[0]?.number
-                orderId = data.orderId
+            // 延迟
+            await new Promise((resolve) => setTimeout(resolve, 1000))
+            Logger.log(cuy, 'mwze167')
+            Logger.log(channel.operator, 'mwze167')
+            const res = await axiosInstance.get('getMobile', {
+                params: {
+                    uid,
+                    sign,
+                    pid,
+                    cuy,
+                    size: 1,
+                    ctype: 3
+                }
+            })
+            const data = res.data
+            Logger.log(data, 'mwze167')
+            number = data.data[0]?.number
+            orderId = data.orderId
 
-                const jsonString: string = data.data[0]?.mcc
-                const parsedObject = JSON.parse(jsonString)
+            const jsonString: string = data.data[0]?.mcc
+            const parsedObject = JSON.parse(jsonString)
 
-                mnc = channel.mnc
-                mcc = channel.mcc
-                operatorName = parsedObject?.operatorName
-                console.log(`mnc: ${mnc}, mcc: ${mcc}, operatorName: ${operatorName}`)
-            } else {
-                const res = await axiosInstance.get('getMobile', {
-                    params: {
-                        uid,
-                        sign,
-                        pid,
-                        cuy,
-                        size: 1,
-                        ctype: 2
-                    }
-                })
-                const data = res.data
-                Logger.log(data, 'mwze167')
-                number = data.data[0]?.number
-                orderId = data.orderId
-            }
+            mnc = channel.mnc
+            mcc = channel.mcc
+            operatorName = parsedObject?.operatorName
+            console.log(`mnc: ${mnc}, mcc: ${mcc}, operatorName: ${operatorName}`)
 
         } catch (e: any) {
             if (e.response) {
@@ -120,13 +120,19 @@ export class mwze167 extends GetNumberService {
                     throw new HttpException('Invalid Vietnamese number', 500)
                 }
                 break
+            case 'IN':
+                // 印度,号码为10位
+                if (!/^\d{10}$/.test(number)) {
+                    throw new HttpException('Invalid Indian number', 500)
+                }
+                break
             default:
                 throw new HttpException('Invalid number', 500)
         }
         if (operatorName === finalOperatorName) {
             Logger.log(`Operator name matches. Continuing...`, 'mwze167')
         } else {
-            throw new HttpException('Operator name matches.', 500)
+            throw new HttpException('Operator name not matches.', 500)
         }
         const rcsNumber = new RcsNumber()
         rcsNumber.mcc = mcc

+ 1 - 0
src/rcs-number/rcs-number.service.ts

@@ -22,6 +22,7 @@ export class RcsNumberService {
 
     async create(deviceId?: string, taskId?: string, channelId?: string): Promise<RcsNumber> {
         console.log('taskId', taskId)
+        console.log('channelId', channelId)
         return await this.mwze167.getNumber(deviceId, taskId, channelId)
     }
 

+ 1 - 1
src/task/entities/task.entity.ts

@@ -53,5 +53,5 @@ export class Task {
     requestNumberInterval: number
 
     @Column({ nullable: false })
-    channelId: number
+    channelId: string
 }

+ 78 - 53
src/task/task.service.ts

@@ -43,7 +43,36 @@ export class TaskService implements OnModuleInit {
     private taskControllers: { [key: number]: AbortController } = {}
 
     async findAllTask(req: PageRequest<Task>): Promise<Pagination<Task>> {
-        return await paginate<Task>(this.taskRepository, req.page, req.search)
+        const result = await paginate<Task>(this.taskRepository, req.page, req.search)
+
+        const taskItems = result.items
+        if (taskItems.length > 0) {
+            for (const task of taskItems) {
+                if (task.status === TaskStatus.PENDING || (task.status === TaskStatus.COMPLETED && moment(task.createdAt).isSameOrAfter(moment().subtract(12, 'hours')))) {
+                    const id = task.id
+                    const successCount = await this.taskItemRepository.countBy({
+                        taskId: id,
+                        status: 'success'
+                    })
+                    const totalCount = await this.taskItemRepository.countBy({
+                        taskId: id
+                    })
+                    if (totalCount === 0) {
+                        throw new Error('No tasks found for the given taskId.')
+                    }
+                    // 计算成功率
+                    const successRate = ((successCount / totalCount) * 100).toFixed(1) + '%'
+                    task.successRate = String(successRate)
+                    const sendCount = await this.taskItemRepository.countBy({
+                        taskId: id,
+                        status: In(['success', 'fail'])
+                    })
+                    task.sent = sendCount
+                    await this.taskRepository.save(task)
+                }
+            }
+        }
+        return result
     }
 
     async findAllTaskItem(req: PageRequest<TaskItem>): Promise<Pagination<TaskItem>> {
@@ -76,63 +105,59 @@ export class TaskService implements OnModuleInit {
             task.status = TaskStatus.PENDING
             await this.taskRepository.save(task)
             await this.runTask(task)
+            
+            const newTask = await this.taskRepository.findOneBy({ id })
+            if ([TaskStatus.COMPLETED, TaskStatus.PAUSE].includes(newTask.status)) {
+                try {
+                    const successCount = await this.taskItemRepository.countBy({
+                        taskId: id,
+                        status: 'success'
+                    })
+                    const totalCount = await this.taskItemRepository.countBy({
+                        taskId: id
+                    })
+                    if (totalCount === 0) {
+                        throw new Error('No tasks found for the given taskId.')
+                    }
+                    // 计算成功率
+                    const successRate = ((successCount / totalCount) * 100).toFixed(1) + '%'
+                    newTask.successRate = String(successRate)
+                    const sendCount = await this.taskItemRepository.countBy({
+                        taskId: id,
+                        status: In(['success', 'fail'])
+                    })
+                    newTask.sent = sendCount
+                    await this.taskRepository.save(newTask)
 
-            let finish = false
-            while (!finish) {
-                // 每隔5s查询一次
-                await setTimeout(5000)
-                const newTask = await this.taskRepository.findOneBy({ id })
-                if ([TaskStatus.COMPLETED, TaskStatus.PAUSE].includes(newTask.status)) {
-                    try {
-                        const successCount = await this.taskItemRepository.countBy({
-                            taskId: id,
-                            status: 'success'
-                        })
-                        const totalCount = await this.taskItemRepository.countBy({
-                            taskId: id
-                        })
-                        if (totalCount === 0) {
-                            throw new Error('No tasks found for the given taskId.')
+                    // 获取用户信息
+                    const user = await this.userRepository.findOneBy({
+                        id: task.userId
+                    })
+                    // 已发送
+                    const send: number = user.send
+                    user.send = send + successCount
+                    // 费用 = 费率*成功发送
+                    const rate: number = user.rate
+                    const cost: number = rate * successCount
+                    // 从用户余额中减去费用 可能有余额不足的情况,后续优化
+                    const latestBalance: number = (user.balance || 0) - cost
+                    user.balance = latestBalance
+
+                    // 余额表更新
+                    const balance = await this.balanceRepository.findOne({
+                        where: {
+                            userId: task.userId
                         }
-                        // 计算成功率
-                        const successRate = ((successCount / totalCount) * 100).toFixed(1) + '%'
-                        newTask.successRate = String(successRate)
-                        const sendCount = await this.taskItemRepository.countBy({
-                            taskId: id,
-                            status: In(['success', 'fail'])
-                        })
-                        newTask.sent = sendCount
-                        await this.taskRepository.save(newTask)
+                    })
+                    balance.currentBalance = latestBalance
 
-                        // 获取用户信息
-                        const user = await this.userRepository.findOneBy({
-                            id: task.userId
-                        })
-                        // 已发送
-                        const send: number = user.send
-                        user.send = send + successCount
-                        // 费用 = 费率*成功发送
-                        const rate: number = user.rate
-                        const cost: number = rate * successCount
-                        // 从用户余额中减去费用 可能有余额不足的情况,后续优化
-                        const latestBalance: number = (user.balance || 0) - cost
-                        user.balance = latestBalance
+                    await this.balanceRepository.save(balance)
+                    await this.userRepository.save(user)
 
-                        // 余额表更新
-                        const balance = await this.balanceRepository.findOne({
-                            where: {
-                                userId: task.userId
-                            }
-                        })
-                        balance.currentBalance = latestBalance
-                        finish = true
-                        await this.balanceRepository.save(balance)
-                        await this.userRepository.save(user)
-                        break
-                    } catch (e) {
-                        Logger.error('Error startTask ', e, 'RcsService')
-                    }
+                } catch (e) {
+                    Logger.error('Error startTask ', e, 'RcsService')
                 }
+
             }
         }
     }