BilibiliCrawl.java
27.8 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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
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.model.dto.rpc.ReportAccountDto;
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.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author null
* @date 2021-11-11 17:15
* @description Bilibili数据抓取
*/
@Slf4j
@Service
@RequiredArgsConstructor
@SuppressWarnings("Duplicates")
public class BilibiliCrawl 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;
@Override
public AccountTypeEnum getType() {
return AccountTypeEnum.BILIBILI;
}
/**
* 获取Bilibili登录二维码
*
* @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://passport.bilibili.com/login");// 打开指定的页面
/*new WebDriverWait(driver, 10, 300).until(driver1 ->
driver1.findElement(By.xpath("//div[@class='header-login-entry']/span"))).click();// 获取'登录'按钮元素, 单击*/
WebElement qrCodeEle = new WebDriverWait(driver, 10, 300).until(driver1 ->
driver1.findElement(By.xpath("//img[contains(@alt,'Scan me')] | //div[@class='qrcode-img']/img")));// 获取网页'登录二维码'元素对象
return qrCodeEle.getAttribute("src");// 返回对象src属性对应的值
} catch (Exception e) {
log.error("获取Bilibili登录二维码发生错误", e);
if (Objects.nonNull(driver)) {
driver.quit();
DRIVER_MAP.remove(accountNo);
}
throw new BusinessException(e.getMessage());
}
}
/**
* 随意请求一个接口, 获取到浏览器cookies, 保存
*
* @param accountNo 账户号
* @return
* @throws BusinessException
*/
@Override
public boolean doLogin(String accountNo) throws BusinessException {
WebDriver driver = DRIVER_MAP.get(accountNo);
if (Objects.isNull(driver)) {
throw new BusinessException("登陆校验失败,请重新尝试");
}
if (!Objects.equals(driver.getCurrentUrl(), "https://passport.bilibili.com/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("userId"))) {
Integer type = this.getType().getValue();
common.saveCookie(driver, accountNo, type);
accountService.updateAccountCookiesStatus(accountNo, type, true);
common.whenLoginCheckAccountExist(accountNo, type);
this.exitBrowser(accountNo, null);
return true;
} else {
this.exitBrowser(accountNo, null);
throw new BusinessException("实际扫码人员与指定扫码人员不同");
}
}
throw new BusinessException("登陆校验失败,请刷新二维码后重新扫码");
}
/**
* 获取所有视频作品信息
*
* @param accountNo 账户号
* @throws IOException
*/
@Override
@Transactional
public List<VideoPool> getAllVideoMsg(String accountNo) throws IOException {
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());
Integer currentPage = 0;
Integer pageSize = 20;
Integer total;
JSONArray videoJsonArray = new JSONArray();
do {
currentPage++;
JSONObject response = this.getBILIBILIVideoPage(accountNo, currentPage, pageSize);
assert response != null;
final JSONObject responseObj = response.getJSONObject("data");
final JSONObject pageMsg = responseObj.getJSONObject("page");
total = pageMsg.getInteger("count");
pageSize = pageMsg.getInteger("ps");
final JSONArray tempList = responseObj.getJSONArray("arc_audits");
if (!CollectionUtils.isEmpty(tempList)) {
videoJsonArray.addAll(tempList);
}
} while (currentPage * pageSize < total);// 条件为false, 退出
log.info(String.format("%s [%s]平台账户号为: %s的视频数据的原始数据为: %s", LocalDateTime.now(), this.getType().getName(), accountNo, JSON.toJSONString(videoJsonArray)));
videoPoolDao.deleteByAccountNoAndDate(accountNo, previousDay, AccountTypeEnum.BILIBILI.getValue(), ResourceTypeEnum.VIDEO.getValue());
// 视频数据存库
List<VideoPool> videoPoolList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
videoJsonArray.forEach(item -> {
JSONObject obj = (JSONObject) item;
JSONObject stat = obj.getJSONObject("stat");
JSONObject Archive = obj.getJSONObject("Archive");
final String videoId = Optional.ofNullable(Archive.getString("bvid")).orElse("");
final Integer playCnt = Optional.ofNullable(stat.getInteger("view")).orElse(0);
final JSONObject videoDataDetails = this.getBILIBILIVideoDataDetails(accountNo, videoId);
final Double duration = Optional.ofNullable(Archive.getDouble("duration")).orElse(0d);
int fullPlayCount;
try {
assert videoDataDetails != null;
final BigDecimal[] bigDecimals = BigDecimal.valueOf(videoDataDetails.getJSONObject("data").getJSONObject("stat").getDouble("play_avg_duration"))
.divide(BigDecimal.valueOf(duration), 4, RoundingMode.HALF_UP)
.multiply(BigDecimal.valueOf(playCnt))
.divideAndRemainder(BigDecimal.ONE);
fullPlayCount = bigDecimals[0].intValue();
if (bigDecimals[1].compareTo(BigDecimal.ZERO) > 0) {
fullPlayCount++;
}
} catch (Exception e) {
log.error("[哔哩哔哩]计算[fullPlayCount]指标发生错误", e);
fullPlayCount = 0;
}
String title = sb.append(Archive.getString("title")).append("#").append(Archive.getString("tag").replace(",", "#")).toString();
videoPoolList.add(VideoPool.builder()
.videoId(videoId)//
.title(title)// 视频标题
.preview(Optional.ofNullable(Archive.getString("cover")).orElse(""))// 封面图
.playCount(playCnt)// 播放次数
.likeCount(Optional.ofNullable(stat.getInteger("like")).orElse(0))// 点赞数
.commentCount(Optional.ofNullable(stat.getInteger("reply")).orElse(0))// 评论数
.accountNo(accountNo)
.reportDate(new Date())
.publishTime(new Date(Archive.getLong("ctime") * 1000))// 发布时间
.videoUrl("https://www.bilibili.com/video/" + videoId)// 视频播放地址
.type(this.getType().getValue())
.resourceType(ResourceTypeEnum.VIDEO.getValue())
.fullPlayCount(fullPlayCount)// 完整播放次数
.duration(duration)// 持续时间
//.newFansUserCnt(Optional.ofNullable(obj.getInteger("increaseFansCount")).orElse(0))
.shareCount(Optional.ofNullable(stat.getInteger("share")).orElse(0))// 分享数
.build());
sb.setLength(0);
});
try {
if (videoPoolList.size() > 0) {
videoPoolDao.saveAll(videoPoolList);// 将收集到的视频信息保存
} else {
final VideoPool nullVideo = VideoPool.builder()
.accountNo(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 + "的Bilibili视频数据失败", e);
}
return videoPoolList;
}
/**
* 分页获取bilibili视频数据列表
*
* @param accountNo 账户号
* @param currentPage 当前页
* @param pageSize 每页大小
* @return 当前页Json数据
*/
private JSONObject getBILIBILIVideoPage(String accountNo, Integer currentPage, Integer pageSize) {
Map<String, Object> params = new HashMap<>();
params.put("status", "is_pubing,pubed,not_pubed");
params.put("pn", currentPage);
params.put("ps", pageSize);
params.put("coop", 1);
params.put("interactive", 1);
HttpConfig config = HttpConfig.custom()
.url("https://member.bilibili.com/x/web/archives")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://member.bilibili.com/")// 非必须
.referer("https://member.bilibili.com/platform/home")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);// 发送GET请求
this.waitFor(0.5);
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
throw new BusinessException("调用Bilibili[视频]接口失败");
}
return response;
}
/**
* 获取bilibili当前视频视频数据
*
* @param accountNo 账户号
* @param videoId 视频id
* @return 当前视频详情Json数据
*/
private JSONObject getBILIBILIVideoDataDetails(String accountNo, String videoId) {
Map<String, Object> params = new HashMap<>();
params.put("bvid", videoId);
params.put("t", System.currentTimeMillis());
HttpConfig config = HttpConfig.custom()
.url("https://member.bilibili.com/x/web/data/v2/archive/analyze/stat")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://member.bilibili.com/")// 非必须
.referer("https://member.bilibili.com/york/ct-data/articleAnalysis")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);// 发送GET请求
this.waitFor(0.1);
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
throw new BusinessException("调用Bilibili[单条视频数据详情]接口失败");
}
return response;
}
/**
* 获取昨天所有直播信息
*
* @param accountNo 账户号
* @throws Exception
*/
@Override
@Transactional
public List<LivePool> getYesterdayLiveMsg(String accountNo) throws IOException {
final List<LivePool> hasFoundLive = common.getHasFoundLive(accountNo, this.getType().getValue(), DateUtil.getThisDayMinTime(new Date()));
if (Objects.nonNull(hasFoundLive)) {
return hasFoundLive;
}
Date previousDay = DateUtil.getPreviousDay(new Date());
Date endTime = DateUtil.getThisDayMaxTime(previousDay);
Date startTime = DateUtil.getThisDayMinTime(previousDay);
Map<String, Object> params = new HashMap<>();
params.put("start_date", startTime.getTime() / 1000);
params.put("end_date", endTime.getTime() / 1000);
params.put("platform", "web");
params.put("page_num", 1);
params.put("page_size", 15);
HttpConfig config = HttpConfig.custom()
.url("https://api.live.bilibili.com/xlive/app-blink/v1/index/getSessionRecordList")
.setGetParams(params)
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://link.bilibili.com/")// 非必须
.referer("https://link.bilibili.com/p/center/index")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);// 发送GET请求
log.info(String.format("%s [%s]平台账户号为: %s的直播数据的原始数据为: %s", LocalDateTime.now(), this.getType().getName(), accountNo, res));
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
throw new BusinessException("调用Bilibili[直播]接口失败");
}
JSONObject dataJSONObject = response.getJSONObject("data").getJSONObject("date_info");
JSONArray dataJSONArray;
if (Objects.isNull(dataJSONObject)) {
dataJSONArray = new JSONArray();
} else {
dataJSONArray = dataJSONObject.getJSONArray("date_item_info");
}
List<LivePool> livePoolList = new ArrayList<>();
dataJSONArray.forEach(item -> {
final JSONObject obj = (JSONObject) item;
/**
* area_id: 145
* area_name: "视频聊天"
* -danmu_num: 0
* date: "2022-02-17"
* effective_viewing_time: 0
* -end_time: "2022-02-17 16:35:52"
* hamster: 50
* -hamster_rmb: 0.05
* -live_id: "210841344744381475"
* -live_time: 4192
* -max_online: 508
* -new_attention: 0
* new_fans_club: 0
* -start_time: "2022-02-17 15:26:00"
* -title: "长安汽车!"
* view_per_duration: 31
*/
livePoolList.add(LivePool.builder()
.type(this.getType().getValue())
.accountNo(accountNo)
.reportDate(new Date())
.commentUserCnt(Optional.ofNullable(obj.getInteger("danmu_num")).orElse(0))// 评论数
//.consumeUserCnt(Optional.ofNullable(obj.getInteger("sendGiftUv")).orElse(0))
.duration(Optional.ofNullable(obj.getDouble("live_time")).orElse(0d) / 60d)// 直播时长
.income(Optional.ofNullable(obj.getDouble("hamster_rmb")).orElse(0d))// 直播收益
.newFansUserCnt(Optional.ofNullable(obj.getInteger("new_attention")).orElse(0))// 增粉数
.openTime(DateUtil.stringToDateTime(obj.getString("start_time")))// 开播时间
.endTime(DateUtil.stringToDateTime(obj.getString("end_time")))// 下播时间
//.roomCoverImage(Optional.ofNullable(obj.getString("liveCover")).orElse(""))
.roomId(Optional.ofNullable(obj.getString("live_id")).orElse(""))// 直播间id
.roomName(Optional.ofNullable(obj.getString("title")).orElse(""))// 直播间标题
.getPlaybackFailTimes(0)
//.score(obj.getInteger("score"))
//.watchCnt(obj.getInteger("watch_cnt"))
//.watchPeakUserCnt(Optional.ofNullable(obj.getInteger("max_online")).orElse(0))// 在线峰值???
//.watchUserCnt(Optional.ofNullable(obj.getInteger("playUv")).orElse(0))
//.shareCnt(Optional.ofNullable(obj.getInteger("shareUv")).orElse(0))
//.likeCnt(Optional.ofNullable(obj.getInteger("likeCnt")).orElse(0))
//.userNick(Optional.ofNullable(obj.getString("userName")).orElse(""))
.build());
});
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 + "的Bilibili直播数据");
final LivePool nullLive = LivePool.builder()
.type(this.getType().getValue())
.accountNo(accountNo)
.reportDate(new Date())
.build();
livePoolDao.save(nullLive);
//livePoolList.add(nullLive);
}
} catch (Exception e) {
log.error(LocalDate.now() + " 执行保存" + accountNo + "的Bilibili直播数据失败", e);
}
return livePoolList;
}
/**
* 更新账户粉丝数
*
* @param accountNo
*/
@Override
@Transactional
public ReportAccountDto updateAccountMsg(String accountNo) throws IOException {
final ReportAccountDto hasFoundAccountMsg = common.getHasFoundAccountMsg(accountNo, this.getType().getValue(), DateUtil.getThisDayMinTime(new Date()));
if (Objects.nonNull(hasFoundAccountMsg)) {
return hasFoundAccountMsg;
}
HttpConfig config = HttpConfig.custom()
.url("https://member.bilibili.com/x/web/index/stat")
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://member.bilibili.com")// 非必须
.referer("https://member.bilibili.com/platform/home")// 非必须
.userAgent(this.getUserAgent(accountNo))// 非必须
.cookie(this.getUserCookies(accountNo))
.build()
);
String res = RequestUtil.get(config);// 发送GET请求
final JSONObject response = JSONObject.parseObject(res);
if (this.verifyCookies(response)) {
return null;
}
if (!StringUtils.hasText(res)) {
throw new BusinessException("调用Bilibili[粉丝]接口失败");
}
ReportAccountDto reportAccountDto;
try {
JSONObject data = response.getJSONObject("data");
reportAccountDto = ReportAccountDto.builder()
.fansCnt(data.getInteger("total_fans"))
//.followCnt(data.getInteger("followCnt"))
.likeCnt(data.getInteger("total_like"))
//.accountId(data.getString("userId"))
//.userOtherId(data.getString("userKwaiId"))
//.accountName(data.getString("userName"))
.build();
} catch (Exception e) {
log.error("获取[哔哩哔哩]fansCnt发生错误", e);
reportAccountDto = ReportAccountDto.builder()
.fansCnt(0)
.build();
}
final Account account = accountDao.findByAccountNoAndType(accountNo, this.getType().getValue());
if (Objects.nonNull(account))
accountDao.updateMsg(account.getId(), reportAccountDto.getAccountName(), reportAccountDto.getFansCnt(), new Date());
else
accountDao.save(Account.builder()
.cookiesStatus(true)
.accountNo(accountNo)
.type(this.getType().getValue())
.fansCnt(reportAccountDto.getFansCnt())
.accountName(reportAccountDto.getAccountName())
.reportDate(new Date())
.done(false)
.build());
return reportAccountDto;
}
/**
* 进入指定账户号的创作者平台首页
*
* @param accountNo Bilibili账户号
*/
public void loginIndex(String accountNo) {
final String uuid = UUID.randomUUID().toString().replace("-", "");
final WebDriver driver = this.getBILIBILIDriver(accountNo, uuid);
String targetUrl = "https://member.bilibili.com/platform/home";
try {
driver.get(targetUrl);
} catch (Exception e) {
this.exitBrowser(accountNo, uuid);
throw new BusinessException("跳转页面发生异常");
}
try {
List<WebElement> jumpButton = new WebDriverWait(driver, 6, 2000).until(driver1 ->
driver1.findElements(By.xpath("//img[@class='jump']")));
if (Objects.nonNull(jumpButton)) {
for (int i = 0; i < jumpButton.size(); i++) {
new WebDriverWait(driver, 6, 500).until(driver1 ->
driver1.findElement(By.xpath("//*[@id='driver-popover-item']/div[4]/span/button[2]"))).click();
this.waitFor(0.45);
}
}
} catch (Exception e) {
this.exitBrowser(accountNo, uuid);
throw new BusinessException(e.getMessage());
}
this.exitBrowser(accountNo, uuid);
}
/**
* 根据账户号获取账户信息
*
* @param accountNo bilibili账户号
* @return
*/
private JSONObject getUserInfo(String accountNo, String... cookies) {
String cookiesString;
if (cookies.length > 0) {
cookiesString = cookies[0];
} else {
cookiesString = this.getUserCookies(accountNo);
}
HttpConfig config = HttpConfig.custom()
.url("https://api.bilibili.com/x/web-interface/nav")
.headers(HttpHeader
.defaultHeader()
.other("Origin", "https://account.bilibili.com/")// 非必须
.referer("https://account.bilibili.com/account/home?spm_id_from=333.1007.0.0")// 非必须
.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("调用bilibili[用户信息]接口失败");
throw new BusinessException("调用bilibili[用户信息]接口失败");
}
JSONObject obj = new JSONObject();
final JSONObject userInfo = response.getJSONObject("data");
obj.put("userId", userInfo.getString("mid"));
obj.put("userNick", userInfo.getString("uname"));
return obj;
}
/**
* 将Bilibili账户的cookies放入driver中
*
* @param accountNo
* @return
*/
private WebDriver getBILIBILIDriver(String accountNo, String uuid) {
WebDriver driver = common.createDriver();
try {
driver.get("https://www.bilibili.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("创建Bilibili驱动发生异常: " + e.getMessage());
}
}
/**
* 根据账户号查到用户cookies, 并组装成String形式返回
*
* @param accountNo 账户号
* @return
*/
public String getUserCookies(String accountNo) {
return this.processCookiesToString(common.loadCookie(accountNo, 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(-101, resultCode) || loginMsg.contains("未登录")) {
return true;
} else {
return false;
}
} catch (Exception e) {
throw new BusinessException("验证Bilibili cookies发生异常: " + e.getMessage());
}
} else {
log.error("调用Bilibili平台接口未接收到返回值");
throw new BusinessException("调用Bilibili平台接口未接收到返回值");
}
}
/**
* 退出浏览器
*
* @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;
}
}