DongCheDiCrawl.java
27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package cn.fw.freya.service.crawl.impl;
import cn.fw.freya.common.BusinessException;
import cn.fw.freya.dao.AccountDao;
import cn.fw.freya.dao.LivePoolDao;
import cn.fw.freya.dao.VideoPoolDao;
import cn.fw.freya.enums.AccountTypeEnum;
import cn.fw.freya.enums.ResourceTypeEnum;
import cn.fw.freya.model.data.Account;
import cn.fw.freya.model.data.FwCookie;
import cn.fw.freya.model.data.pool.LivePool;
import cn.fw.freya.model.data.pool.VideoPool;
import cn.fw.freya.service.crawl.CrawlStrategy;
import cn.fw.freya.service.data.AccountService;
import cn.fw.freya.utils.DateUtil;
import cn.fw.freya.utils.RequestUtil;
import cn.fw.freya.utils.http.HttpConfig;
import cn.fw.freya.utils.http.HttpHeader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author unknown
* @version 1.0
* @date 2022/2/14 15:28
* @Description
*/
@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings("Duplicates")
public class DongCheDiCrawl implements CrawlStrategy {
private final VideoPoolDao videoPoolDao;
private final LivePoolDao livePoolDao;
private final AccountDao accountDao;
private final Common common;
public final static ConcurrentHashMap<String, WebDriver> DRIVER_MAP = new ConcurrentHashMap<>();
private final AccountService accountService;
/**
* 账户类型(1:快手, 2:抖音, 3:懂车帝, 4:Bilibili)
*
* @return
*/
@Override
public AccountTypeEnum getType() {
return AccountTypeEnum.DCD;
}
/**
* 登陆准备
*
* @param accountNo 账户号
* @return
*/
@Override
public String preLogin(String accountNo) {
WebDriver driver = DRIVER_MAP.get(accountNo);
try {
if (Objects.isNull(driver)) {
driver = common.createDriver();
DRIVER_MAP.put(accountNo, driver);
}
driver.get("https://mp.toutiao.com/auth/page/login");// 打开指定的页面
WebElement qrCodeEle = new WebDriverWait(driver, 10, 300).until(driver1 ->
driver1.findElement(By.xpath("//div[contains(@class,'web-login-scan-code__content__qrcode-wrapper')]/img")));// 获取网页'登录二维码'元素对象
return qrCodeEle.getAttribute("src");// 返回对象src属性对应的值
} catch (Exception e) {
log.error("获取头条登录二维码发生错误", e);
if (Objects.nonNull(driver)) {
driver.quit();
DRIVER_MAP.remove(accountNo);
}
throw new BusinessException(e.getMessage());
}
}
/**
* 登陆
*
* @param accountNo 账户号
* @return
*/
@Override
public boolean doLogin(String accountNo) {
WebDriver driver = DRIVER_MAP.get(accountNo);
if (Objects.isNull(driver)) {
throw new BusinessException("登陆校验失败,请重新尝试");
}
if (!Objects.equals(driver.getCurrentUrl(), "https://mp.toutiao.com/auth/page/login")) {
final JSONObject userInfo = this.getUserInfo(accountNo, this.processCookiesToString(common.getTempCookies(driver, accountNo, this.getType().getValue())));
assert userInfo != null;
if (Objects.equals(accountNo, userInfo.get("ttId"))) {
common.saveCookie(driver, accountNo, this.getType().getValue());
accountService.updateAccountCookiesStatus(accountNo, this.getType().getValue(), true);
this.exitBrowser(accountNo, null);
return true;
} else {
this.exitBrowser(accountNo, null);
throw new BusinessException("实际扫码人员与指定扫码人员不同");
}
}
throw new BusinessException("登陆校验失败,请刷新二维码后重新扫码");
}
/**
* 获取今日头条资源
*
* @param accountNo 账户号
* @param resourceType 资源类型(1:文章, 2:视频, 3:微头条, 4:问答, 5:小视频)
* @return
*/
private JSONObject getJRTTResource(String accountNo, Integer resourceType) {
Map<String, Object> params = new HashMap<>();
params.put("type", resourceType);
params.put("page_size", 150);
params.put("page_num", 1);
params.put("app_id", 1231);
HttpConfig config = HttpConfig.custom()
.url("https://mp.toutiao.com/mp/agw/statistic/v2/item/list")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://mp.toutiao.com")// 非必须
.referer("https://mp.toutiao.com/profile_v4/analysis/works-single/small_video")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
throw new BusinessException("调用头条[" + (Objects.equals(resourceType, 1) ? "文章" :
Objects.equals(resourceType, 2) ? "视频" :
Objects.equals(resourceType, 3) ? "微头条" :
Objects.equals(resourceType, 4) ? "问答" : "小视频") + "]接口失败");
}
return response;
}
/**
* 获取所有视频信息
*
* @param accountNo 账户号
* @return
*/
@Override
@Transactional
public List<VideoPool> getAllVideoMsg(String accountNo) {
final List<VideoPool> hasFoundVideo = common.getHasFoundVideo(accountNo, this.getType().getValue(), DateUtil.getThisDayMinTime(new Date()));
if (Objects.nonNull(hasFoundVideo)) {
return hasFoundVideo;
}
Date previousDay = DateUtil.getPreviousDay(new Date());
final JSONObject response = this.getJRTTResource(accountNo, 2);
assert response != null;
JSONArray videoJsonArray = Optional.ofNullable(response.getJSONArray("item_datas")).orElse(new JSONArray());// 获取[视频]数据数组
final JSONObject response1 = this.getJRTTResource(accountNo, 5);
assert response1 != null;
JSONArray smallVideoJsonArray = Optional.ofNullable(response1.getJSONArray("item_datas")).orElse(new JSONArray());// 获取[小视频]数据数组
videoJsonArray.addAll(smallVideoJsonArray);
videoPoolDao.deleteByPhoneNoAndDate(accountNo, previousDay, this.getType().getValue(), ResourceTypeEnum.VIDEO.getValue());
// 视频数据存库
List<VideoPool> videoPoolList = new ArrayList<>(videoJsonArray.size());
log.info(String.format("%s [%s]平台账户号为: %s的视频数据的原始数据为: %s", LocalDateTime.now(), this.getType().getName(), accountNo, JSON.toJSONString(videoJsonArray)));
videoJsonArray.forEach(item -> {
JSONObject obj = (JSONObject) item;
JSONObject detailsObj = obj.getJSONObject("item_stat");
JSONObject playObj = detailsObj.getJSONObject("consume_data");
JSONObject DCSObj = detailsObj.getJSONObject("interaction_data");
JSONObject fullPlayObj = detailsObj.getJSONObject("consume_detail");
Integer playCount = Optional.ofNullable(playObj.getInteger("play_count")).orElse(0);// 播放次数
final String videoId = Optional.ofNullable(obj.getString("item_id")).orElse("");
int fullPlayCount;
try {
final BigDecimal[] bigDecimals = fullPlayObj.getBigDecimal("read_complete_rate")
.multiply(BigDecimal.valueOf(playCount))
.divideAndRemainder(BigDecimal.valueOf(100));
fullPlayCount = bigDecimals[0].intValue();
if (bigDecimals[1].compareTo(BigDecimal.ZERO) > 0) {
fullPlayCount++;
}
} catch (Exception e) {
log.error("[懂车帝]计算[fullPlayCount]指标发生错误", e);
fullPlayCount = 0;
}
videoPoolList.add(VideoPool.builder()
.videoId(videoId)// 视频id
.title(Optional.ofNullable(obj.getString("title")).orElse(""))// 视频标题
.preview(obj.getString("cover_url"))// 封面图
.playCount(playCount)// 播放次数
.likeCount(Optional.ofNullable(DCSObj.getInteger("digg_count")).orElse(0))// 点赞数
.commentCount(Optional.ofNullable(DCSObj.getInteger("comment_count")).orElse(0))// 评论数
.phoneNo(accountNo)
.reportDate(new Date())
.publishTime(new Date(obj.getLong("create_time") * 1000L))// 发布时间
.videoUrl("https://www.ixigua.com/" + videoId)// 播放地址
.type(this.getType().getValue())
.resourceType(ResourceTypeEnum.VIDEO.getValue())
.fullPlayCount(fullPlayCount)// 完整播放数
.duration(Optional.ofNullable(obj.getDouble("duration")).orElse(0d))
.newFansUserCnt(Optional.ofNullable(detailsObj.getInteger("fans_change_count")).orElse(0))// 增粉数
.shareCount(Optional.ofNullable(DCSObj.getInteger("share_count")).orElse(0))// 分享数
.build());
});
try {
if (videoPoolList.size() > 0) {
videoPoolDao.saveAll(videoPoolList);// 将收集到的视频信息保存
} else {
final VideoPool nullVideo = VideoPool.builder()
.phoneNo(accountNo)
.type(this.getType().getValue())
.resourceType(ResourceTypeEnum.VIDEO.getValue())
.reportDate(new Date())
.build();
videoPoolDao.save(nullVideo);
final ArrayList<VideoPool> nullList = new ArrayList<>();
//nullList.add(nullVideo);
return nullList;
}
} catch (Exception e) {
log.error(LocalDate.now() + " 执行保存" + accountNo + "的懂车帝视频数据失败", e);
}
return videoPoolList;
}
/**
* 获取昨日所有直播信息
*
* @param accountNo 账户号
* @return
*/
@Override
public List<LivePool> getYesterdayLiveMsg(String accountNo) {
List<LivePool> livePoolList = new ArrayList<>();
final List<LivePool> hasFoundLive = common.getHasFoundLive(accountNo, this.getType().getValue(), DateUtil.getThisDayMinTime(new Date()));
if (Objects.nonNull(hasFoundLive)) {
return hasFoundLive;
}
final JSONObject userInfo = this.getUserInfo(accountNo);
Map<String, Object> params = new HashMap<>();
params.put("Limit", 15);
params.put("Offset", 0);
HttpConfig config = HttpConfig.custom()
.url("https://live.ixigua.com/anchor-center/api/v1/videoroom/video-room-list")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://mp.dcdapp.com")// 非必须
.referer("https://live.ixigua.com/anchor-center/common/settings/roomlist")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);
log.info(String.format("%s [%s]平台账户号为: %s的直播数据的原始数据为: %s", LocalDateTime.now(), this.getType().getName(), accountNo, res));
JSONObject response = new JSONObject();
try {
response = JSONObject.parseObject(res);
} catch (Exception e) {
log.info(LocalDate.now() + " 暂未找到账户号为:" + accountNo + "的懂车帝直播数据");
final LivePool nullLive = LivePool.builder()
.type(this.getType().getValue())
.phoneNo(accountNo)
.reportDate(new Date())
.build();
livePoolDao.save(nullLive);
return livePoolList;
}
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
log.error("调用懂车帝[直播列表]接口失败");
throw new BusinessException("调用懂车帝[直播列表]接口失败");
}
JSONArray roomList = response.getJSONObject("data").getJSONObject("data").getJSONArray("Rooms");
JSONArray mctLiveDetails = this.getMCTLiveDetails(accountNo, LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN).toEpochSecond(ZoneOffset.of("+8")));
final LocalDate yesterday = LocalDate.now().minusDays(1);
final long yesterdaySecond = LocalDateTime.of(yesterday, LocalTime.MIN).toInstant(ZoneOffset.of("+8")).toEpochMilli();
roomList.forEach(item -> {
final JSONObject obj = (JSONObject) item;
final JSONObject roomStats = obj.getJSONObject("RoomStats");
final long createTime = Optional.ofNullable(obj.getLong("CreateTime")).orElse(0L) * 1000L;
final long finishTime = Optional.ofNullable(obj.getLong("FinishTime")).orElse(0L) * 1000L;
final Double duration = (finishTime - createTime) / 1000 / 60d;
if (createTime < yesterdaySecond) {
return;
}
Integer watchCnt = null;
Integer commentCnt = null;
Integer newFansCnt = null;
assert mctLiveDetails != null;
for (Object liveDetail : mctLiveDetails) {
final JSONObject obj1 = (JSONObject) liveDetail;
if (Objects.equals(DateUtil.stringToDateTime(obj1.getString("live_start_time")).getTime(), createTime)) {
watchCnt = obj1.getInteger("watch_cnt");
commentCnt = obj1.getInteger("comment_cnt");
newFansCnt = obj1.getInteger("new_fans_cnt");
}
}
assert userInfo != null;
livePoolList.add(LivePool.builder()
.type(this.getType().getValue())
.phoneNo(accountNo)
.reportDate(new Date())
.commentUserCnt(commentCnt)// 评论数
//.consumeUserCnt(Optional.ofNullable(obj.getInteger("sendGiftUv")).orElse(0))
.duration(duration)// 持续时间
//.income(Optional.ofNullable(obj.getDouble("receiveAmount")).orElse(0d))
.newFansUserCnt(newFansCnt)// 增粉数
.openTime(new Date(createTime))// 开播时间
.endTime(new Date(finishTime))// 下播时间
.roomCoverImage(Optional.ofNullable(obj.getString("CoverURL")).orElse(""))// 封面图
.roomId(Optional.ofNullable(obj.getString("RoomIDStr")).orElse(""))// 直播间id
.roomName(Optional.ofNullable(obj.getString("Title")).orElse(""))// 直播间标题
.watchPeakUserCnt(Optional.ofNullable(roomStats.getInteger("EnterCount")).orElse(0) / 20)// 峰值人数???
.watchUserCnt(watchCnt)// 观看人数
//.shareCnt(Optional.ofNullable(obj.getInteger("shareUv")).orElse(0))
//.likeCnt(Optional.ofNullable(obj.getInteger("likeCnt")).orElse(0))
.userNick(Optional.ofNullable(userInfo.getString("userNick")).orElse(""))// 用户昵称
.getPlaybackFailTimes(0)
.build());
});
Date previousDay = DateUtil.getPreviousDay(new Date());
Date endTime = DateUtil.getThisDayMaxTime(previousDay);
Date startTime = DateUtil.getThisDayMinTime(previousDay);
try {
if (livePoolList.size() > 0) {
livePoolDao.saveAll(livePoolList.stream()
.filter(item -> item.getOpenTime().compareTo(startTime) >= 0 && item.getOpenTime().compareTo(endTime) <= 0)
.collect(Collectors.toList())
);
} else {
log.info(LocalDate.now() + " 暂未找到账户号为:" + accountNo + "的懂车帝直播数据");
final LivePool nullLive = LivePool.builder()
.type(this.getType().getValue())
.phoneNo(accountNo)
.reportDate(new Date())
.build();
livePoolDao.save(nullLive);
//livePoolList.add(nullLive);
}
} catch (Exception e) {
log.error(LocalDate.now() + " 执行保存" + accountNo + "的懂车帝直播数据失败", e);
}
return livePoolList;
}
/**
* 更新账户粉丝数
*
* @param accountNo 账户号
* @return
*/
@Override
public Integer updateAccountFans(String accountNo) {
final Integer hasFoundFansCnt = common.getHasFoundFansCnt(accountNo, this.getType().getValue(), DateUtil.getThisDayMinTime(new Date()));
if (Objects.nonNull(hasFoundFansCnt)) {
return hasFoundFansCnt;
}
final String userId;
try {
userId = Objects.requireNonNull(this.getUserInfo(accountNo)).getString("userId");
} catch (NullPointerException e) {
return null;
}
Map<String, Object> params = new HashMap<>();
params.put("uid", userId);
params.put("app_name", "automobile");
params.put("date", LocalDate.now().minusDays(1));
HttpConfig config1 = HttpConfig.custom()
.url("https://mp.dcdapp.com/motor/pugc/serv/mp_analysis/fans/" + userId + "/overview")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://mp.dcdapp.com")// 非必须
.referer("https://mp.dcdapp.com/profile_v2/analysis/fans/dcd")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res1 = RequestUtil.get(config1);
final JSONObject response1 = JSONObject.parseObject(res1);
if (this.verifyCookies(response1)) {
return null;
}
if (!StringUtils.hasText(res1)) {
log.error("调用懂车帝[粉丝]接口失败");
throw new BusinessException("调用懂车帝[粉丝]接口失败");
}
final JSONArray data = response1.getJSONArray("data");
for (Object item : data) {
JSONObject obj = (JSONObject) item;
if (obj.getString("title").contains("总数")) {
final Integer fansCnt = obj.getInteger("data");
final Account account = accountDao.findByPhoneNoAndType(accountNo, this.getType().getValue());
if (Objects.nonNull(account)) {
accountDao.updateFans(account.getId(), fansCnt, new Date());
} else {
accountDao.save(Account.builder()
.cookiesStatus(true)
.phoneNo(accountNo)
.type(this.getType().getValue())
.fansCnt(fansCnt)
.reportDate(new Date())
.done(false)
.build());
}
return fansCnt;
}
}
return null;
}
/**
* 根据账户号获取账户信息
*
* @param accountNo 懂车帝账户号
* @return
*/
private JSONObject getUserInfo(String accountNo, String... cookies) {
String cookiesString;
if (cookies.length > 0) {
cookiesString = cookies[0];
} else {
cookiesString = this.getUserCookies(accountNo);
}
Map<String, Object> params = new HashMap<>();
params.put("app_id", 1231);
HttpConfig config = HttpConfig.custom()
.url("https://mp.toutiao.com/mp/agw/creator_center/user_info")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://mp.toutiao.com/")// 非必须
.referer("https://mp.toutiao.com/profile_v4/personal/info")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(cookiesString)
.build()
);
String res = RequestUtil.get(config);
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
log.error("调用头条号[用户信息]接口失败");
throw new BusinessException("调用头条号[用户信息]接口失败");
}
JSONObject obj = new JSONObject();
obj.put("userId", response.getString("user_id"));
obj.put("ttId", response.getString("media_id"));
obj.put("userNick", response.getString("name"));
return obj;
}
/**
* 根据账户号获取卖车通直播信息
*
* @param accountNo 懂车帝账户号
* @return
*/
private JSONArray getMCTLiveDetails(String accountNo, Long startTimeStamp) {
Map<String, Object> params = new HashMap<>();
params.put("start_time", startTimeStamp);
params.put("end_time", startTimeStamp + 24 * 3600 - 1);
params.put("offset", 0);
params.put("limit", 50);
params.put("from_mct", "pc");
HttpConfig config = HttpConfig.custom()
.url("https://mct.dcdapp.com/live/data/live_detail")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://mct.dcdapp.com/")// 非必须
.referer("https://mct.dcdapp.com/dashboard")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
log.error("调用卖车通[直播信息]接口失败");
throw new BusinessException("调用卖车通[直播信息]接口失败");
}
return response.getJSONObject("data").getJSONArray("list");
}
/**
* 进入指定账户号的创作者平台首页
*
* @param accountNo 懂车帝账户号
*/
public void loginIndex(String accountNo) {
final String uuid = UUID.randomUUID().toString().replace("-", "");
final WebDriver driver = this.getDCDDriver(accountNo, uuid);
String targetUrl = "https://mp.toutiao.com/profile_v4/index";
try {
driver.get(targetUrl);
} catch (Exception e) {
this.exitBrowser(accountNo, uuid);
throw new BusinessException("跳转页面发生异常");
}
this.exitBrowser(accountNo, uuid);
}
/**
* 将懂车帝账户的cookies放入driver中
*
* @param accountNo
* @return
*/
private WebDriver getDCDDriver(String accountNo, String uuid) {
WebDriver driver = common.createDriver();
try {
driver.get("https://www.dongchedi.com/");
Set<Cookie> cookieSet = common.loadCookie(accountNo, this.getType().getValue())
.stream()
.map(FwCookie::seleniumCookie)
.collect(Collectors.toSet());
cookieSet.forEach(item -> driver.manage().addCookie(item));// 给driver加载账户的cookies;
DRIVER_MAP.put(accountNo + "#" + uuid, driver);
return driver;
} catch (Exception e) {
driver.close();
throw new BusinessException("创建懂车帝驱动发生异常: " + e.getMessage());
}
}
/**
* 根据账户号查到用户cookies, 并组装成String形式返回
*
* @param phoneNo 账户号
* @return
*/
public String getUserCookies(String phoneNo) {
return this.processCookiesToString(common.loadCookie(phoneNo, this.getType().getValue()));
}
/**
* 将cookies处理成字符串
*
* @return
*/
private String processCookiesToString(List<FwCookie> cookies) {
StringBuffer sb = new StringBuffer();
cookies.forEach(item -> {
sb.append(item.getName()).append("=").append(item.getValue()).append(";");
});
return sb.toString();
}
/**
* 验证账户cookies是否失效
*
* @param response
* @return
*/
public boolean verifyCookies(JSONObject response) {
if (Objects.nonNull(response)) {
try {
final Integer resultCode = response.getInteger("code");
final String loginMsg = response.getString("message");
if (Objects.equals(100004, resultCode) || Objects.equals(loginMsg, "user not login") || Objects.equals(30002, resultCode) || Objects.equals(loginMsg, "登陆过期,请重新登陆")) {
return true;
} else {
return false;
}
} catch (Exception e) {
throw new BusinessException("验证懂车帝cookies发生异常: " + e.getMessage());
}
} else {
log.error("调用懂车帝平台接口未接收到返回值");
throw new BusinessException("调用懂车帝平台接口未接收到返回值");
}
}
/**
* 退出浏览器
*
* @param accountNo 账户号
* @return
*/
public boolean exitBrowser(String accountNo, String uuid) {
String key = accountNo + (Objects.nonNull(uuid) ? "#" + uuid : "");
WebDriver driver = DRIVER_MAP.get(key);
if (Objects.isNull(driver)) {
return true;
}
driver.close();
DRIVER_MAP.remove(key);
return true;
}
}