UpdateVideoApplication.java 36.5 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 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
package cn.bxe.updatevideo;

import cn.bxe.updatevideo.model.TbxXrBook;
import cn.bxe.updatevideo.model.TbxXrChapter;
import cn.bxe.updatevideo.model.TbxXrModule;
import cn.bxe.updatevideo.model.TbxXrVideo;
import cn.bxe.updatevideo.model.original.Chapter;
import cn.bxe.updatevideo.model.original.Module;
import cn.bxe.updatevideo.model.original.Textbook;
import cn.bxe.updatevideo.model.original.Video;
import cn.bxe.updatevideo.service.impl.TbxXrBookServiceImpl;
import cn.bxe.updatevideo.service.impl.TbxXrChapterServiceImpl;
import cn.bxe.updatevideo.service.impl.TbxXrModuleServiceImpl;
import cn.bxe.updatevideo.service.impl.TbxXrVideoServiceImpl;
import cn.bxe.updatevideo.util.JsonUtil;
import cn.zhxu.okhttps.HTTP;
import cn.zhxu.okhttps.HttpResult;
import cn.zhxu.okhttps.gson.GsonMsgConvertor;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;
import ws.schild.jave.FfmpegFileInfo;
import ws.schild.jave.MultimediaInfo;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static cn.bxe.updatevideo.util.VersionUtil.*;

/**
 * 用于更新知识点精讲视频(其实是新增  一般不修改旧的)
 * 1.一般来说操作流程是: 获取新书籍->获取新章节->获取新模块->获取新视频->下载视频封面->更新数据库视频封面链接
 * 2.如果只是某本版本更新了内容,并没有新增书籍,也可以单独更新章节/模块/视频
 * 3.他们存储有几个域名,其中有一个oss.5rs.com得域名,这个域名下的视频封面不可以直接访问的,所以需要特殊处理来下载
 * 更新完视频后检查下有无此域名的,如果有需要使用功能6单独下载
 * 4.视频可能没有时长,使用功能8单独获取
 *
 */
@SpringBootApplication
@MapperScan("cn.bxe.updatevideo.mapper")
public class UpdateVideoApplication {
    private static TbxXrBookServiceImpl bookService;
    private static TbxXrChapterServiceImpl chapterService;
    private static TbxXrModuleServiceImpl moduleService;
    private static TbxXrVideoServiceImpl videoService;

    static Logger logger = LoggerFactory.getLogger(UpdateVideoApplication.class);
    private static final HTTP http = HTTP
            .builder()
            .bodyType("json")
            .addMsgConvertor(new GsonMsgConvertor())
            .build();

