返回 AiToEarn
account.service.ts
根目录 / project / aitoearn-electron / server / src / modules / account / account.service.ts
1 import { forwardRef, Inject, Injectable } from '@nestjs/common';
2 import { InjectModel } from '@nestjs/mongoose';
3 import { Model } from 'mongoose';
4 import { Account, AccountType } from '../../db/schema/account.schema';
5 import { IdService } from 'src/db/id.service';
6
7 import { AccountGroupService } from './accountGroup/accountGroup.service';
8
9 @Injectable()
10 export class AccountService {
11
12 constructor(
13 @InjectModel(Account.name)
14 private readonly accountModel: Model<Account>,
15
16 private readonly idService: IdService,
17 @Inject(forwardRef(() => AccountGroupService))
18 private readonly accountGroupService: AccountGroupService,
19 ) {
20 }
21
22 private async getId() {
23 return this.idService.createId('accountId', 100000000, 1);
24 }
25
26 /**
27 * 将用户组下的账户切换到默认组
28 * @param userId
29 * @param groupId
30 * @param defaultGroupId
31 */
32 async switchToDefaultGroup(
33 userId: string,
34 groupId: number,
35 defaultGroupId: number,
36 ) {
37 return this.accountModel.updateMany(
38 { userId, groupId: { $ne: groupId } },
39 { groupId: defaultGroupId },
40 );
41 }
42
43 /**
44 * 添加或更新账号
45 * @param account
46 * @returns
47 */
48 async addOrUpdateAccount(account: Partial<Account>): Promise<Account> {
49 const existingAccount = await this.accountModel.findOne(
50 account.id
51 ? {
52 id: account.id,
53 }
54 : {
55 userId: account.userId,
56 uid: account.uid,
57 type: account.type,
58 },
59 );
60
61 if (existingAccount) {
62 return this.accountModel.findOneAndUpdate(
63 { id: existingAccount.id },
64 account,
65 {
66 new: true,
67 },
68 );
69 }
70
71 // 获取默认用户组
72 let defaultGrpoupId: number;
73 const defaultGroup = await this.accountGroupService.getDefaultGroup(
74 account.userId,
75 );
76 if (defaultGroup) {
77 defaultGrpoupId = defaultGroup.id;
78 } else {
79 // 如果没有默认用户组,则创建一个默认用户组
80 const newGroup = await this.accountGroupService.createDefaultGroup(
81 account.userId,
82 );
83 defaultGrpoupId = newGroup.id;
84 }
85
86 account.id = await this.getId();
87 account.groupId = defaultGrpoupId;
88 return this.accountModel.create(account);
89 }
90
91 /**
92 * 根据用户id获取账号
93 */
94 async getAccountById(id: number) {
95 return this.accountModel.findOne({ id });
96 }
97
98 /**
99 * 获取所有账户
100 * @param userId
101 * @returns
102 */
103 async getAccounts(userId: string) {
104 return await this.accountModel.find({
105 userId,
106 });
107 }
108
109 /**
110 * 根据ID数组ids获取账户列表数组
111 * @param userId
112 * @param ids
113 * @returns
114 */
115 async getAccountListByIds(userId: string, ids: number[]) {
116 return await this.accountModel.find({
117 userId,
118 id: { $in: ids },
119 });
120 }
121
122 /**
123 * 获取账户的统计信息
124 * @param userId
125 * @param type
126 * @returns
127 */
128 async getAccountStatistics(
129 userId: string,
130 type?: AccountType,
131 ): Promise<{
132 accountTotal: number;
133 list: Account[];
134 fansCount?: number;
135 readCount?: number;
136 likeCount?: number;
137 collectCount?: number;
138 commentCount?: number;
139 income?: number;
140 }> {
141 const accountList = await this.accountModel.find({
142 userId,
143 ...(type && { type }),
144 });
145
146 const res = {
147 accountTotal: accountList.length,
148 list: accountList,
149 fansCount: 0,
150 };
151
152 for (const element of accountList) {
153 // TODO: 获取统计信息
154 // const ret = await platController.getStatistics(element).catch((err) => {
155 // console.error(err);
156 // });
157 // res.fansCount += ret?.fansCount || 0;
158 }
159
160 return res;
161 }
162
163 /**
164 * 获取用户的账户总数
165 * @param userId
166 * @returns
167 */
168 async getAccountCount(userId: string) {
169 return await this.accountModel.countDocuments({ userId });
170 }
171
172 /**
173 * 根据多个账户id查询账户信息
174 * @param ids
175 * @returns
176 */
177 async getAccountsByIds(ids: number[]) {
178 return await this.accountModel.find({
179 id: { $in: ids },
180 });
181 }
182
183 /**
184 * 更新粉丝数量
185 * @param userId
186 * @param account
187 * @param fansCount
188 * @returns
189 */
190 async updateFansCount(userId: string, account: string, fansCount: number) {
191 return await this.accountModel.updateOne(
192 { userId, account },
193 { fansCount: fansCount },
194 );
195 }
196
197 // 获取用户的所有账户的总粉丝量
198 async getUserFansCount(userId: string) {
199 const accounts = await this.accountModel.find({ userId });
200 return accounts.reduce((acc, cur) => acc + (cur.fansCount || 0), 0);
201 }
202
203 /**
204 * 删除
205 * @param id
206 * @param userId
207 * @returns
208 */
209 async deleteAccount(id: number, userId: string): Promise<boolean> {
210 const res = await this.accountModel.deleteOne({
211 id,
212 userId: userId,
213 });
214
215 return res.deletedCount > 0;
216 }
217
218 // 删除多个账户
219 async deleteAccounts(ids: string[], userId: string) {
220 const res = await this.accountModel.deleteMany({
221 _id: { $in: ids },
222 userId,
223 });
224 return res.deletedCount > 0;
225 }
226
227 /**
228 * 更新用户状态
229 * @param id
230 * @param status
231 * @returns
232 */
233 async updateAccountStatus(id: number, status: number) {
234 return await this.accountModel.updateOne({ id }, { status });
235 }
236
237 // 更新账户的统计信息
238 async updateAccountStatistics(
239 id: number,
240 fansCount: number,
241 readCount: number,
242 likeCount: number,
243 collectCount: number,
244 commentCount: number,
245 income: number,
246 workCount: number,
247 ) {
248 return await this.accountModel.updateOne(
249 { id },
250 {
251 fansCount,
252 readCount,
253 likeCount,
254 collectCount,
255 commentCount,
256 income,
257 workCount,
258 },
259 );
260 }
261
262 // /**
263 // * Google登录
264 // * @param clientId Google客户端ID
265 // * @param credential Google认证凭证
266 // * @returns Account
267 // */
268 // async googleLogin(clientId: string, credential: string): Promise<any> {
269 // try {
270 // console.log('Verifying Google token with:');
271
272 // // 验证Google token
273 // const ticket = await this.googleClient.verifyIdToken({
274 // idToken: credential,
275 // audience: clientId,
276 // });
277 // console.log('ticket',ticket)
278 // const payload = ticket.getPayload();
279 // console.log('payload',payload)
280 // if (!payload) {
281 // throw new Error('Invalid Google token');
282 // }
283
284 // console.log('Google login success, payload:', payload);
285 // return payload;
286 // } catch (error) {
287 // console.error('Google login error:', error);
288 // throw new Error(`Google login failed: ${error.message}`);
289 // }
290 // }
291 }
292
292 lines TYPESCRIPT