    private static final ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 10,
            0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(30),
            new ThreadPoolExecutor.DiscardPolicy());

    public static void main(String[] args) throws InterruptedException, IOException {
        ConfigurableApplicationContext ctx = SpringApplication.run(UpdateVideoApplication.class, args);
        bookService = ctx.getBean(TbxXrBookServiceImpl.class);
        chapterService = ctx.getBean(TbxXrChapterServiceImpl.class);
        moduleService = ctx.getBean(TbxXrModuleServiceImpl.class);
        videoService = ctx.getBean(TbxXrVideoServiceImpl.class);

        menu();
        Thread.currentThread().join();
    }

    private static void menu() throws InterruptedException, IOException {
        System.out.println("=========菜单=========");
        System.out.println("1: 更新书籍");
        System.out.println("2: 更新章节");
        System.out.println("3: 更新模块");
        System.out.println("4: 更新视频");
        System.out.println("5: 下载封面");
        System.out.println("6: 下载oss.5rs.me视频封面");
        System.out.println("7: 更新数据库视频封面链接");
        System.out.println("8: 补充视频时长");
        System.out.println("9: 计算数量");
        System.out.println("0: 退出");
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入功能代码: ");
        String input = scanner.nextLine().trim();

        switch (input) {
            case "1":
                System.out.println("更新书籍咯");
                updateTextbook();
                break;
            case "2":
                System.out.println("更新章节咯");
                updateChapter();
                break;
            case "3":
                System.out.println("更新模块咯");
                updateModule();
                break;
            case "4":
                System.out.println("更新视频咯");
                updateVideo();
                break;
            case "5":
                System.out.println("下载封面咯");
                downloadCoverPic();
                break;
            case "6":
                System.out.println("下载oss5rsme视频封面");
                getOss5rsmeCover();
                break;
            case "7":
                System.out.println("更新数据库视频封面链接咯");
                updateDbVideoCoverUrl();
                break;
            case "8":
                System.out.println("补充视频时长咯");
                updateVideoDuration();
                break;
            case "9":
                System.out.println("计算");
                countSubjectVideo();
                break;
            case "0":
                System.out.println("退出咯");
                System.exit(0);
                break;
            default:
                System.out.println("你想做咩啊?");
                TimeUnit.SECONDS.sleep(2);
                break;
        }
        menu();
    }

    private static void updateTextbook() {
        String url = "https://api.bendiclass.com/external/api/textbook/v1/getTextbookListByLabel";
        HttpResult.Body body = http.sync(url)
                .addHeader("authorize", "banxiaoer")
                .setBodyPara(new Object())
                .post()
                .getBody();
        JSONObject jsonObject = JSONObject.parseObject(body.toString());
        boolean hasData = jsonObject.containsKey("data");

        if (hasData) {
            String data = jsonObject.getString("data");
            List<Textbook> textbooks = JSONArray.parseArray(data, Textbook.class);
            List<TbxXrBook> tbxXrBookList = new ArrayList<>();
            for (Textbook original : textbooks) {
                TbxXrBook pojo = new TbxXrBook();
                pojo.setBookName(original.getSubjectName() + original.getTextbookVersionName() + original.getGradeName() + original.getSchoolYearName());
                pojo.setTextbookId(Math.toIntExact(original.getId()));
                pojo.setSubject(SUBJECT_MAP.get(original.getSubject()));
                pojo.setGradeCode(GRADE_MAP.get(original.getGrade()));
                pojo.setTerm(SCHOOL_YEAR_MAP.get(original.getSchoolYear()));
                pojo.setStatus(10);
                String textBookVersion = VERSION_MAP.get(original.getTextbookVersion());
                if (textBookVersion == null) {
                    logger.warn("版本未登记: {} {}", original.getTextbookVersion(), pojo.getBookName());
                    logger.warn(JsonUtil.tranObjectToJsonStr(original));
                }
                pojo.setTextbookVersion(textBookVersion);
                pojo.setCreateTime(System.currentTimeMillis());
                tbxXrBookList.add(pojo);
            }
            if (!tbxXrBookList.isEmpty()) {
                // 查询已存在的book
                Set<Integer> textBookSet = bookService.lambdaQuery().select(TbxXrBook::getTextbookId).list()
                        .stream().map(TbxXrBook::getTextbookId).collect(Collectors.toSet());
                // 根据textbookId过滤已存在的
                tbxXrBookList = tbxXrBookList.stream().filter(o -> !textBookSet.contains(o.getTextbookId())).collect(Collectors.toList());
                // 保存新增的
                bookService.saveBatch(tbxXrBookList);
            }
        }
    }

    private static void updateChapter() throws InterruptedException {
        LambdaQueryWrapper<TbxXrBook> qw = new LambdaQueryWrapper<>();
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入你想更新的Textbook Id,直接回车为全部: ");
        String textbookId = scanner.nextLine().trim();
        if (StringUtils.isNotBlank(textbookId)) {
            qw.eq(TbxXrBook::getTextbookId, textbookId);
        } else {
            System.out.print("请输入你想更新的版本,直接回车为全部: ");
            String version = scanner.nextLine().trim();
            if (StringUtils.isNotBlank(version)) {
                System.out.println(version);
                qw.eq(TbxXrBook::getTextbookVersion, version);
            }
            System.out.print("请输入你想更新的年级,直接回车为全部: ");
            String grade = scanner.nextLine().trim();
            if (StringUtils.isNotBlank(grade)) {
                qw.eq(TbxXrBook::getGradeCode, grade);
            }
        }

        qw.select(TbxXrBook::getTextbookId, TbxXrBook::getBookName);
        List<TbxXrBook> list = bookService.list(qw);
        int bookNum = list.size();
        AtomicInteger count = new AtomicInteger();
        CountDownLatch cdl = new CountDownLatch(bookNum);
        for (TbxXrBook book : list) {
            pool.submit(() -> {
                try {
                    int currentNum = count.addAndGet(1);
                    String url = "https://api.bendiclass.com/external/textbookChapter/v1/queryTextbookChapter";
                    HttpResult.Body body = http
                            .sync(url)
                            .addHeader("authorize", "banxiaoer")
                            .addUrlPara("textbookId", book.getTextbookId())
                            .get()
                            .getBody();
                    TimeUnit.MILLISECONDS.sleep(200);
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    boolean hasData = jsonObject.containsKey("data");
                    if (hasData) {
                        String data = jsonObject.getObject("data", String.class);
                        List<Chapter> originalChaperList = JsonUtil.tranJsonStrToArray(data, Chapter.class);
                        List<TbxXrChapter> tbxXrChapterList = new ArrayList<>();
                        for (Chapter original : originalChaperList) {
                            TbxXrChapter chapter = new TbxXrChapter();
                            chapter.setLevel(original.getLevel());
                            chapter.setChapterId(original.getId());
                            chapter.setChapterName(original.getChapterName());
                            chapter.setTextbookId(original.getTextbookID());
                            chapter.setParentId(original.getParentID());
                            chapter.setSortIndex(original.getSortIndex());
                            chapter.setChildrenJson(original.getChildren());
                            chapter.setStatus(10);
                            chapter.setCreateTime(System.currentTimeMillis());
                            tbxXrChapterList.add(chapter);
                        }
                        if (tbxXrChapterList.size() > 0) {
                            List<Integer> chapterIdList = tbxXrChapterList.stream().map(TbxXrChapter::getChapterId).collect(Collectors.toList());
                            LambdaQueryWrapper<TbxXrChapter> chapterQW = new LambdaQueryWrapper<>();
                            chapterQW.eq(TbxXrChapter::getTextbookId, book.getTextbookId());
                            chapterQW.in(TbxXrChapter::getChapterId, chapterIdList);
                            chapterQW.select(TbxXrChapter::getChapterId);
                            List<TbxXrChapter> dbList = chapterService.list(chapterQW);
                            Set<Integer> dbChapterIdSet = dbList.stream().map(TbxXrChapter::getChapterId).collect(Collectors.toSet());
                            tbxXrChapterList = tbxXrChapterList.stream().filter(o -> !dbChapterIdSet.contains(o.getChapterId())).collect(Collectors.toList());
                            if (tbxXrChapterList.size() > 0) {
                                logger.info("{}/{},{},新增{}条数据", currentNum, bookNum, book.getBookName(), tbxXrChapterList.size());
                                chapterService.saveBatch(tbxXrChapterList);
                            } else {
                                logger.info("{}/{},{}无新内容", currentNum, bookNum, book.getBookName());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cdl.countDown();
            });
            TimeUnit.MILLISECONDS.sleep(100);
        }
        cdl.await();
    }

    private static void updateModule() throws InterruptedException {
        LambdaQueryWrapper<TbxXrBook> qw = new LambdaQueryWrapper<>();
        Scanner scanner = new Scanner(System.in);
        System.out.print("也许你想按textbookId更新?,直接回车为全部: ");
        String textbookId = scanner.nextLine().trim();
        if (StringUtils.isNotBlank(textbookId)) {
            qw.eq(TbxXrBook::getTextbookId, textbookId);
        } else {
            System.out.print("请输入你想更新的版本,直接回车为全部: ");
            String version = scanner.nextLine().trim();
            if (StringUtils.isNotBlank(version)) {
                System.out.println(version);
                qw.eq(TbxXrBook::getTextbookVersion, version);
            }
            System.out.print("请输入你想更新的年级,直接回车为全部: ");
            String grade = scanner.nextLine().trim();
            if (StringUtils.isNotBlank(grade)) {
                qw.eq(TbxXrBook::getGradeCode, grade);
            }
        }
        qw.select(TbxXrBook::getTextbookId, TbxXrBook::getBookName);
        List<TbxXrBook> list = bookService.list(qw);
        int bookNum = list.size();
        AtomicInteger bookCounter = new AtomicInteger();
        CountDownLatch bookCDL = new CountDownLatch(bookNum);
        for (TbxXrBook tbxXrBook : list) {
            int currentBookNum = bookCounter.addAndGet(1);
            logger.info("查询书籍{}/{} :: 书名: {}", currentBookNum, bookNum, tbxXrBook.getBookName());
            LambdaQueryWrapper<TbxXrChapter> chapterQW = new LambdaQueryWrapper<>();
            chapterQW.eq(TbxXrChapter::getTextbookId, tbxXrBook.getTextbookId());
            chapterQW.select(TbxXrChapter::getChapterId, TbxXrChapter::getChildrenJson);
            List<TbxXrChapter> chapterList = chapterService.list(chapterQW);
            List<Integer> chapterIdList = new ArrayList<>();
            for (TbxXrChapter chapter : chapterList) {
                chapterIdList.add(chapter.getChapterId());
                List<Integer> childrenIdList = JsonUtil
                        .tranJsonStrToArray(chapter.getChildrenJson(), Chapter.class)
                        .stream()
                        .map(Chapter::getId)
                        .collect(Collectors.toList());
                chapterIdList.addAll(childrenIdList);
            }
            int chapterNum = chapterIdList.size();
            AtomicInteger chapterCounter = new AtomicInteger();
            CountDownLatch chapterCDL = new CountDownLatch(chapterNum);
            for (Integer id : chapterIdList) {
                pool.execute(() -> {
                    try {
                        int currentChapterNum = chapterCounter.addAndGet(1);
                        String url = "https://api.bendiclass.com/external/textbookCategory/v1/queryValidCategory";
                        HttpResult.Body body = http
                                .sync(url)
                                .addUrlPara("textbookId", tbxXrBook.getTextbookId())
                                .addUrlPara("chapterId", id)
                                .get()
                                .getBody();
                        TimeUnit.MILLISECONDS.sleep(100);
                        JSONObject jsonObject = JSONObject.parseObject(body.toString());
                        String dataList = jsonObject.getObject("data", String.class);
                        List<Module> modules = JsonUtil.tranJsonStrToArray(dataList, Module.class);
                        if (modules.size() > 0) {
                            List<TbxXrModule> tbxXrModuleList = new ArrayList<>();
                            List<Integer> moduleIdList = new ArrayList<>();
                            for (Module module : modules) {
                                TbxXrModule tbxXrModule = moduleConvert(module);
                                tbxXrModule.setChapterId(id);
                                tbxXrModuleList.add(tbxXrModule);
                                moduleIdList.add(tbxXrModule.getModuleId());
                                List<Module> moduleList = module.getModuleList();
                                for (Module module1 : moduleList) {
                                    TbxXrModule subTbxXrModule = moduleConvert(module1);
                                    subTbxXrModule.setChapterId(id);
                                    subTbxXrModule.setCategoryName(module.getCategoryName());
                                    subTbxXrModule.setCategoryDesc(module1.getModuleDesc());
                                    moduleIdList.add(subTbxXrModule.getModuleId());
                                    tbxXrModuleList.add(subTbxXrModule);
                                }

                            }
                            LambdaQueryWrapper<TbxXrModule> moduleQW = new LambdaQueryWrapper<>();
                            moduleQW.in(TbxXrModule::getModuleId, moduleIdList);
                            moduleQW.eq(TbxXrModule::getChapterId, id);
                            moduleQW.eq(TbxXrModule::getTextbookId, tbxXrBook.getTextbookId());
                            moduleQW.select(TbxXrModule::getModuleId, TbxXrModule::getTextbookId, TbxXrModule::getChapterId);
                            List<TbxXrModule> dbExistModule = moduleService.list(moduleQW);
                            for (TbxXrModule tbxXrModule : dbExistModule) {
                                tbxXrModuleList.remove(tbxXrModule);
                            }
                            if (tbxXrModuleList.size() > 0) {
                                moduleService.saveBatch(tbxXrModuleList);
                                logger.info("书籍{}/{},开始处理章节: {}/{},更新模块数:{}", currentBookNum, bookNum, currentChapterNum, chapterNum, tbxXrModuleList.size());
                            } else {
                                logger.info("章节: {}/{},无", currentChapterNum, chapterNum);
                            }
                        } else {
                            logger.info("章节: {}/{},无内容~", currentChapterNum, chapterNum);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    chapterCDL.countDown();
                });
                TimeUnit.MILLISECONDS.sleep(100);
            }
            chapterCDL.await();
            bookCDL.countDown();
        }
        bookCDL.await();
    }

    private static void updateVideo() throws InterruptedException {
        LambdaQueryWrapper<TbxXrBook> qw = new LambdaQueryWrapper<>();
        Scanner scanner = new Scanner(System.in);
        System.out.print("也许你想按textbookId更新?,直接回车为全部: ");
        String textbookId = scanner.nextLine().trim();
        if (StringUtils.isNotBlank(textbookId)) {
            qw.eq(TbxXrBook::getTextbookId, textbookId);
        } else {
            System.out.print("请输入你想更新的版本,直接回车为全部: ");
            String version = scanner.nextLine().trim();
            if (StringUtils.isNotBlank(version)) {
                qw.eq(TbxXrBook::getTextbookVersion, version);
            }
            System.out.print("请输入你想更新的年级,直接回车为全部: ");
            String grade = scanner.nextLine().trim();
            if (StringUtils.isNotBlank(grade)) {
                qw.eq(TbxXrBook::getGradeCode, grade);
            }
        }
        qw.select(TbxXrBook::getTextbookId, TbxXrBook::getBookName);
        List<TbxXrBook> bookList = bookService.list(qw);
        AtomicInteger bookCount = new AtomicInteger();
        CountDownLatch bookCDL = new CountDownLatch(bookList.size());
        for (TbxXrBook book : bookList) {
            int currentBookNum = bookCount.addAndGet(1);
            LambdaQueryWrapper<TbxXrChapter> chapterQW = new LambdaQueryWrapper<>();
            chapterQW.eq(TbxXrChapter::getTextbookId, book.getTextbookId());
            chapterQW.select(TbxXrChapter::getChapterId, TbxXrChapter::getChildrenJson, TbxXrChapter::getChapterName);
            List<TbxXrChapter> dbChapterList = chapterService.list(chapterQW);
            //key: chapterId, value: moduleIdList
            Map<Integer, List<Integer>> chapterAndModuleIdMap = new HashMap<>();
            //整理章节id
            for (TbxXrChapter chapter : dbChapterList) {
                chapterAndModuleIdMap.put(chapter.getChapterId(), new ArrayList<>());
                List<Chapter> childChapter = JsonUtil.tranJsonStrToArray(chapter.getChildrenJson(), Chapter.class);
                chapterAndModuleIdMap.put(chapter.getChapterId(), new ArrayList<>());
                for (Chapter chapter1 : childChapter) {
                    chapterAndModuleIdMap.put(chapter1.getId(), new ArrayList<>());
                }
            }

            List<Integer> emptyModuleIdList = new ArrayList<>();

            //整理模块id
            chapterAndModuleIdMap.forEach((k, v) -> {
                LambdaQueryWrapper<TbxXrModule> moduleQW = new LambdaQueryWrapper<>();
                moduleQW.eq(TbxXrModule::getChapterId, k);
                moduleQW.select(TbxXrModule::getModuleId);
                List<TbxXrModule> dbModuleList = moduleService.list(moduleQW);
                if (CollectionUtils.isEmpty(dbModuleList)) {
                    emptyModuleIdList.add(k);
                } else {
                    for (TbxXrModule module : dbModuleList) {
                        v.add(module.getModuleId());
                    }
                }
            });
            emptyModuleIdList.forEach(chapterAndModuleIdMap::remove);

            //获取视频 整理需要更新的视频
            AtomicInteger chapterCount = new AtomicInteger();

            chapterAndModuleIdMap.forEach((chapterId, moduleIdList) -> {
                int currentChapterNum = chapterCount.addAndGet(1);
                if (moduleIdList.size() > 0) {
                    CountDownLatch moduleCDL = new CountDownLatch(moduleIdList.size());
                    CopyOnWriteArrayList<TbxXrVideo> chapterVideoList = new CopyOnWriteArrayList<>();
                    CopyOnWriteArrayList<Integer> videoIdList = new CopyOnWriteArrayList<>();
                    for (Integer moduleId : moduleIdList) {
                        pool.submit(() -> {
                            try {
                                List<TbxXrVideo> moduleVideoList = new ArrayList<>();
                                String baseUrl = "https://api.bendiclass.com/external/textbookVideo/v1/queryTextbookVideo";
                                HttpResult.Body body = http
                                        .sync(baseUrl)
                                        .addUrlPara("chapterId", chapterId)
                                        .addUrlPara("moduleId", moduleId)
                                        .get()
                                        .getBody();
                                TimeUnit.MILLISECONDS.sleep(100);
                                JSONObject jsonObject = JSONObject.parseObject(body.toString());
                                List<Video> videoDataList = JsonUtil.tranJsonStrToArray(jsonObject.getObject("data", String.class), Video.class);
                                if (videoDataList.size() > 0) {
                                    for (Video video : videoDataList) {
                                        TbxXrVideo record = new TbxXrVideo();
                                        record.setVideoId(video.getId());
                                        record.setModuleId(moduleId);
                                        record.setChapterId(chapterId);
                                        video.setVideoName(video.getVideoName().trim());
                                        record.setVideoName(video.getVideoName());
                                        if (video.getVideoName().length() > 50) {
                                            System.out.println(video.getVideoName());
                                            record.setVideoName(video.getVideoName().substring(0, 46) + "...");
                                        }
                                        record.setUrl(video.getUrl());
                                        record.setTimeDuration(video.getTimeDuration());
                                        record.setStatus(10);
                                        record.setCreateTime(System.currentTimeMillis());
                                        moduleVideoList.add(record);
                                    }
                                    videoIdList.addAll(moduleVideoList.stream().map(TbxXrVideo::getVideoId).collect(Collectors.toList()));

                                    chapterVideoList.addAll(moduleVideoList);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            moduleCDL.countDown();
                        });
                    }
                    try {
                        moduleCDL.await();
                        if (videoIdList.size() > 0) {
                            LambdaQueryWrapper<TbxXrVideo> tbxXrVideoQW = new LambdaQueryWrapper<>();
                            tbxXrVideoQW.select(TbxXrVideo::getVideoId, TbxXrVideo::getChapterId, TbxXrVideo::getModuleId);
                            tbxXrVideoQW.eq(TbxXrVideo::getStatus, 10);
                            tbxXrVideoQW.in(TbxXrVideo::getVideoId, videoIdList);
                            List<TbxXrVideo> dbVideoList = videoService.list(tbxXrVideoQW);
                            for (TbxXrVideo tbxXrVideo : dbVideoList) {
                                chapterVideoList.remove(tbxXrVideo);
                            }
                            if (chapterVideoList.size() > 0) {
                                videoService.saveBatch(chapterVideoList);
                                logger.info("书籍进度{}/{},章节进度{}/{},新增视频{}条", currentBookNum, bookList.size(), currentChapterNum, chapterAndModuleIdMap.size(), chapterVideoList.size());
                            } else {
                                logger.info("书籍进度{}/{},章节进度{}/{},无新视频", currentBookNum, bookList.size(), currentChapterNum, chapterAndModuleIdMap.size());
                            }
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    logger.info("书籍进度{}/{},章节进度{}/{},无模块", currentBookNum, bookList.size(), currentChapterNum, chapterAndModuleIdMap.size());
                }
            });
            logger.info("书籍进度{}/{},更新完成", currentBookNum, bookList.size());
            bookCDL.countDown();
        }
        bookCDL.await();
    }

    private static void downloadCoverPic() throws InterruptedException {
        LambdaQueryWrapper<TbxXrVideo> qw = new LambdaQueryWrapper<>();
        qw.select(TbxXrVideo::getVideoId, TbxXrVideo::getChapterId, TbxXrVideo::getModuleId, TbxXrVideo::getVideoName, TbxXrVideo::getUrl);
        qw.eq(TbxXrVideo::getStatus, 10);
        qw.notLike(TbxXrVideo::getUrl, "https://oss.5rs.me");
        qw.isNull(TbxXrVideo::getCoverUrl);
        List<TbxXrVideo> list = videoService.list(qw);
        for (int i = 0; i < list.size(); i++) {
            //remove exists file in list
            TbxXrVideo tbxXrVideo = list.get(i);
            String fileName = "xrv_" + tbxXrVideo.getVideoId() + ".jpg";
            String filePath = "D:\\video\\" + fileName;
            File file = new File(filePath);
            if (file.exists()) {
                //如果文件小于50kb,可能是下载失败的文件,重新下载
                if (file.length() / 1024 < 20) {
                    boolean delete = file.delete();
                    System.out.println("删除未成功下载的文件");
                } else {
                    list.remove(i);
                    i--;
                }
            }
        }
        int size = list.size();
        AtomicInteger count = new AtomicInteger();
        for (TbxXrVideo tbxXrVideo : list) {
            pool.submit(() -> {
                int currentCount = count.addAndGet(1);
                String coverUrl = tbxXrVideo.getUrl() + "?spm=a2c4g.11186623.2.1.yjOb8V&x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast";
                String fileName = "xrv_" + tbxXrVideo.getVideoId() + ".jpg";
                String filePath = "D:\\video\\" + fileName;
                if (new File(filePath).exists()) {
                    logger.info("视频封面{}/{},已存在", currentCount, size);
                    return;
                }
                //下载封面
                try {
                    http.sync(coverUrl)
                            .get()
                            .getBody()
                            .toFile(filePath)
                            .start();
                    logger.info("{}/{},{},下载封面成功", currentCount, size, tbxXrVideo.getVideoName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            TimeUnit.MILLISECONDS.sleep(200);
        }
    }

    private static void updateVideoDuration() throws InterruptedException {
        LambdaQueryWrapper<TbxXrVideo> qw = new LambdaQueryWrapper<>();
        qw.select(TbxXrVideo::getId, TbxXrVideo::getUrl);
        qw.in(TbxXrVideo::getTimeDuration,"","--");
        qw.eq(TbxXrVideo::getStatus, 10);
        List<TbxXrVideo> list = videoService.list(qw);
        int size = list.size();
        AtomicInteger counter = new AtomicInteger();
        for (TbxXrVideo tbxXrVideo : list) {
            pool.submit(() -> {
                int current = counter.addAndGet(1);
                try {
                    String url = tbxXrVideo.getUrl();
                    FfmpegFileInfo ffmpegFileInfo = new FfmpegFileInfo();
                    MultimediaInfo info = ffmpegFileInfo.getInfo(url);
                    long duration = info.getDuration();
                    long minutes = duration / 1000L / 60L;
                    long seconds = duration / 1000L % 60L;
                    String minutesStr = minutes + "";
                    String secondsStr = seconds + "";
                    if (minutesStr.length() == 1) {
                        minutesStr = "0" + minutesStr;
                    }
                    if (secondsStr.length() == 1) {
                        secondsStr = "0" + secondsStr;
                    }
                    tbxXrVideo.setTimeDuration(minutesStr + ":" + secondsStr);
                    LambdaUpdateWrapper<TbxXrVideo> uw = new LambdaUpdateWrapper<>();
                    uw.eq(TbxXrVideo::getVideoId, tbxXrVideo.getVideoId());
                    uw.eq(TbxXrVideo::getChapterId, tbxXrVideo.getChapterId());
                    uw.eq(TbxXrVideo::getModuleId, tbxXrVideo.getModuleId());
                    tbxXrVideo.updateById();
                    logger.info("{}/{}更新视频时长成功,时长:{}", current, size, tbxXrVideo.getTimeDuration());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            Thread.sleep(500);
        }
        logger.info("更新视频时长完成");
    }

    private static void updateDbVideoCoverUrl() throws InterruptedException {
        LambdaQueryWrapper<TbxXrVideo> qw = new LambdaQueryWrapper<>();
        qw.select(TbxXrVideo::getVideoId, TbxXrVideo::getId);
        qw.eq(TbxXrVideo::getStatus, 10);
        //qw.notLike(TbxXrVideo::getUrl, "https://oss.5rs.me");
        qw.isNull(TbxXrVideo::getCoverUrl);
        List<TbxXrVideo> list = videoService.list(qw);
        int size = list.size();
        AtomicInteger counter = new AtomicInteger();
        for (TbxXrVideo video : list) {
            pool.execute(() -> {
                //检测封面是否存在本地
                String fileName = "xrv_" + video.getVideoId() + ".jpg";
                String filePath = "D:\\video\\" + fileName;
                if (!new File(filePath).exists()) {
                    return;
                }
                video.setCoverUrl("https://pics-cos.banxiaoer.net/tbx/xrv/covers_images/xrv_" + video.getVideoId() + ".jpg");
                video.updateById();
                int count = counter.addAndGet(1);
                logger.info("{}/{}更新视频封面成功", count, size);
            });
            TimeUnit.MILLISECONDS.sleep(100);
        }
    }

    private static void countSubjectVideo() {
        SUBJECT_MAP.forEach((k, v) -> {
            LambdaQueryWrapper<TbxXrBook> qw = new LambdaQueryWrapper<>();
            qw.eq(TbxXrBook::getSubject, v);
            List<TbxXrBook> list = bookService.list(qw);
            List<Integer> collect = list.stream().map(TbxXrBook::getTextbookId).collect(Collectors.toList());
            LambdaQueryWrapper<TbxXrModule> moduleQW = new LambdaQueryWrapper<>();
            if (collect.size() > 0) {
                moduleQW.in(TbxXrModule::getTextbookId, collect);
                List<TbxXrModule> list1 = moduleService.list(moduleQW);

                LambdaQueryWrapper<TbxXrVideo> videoQW = new LambdaQueryWrapper<>();
                list1.forEach(obj -> videoQW.or().eq(TbxXrVideo::getChapterId, obj.getChapterId()).eq(TbxXrVideo::getModuleId, obj.getModuleId()));
                List<TbxXrVideo> list2 = videoService.list(videoQW);
                System.out.println(v + "," + list2.size());
            }
        });
    }

    /**
     * 获取oss.5rs.me的视频封面
     *
     */
    private static void getOss5rsmeCover() throws IOException {
        LambdaQueryWrapper<TbxXrVideo> qw = new LambdaQueryWrapper<>();
        qw.like(TbxXrVideo::getUrl, "https://oss.5rs.me");
        qw.isNull(TbxXrVideo::getCoverUrl);
        List<TbxXrVideo> list = videoService.list(qw);
        for (TbxXrVideo tbxXrVideo : list) {
            //如果已存在则跳过
            String imgName = "xrv_" + tbxXrVideo.getVideoId() + ".jpg";
            String filePath = "D:\\ossvideo\\" + imgName;
            File picFile = new File(filePath);
            boolean exists = picFile.exists();
            if (exists) {
                continue;
            }
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(tbxXrVideo.getUrl());
            ff.start();
            Frame frame = null;
            for (int i = 0; i < 75; i++) {
                //获取第三秒第一帧
                frame = ff.grabImage();
            }
            if (frame.image == null) {
                continue;
            }
            Java2DFrameConverter converter = new Java2DFrameConverter();//创建一个帧-->图片的转换器

            BufferedImage image = converter.getBufferedImage(frame);//转换

            //将图片保存到目标文件中
            ImageIO.write(image, "jpg", picFile);
            ff.stop();
            ff.close();
        }

    }


    private static TbxXrModule moduleConvert(Module module) {
        TbxXrModule tbxXrModule = new TbxXrModule();
        tbxXrModule.setModuleId((int) module.getId());
        tbxXrModule.setCategoryDesc(module.getCategoryDesc());
        tbxXrModule.setCategoryName(module.getCategoryName());
        tbxXrModule.setTextbookId((int) module.getTextbookID());
        tbxXrModule.setStatus(10);
        tbxXrModule.setCreateTime(System.currentTimeMillis());

        return tbxXrModule;
    }

}