├── .gitignore ├── BParser.iml ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── java └── com │ └── lemontree │ ├── BParser.java │ ├── BParserOnTerminal.java │ ├── BParserWithTray.java │ ├── Constant.java │ ├── FormatInfo.java │ ├── Logger.java │ └── Utils.java └── resources └── com └── lemontree ├── icon.ico └── icon.png /.gitignore: -------------------------------------------------------------------------------- 1 | ### IntelliJ IDEA ### 2 | out/ 3 | !**/src/main/**/out/ 4 | !**/src/test/**/out/ 5 | 6 | ### Eclipse ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | bin/ 15 | !**/src/main/**/bin/ 16 | !**/src/test/**/bin/ 17 | 18 | ### NetBeans ### 19 | /nbproject/private/ 20 | /nbbuild/ 21 | /dist/ 22 | /nbdist/ 23 | /.nb-gradle/ 24 | 25 | ### VS Code ### 26 | .vscode/ 27 | 28 | ### Mac OS ### 29 | .DS_Store 30 | 31 | /.idea 32 | /log 33 | /img 34 | -------------------------------------------------------------------------------- /BParser.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 LemonTree 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bilibili视频自动解析 2 | 效果如下: 3 | 4 | 复制: 5 | ``` 6 | https://www.bilibili.com/video/BV1EE411W7oa?vd_source=1ea648cf2e482b3e0f8610e072ad4062&p=11&spm_id_from=333.788.videopod.episodes 7 | ``` 8 | 9 | 粘贴: 10 | ``` 11 | <<<<这是视频封面图片>>>> 12 | 【完结】0元搭建NAS从入门到入坑 13 | 分集: 媒体管理:DDNS设置、Video Station搭建 14 | 发布时间: 2020-03-06 12:32:43 15 | up: 天马Pegasus 16 | 评论数: 2289 17 | 收藏数: 63387 18 | 硬币数: 52002 19 | 点赞数: 50467 20 | https://www.bilibili.com/video/BV1EE411W7oa?p=11 21 | ``` 22 | 23 | ## 使用 24 | 1. 复制浏览器标题的链接,或者使用分享按钮获取链接。 25 | 2. **进行解析的判断条件**: 26 | - 正则表达式 `/video/(BV[0-9A-Za-z]{10})(?:[/?]|$)` 27 | 28 | 29 | ## 关于 30 | 自己瞎做的,使用Java21 31 | 只能解析到地址栏或网页端分享按钮的BVID 32 | exe打包部分的maven插件配置来自 [SoNovel](https://github.com/freeok/so-novel) 33 | 34 | ## BUG 35 | 复制jetbrains的文字会报错,不影响运行 36 | 如果在powershell使用这个命令报错,请使用cmd运行 37 | 38 | ## 使用 39 | 下载Releases中的jar或者exe文件 40 | **jar:** 在jar文件所在目录下打开控制台,确保安装了java,输入`java -jar (你下载的jar名称)` 41 | **exe:** 确保你是windows环境,直接运行 42 | 43 | ## 闲聊 44 | 项目有问题可以提一个issue,在上面大声说出你的问题 45 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | BParser 5 | 0.0.3 6 | com.lemontree.BParser 7 | bilibili链接解析器 8 | 9 | com.lemontree 10 | 11 | 12 | 21 13 | 21 14 | UTF-8 15 | 21 16 | 17 | 18 | ${java.version} 19 | ${java.version} 20 | UTF-8 21 | UTF-8 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.codehaus.mojo 30 | exec-maven-plugin 31 | 3.5.0 32 | 33 | com.lemontree.BParser 34 | 35 | 36 | 37 | 41 | 42 | org.apache.maven.plugins 43 | maven-assembly-plugin 44 | 3.7.1 45 | 46 | 47 | 48 | com.lemontree.BParser 49 | 50 | 51 | 52 | 53 | jar-with-dependencies 54 | 55 | app 56 | 57 | 58 | 59 | make-assembly 60 | package 61 | 62 | single 63 | 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-resources-plugin 70 | 3.3.1 71 | 72 | UTF-8 73 | 74 | 75 | 76 | 77 | com.akathist.maven.plugins.launch4j 78 | launch4j-maven-plugin 79 | 2.5.2 80 | 81 | 82 | launch4j-exe 83 | package 84 | 85 | launch4j 86 | 87 | 88 | 89 | 90 | console 91 | target/BParser/BParser.exe 92 | ${project.build.directory}/app-jar-with-dependencies.jar 93 | SoNovel 94 | 95 | false 96 | 97 | com.lemontree.BParser 98 | true 99 | anything 100 | 101 | 102 | 103 | ${jrePath} 104 | 21 105 | 106 | 107 | 108 | ${project.version}.0 109 | ${project.version}.0 110 | 111 | Parser link from copy board. 112 | Copyright (C) 2021-2025 LEMONTREE. All rights reserved. 113 | ${project.version}.0 114 | ${project.version}.0 115 | 116 | BParser 117 | github.com/lemontreelt 118 | BParser 119 | BParser.exe 120 | 121 | SIMPLIFIED_CHINESE 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | src/main/resources 131 | true 132 | 133 | 134 | 135 | 136 | 137 | 138 | com.alibaba.fastjson2 139 | fastjson2 140 | 2.0.46 141 | 142 | 143 | org.jetbrains 144 | annotations 145 | 24.1.0 146 | 147 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/BParser.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import java.util.Arrays; 4 | import java.util.function.Predicate; 5 | 6 | public class BParser { 7 | private static final Logger logger = new Logger(Logger.LoggerLevel.ALL, "BParser"); 8 | public static void main(String[] args) { 9 | if(Arrays.stream(args).anyMatch(Predicate.isEqual("--tray"))) BParserWithTray.run(logger); 10 | else BParserOnTerminal.run(logger); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/BParserOnTerminal.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import java.util.concurrent.Executors; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class BParserOnTerminal { 7 | public static void run(Logger logger) { 8 | Utils utils = new Utils(logger); 9 | utils.introduce(); 10 | 11 | Executors.newSingleThreadScheduledExecutor() 12 | .scheduleAtFixedRate(utils.clipMonitor, 0, 2, TimeUnit.SECONDS); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/BParserWithTray.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | import java.awt.*; 6 | import java.awt.event.ActionEvent; 7 | import java.awt.event.ActionListener; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.ScheduledFuture; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | public class BParserWithTray { 13 | private static boolean isRunning = true; 14 | private static ScheduledFuture scheduledFuture; 15 | 16 | public static void run(Logger logger) { 17 | try { 18 | SystemTray tray = SystemTray.getSystemTray(); 19 | 20 | //设置任务栏图标 21 | Image image = Toolkit.getDefaultToolkit().createImage(BParser.class.getResource("icon.png")); 22 | Utils utils = new Utils(logger); 23 | TrayIcon icon = getTrayIcon(image, logger, utils); 24 | 25 | utils.setIcon(icon); 26 | tray.add(icon); 27 | 28 | logger.Info("初始化任务栏成功"); 29 | 30 | utils.introduce(); 31 | 32 | scheduledFuture = Executors.newSingleThreadScheduledExecutor() 33 | .scheduleAtFixedRate(utils.clipMonitor, 0, 1, TimeUnit.SECONDS); 34 | 35 | } catch(AWTException e) { 36 | logger.Error("无法初始化任务栏图标"); 37 | System.exit(-1); 38 | } 39 | } 40 | 41 | private static @NotNull TrayIcon getTrayIcon(Image image, Logger logger, Utils utils) { 42 | TrayIcon icon = new TrayIcon(image, "BParser"); 43 | icon.setImageAutoSize(true); 44 | 45 | //添加菜单 46 | PopupMenu menu = new PopupMenu(); 47 | MenuItem exitItem = new MenuItem("Exit"); 48 | MenuItem toggleItem = new MenuItem("Stop"); 49 | MenuItem analyzeItem = new MenuItem("Analyze"); 50 | analyzeItem.setEnabled(false); 51 | menu.add(exitItem); 52 | menu.add(toggleItem); 53 | menu.add(analyzeItem); 54 | menu.setFont(new Font("微软雅黑", Font.PLAIN, 12)); 55 | 56 | exitItem.addActionListener(event -> { 57 | logger.Info("退出程序"); 58 | System.exit(0); 59 | }); 60 | 61 | analyzeItem.addActionListener(event -> { 62 | logger.Info("用户手动进行解析"); 63 | utils.clipMonitor.run(); 64 | }); 65 | 66 | class ToggleState implements ActionListener { 67 | @Override 68 | public void actionPerformed(ActionEvent e) { 69 | if(isRunning) { 70 | toggleItem.setLabel("Run"); 71 | analyzeItem.setEnabled(true); 72 | scheduledFuture.cancel(false); 73 | logger.Info("停止程序"); 74 | isRunning = false; 75 | } else { 76 | toggleItem.setLabel("Stop"); 77 | analyzeItem.setEnabled(false); 78 | scheduledFuture = Executors.newSingleThreadScheduledExecutor() 79 | .scheduleAtFixedRate(utils.clipMonitor, 0, 1, TimeUnit.SECONDS); 80 | logger.Info("启动程序"); 81 | isRunning = true; 82 | } 83 | } 84 | } 85 | 86 | ToggleState toggleState = new ToggleState(); 87 | toggleItem.addActionListener(toggleState); 88 | 89 | icon.setPopupMenu(menu); 90 | return icon; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/Constant.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | public interface Constant { 6 | String videoInfoApiUrl = "https://api.bilibili.com/x/web-interface/view?bvid="; 7 | String pageInfoApiUrl = "https://api.bilibili.com/x/player/pagelist?bvid="; 8 | Pattern BvPattern = Pattern.compile("/video/(BV[0-9A-Za-z]{10})(?:[/?]|$)"); 9 | Pattern pagePattern = Pattern.compile("[?&]p=(\\d+)(?:&|$)"); 10 | String IntroduceBParser = """ 11 | ___ ___ \s 12 | | _ ) | _ \\ __ _ _ _ ___ ___ _ _ \s 13 | | _ \\ | _/ / _` | | '_| (_-< / -_) | '_|\s 14 | |___/ _|_|_ \\__,_| _|_|_ /__/_ \\___| _|_|_ \s 15 | _|""\"""|_| ""\" |_|""\"""|_|""\"""|_|""\"""|_|""\"""|_|""\"""|\s 16 | "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"""; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/FormatInfo.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | import java.awt.datatransfer.DataFlavor; 6 | import java.awt.datatransfer.Transferable; 7 | import java.awt.datatransfer.UnsupportedFlavorException; 8 | 9 | public class FormatInfo implements Transferable { 10 | private final String htmlContent; 11 | private final DataFlavor DEF_DF = new DataFlavor("text/html; charset=unicode; class=java.lang.String", "text/html"); 12 | private final String text; 13 | 14 | 15 | public FormatInfo(String PicPath, String Text){ 16 | this.text = Text; 17 | htmlContent = String.format("
%s", PicPath, Text); 18 | } 19 | 20 | 21 | @Override 22 | public DataFlavor[] getTransferDataFlavors() { 23 | return new DataFlavor[] {DEF_DF, DataFlavor.stringFlavor}; 24 | } 25 | 26 | @Override 27 | public boolean isDataFlavorSupported(DataFlavor flavor) { 28 | return DEF_DF.equals(flavor) || flavor.equals(DataFlavor.stringFlavor); 29 | } 30 | 31 | @NotNull 32 | @Override 33 | public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { 34 | if (DEF_DF.equals(flavor)) return htmlContent; 35 | if (flavor.equals(DataFlavor.stringFlavor)) return text.replace("
", "\n"); 36 | throw new UnsupportedFlavorException(flavor); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/Logger.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import java.text.SimpleDateFormat; 4 | 5 | @SuppressWarnings("unused") 6 | public class Logger { 7 | public enum LoggerLevel { 8 | ALL, VIDEO, ERROR, WARN, INFO 9 | } 10 | 11 | SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 12 | private String Level; 13 | private String Prefix; 14 | 15 | public Logger(LoggerLevel LoggerLevel, String prefix) { 16 | Level = String.valueOf(LoggerLevel); 17 | this.Prefix = prefix; 18 | } 19 | 20 | public Logger(LoggerLevel loggerLevel) { 21 | this(loggerLevel, null); 22 | } 23 | 24 | public Logger() { 25 | this(LoggerLevel.ALL); 26 | } 27 | 28 | 29 | public void setLevel(LoggerLevel loggerLevel) { 30 | Level = String.valueOf(loggerLevel); 31 | } 32 | 33 | public void changePrefix(String prefixName) { 34 | Prefix = prefixName; 35 | } 36 | 37 | public void Error(String msg) { 38 | System.out.println(Prefix("ERROR", getColorForLevel("error")) + msg); 39 | } 40 | 41 | public void Warn(String msg) { 42 | if(Level.equals(String.valueOf(LoggerLevel.ERROR))) return; 43 | System.out.println(Prefix("WARN", getColorForLevel("warn")) + msg); 44 | } 45 | 46 | public void Info(String msg) { 47 | if(!Level.equals(String.valueOf(LoggerLevel.ALL)) && !Level.equals(String.valueOf(LoggerLevel.INFO))) return; 48 | System.out.println(Prefix("INFO", getColorForLevel("info")) + msg); 49 | } 50 | 51 | public void Video(String msg) { 52 | if(!Level.equals(String.valueOf(LoggerLevel.VIDEO)) && !Level.equals(String.valueOf(LoggerLevel.ALL))) return; 53 | System.out.println(Prefix("VIDEO", getColorForLevel("VIDEO")) + msg); 54 | } 55 | 56 | private String Prefix(String msg, String color) { 57 | // 时间前缀 58 | String PrefixTime = ConsoleColor.RESET + ConsoleColor.WHITE + "[" + ConsoleColor.GREEN + 59 | formatter.format(System.currentTimeMillis()) + ConsoleColor.WHITE + "]"; 60 | 61 | // 等级前缀 62 | String PrefixLevel = PrefixTime + ConsoleColor.RESET + ConsoleColor.WHITE + 63 | "[" + ConsoleFont.BOLD + color + msg + ConsoleColor.RESET + ConsoleColor.WHITE + "] " + ConsoleColor.RESET; 64 | 65 | if(Prefix == null) return PrefixLevel; 66 | return ConsoleColor.WHITE + "[" + ConsoleColor.MAGENTA + this.Prefix + ConsoleColor.WHITE + "]" + PrefixLevel; 67 | } 68 | 69 | private String getColorForLevel(String level) { 70 | return switch(level.toLowerCase()) { 71 | case "warn" -> ConsoleColor.YELLOW; 72 | case "error" -> ConsoleColor.RED; 73 | case "video" -> ConsoleColor.BLUE; 74 | default -> ConsoleColor.RESET; 75 | }; 76 | } 77 | 78 | @SuppressWarnings("unused") 79 | private interface ConsoleColor { 80 | // 文字颜色 81 | String RESET = "\u001B[0m"; 82 | String BLACK = "\u001B[30m"; 83 | String RED = "\u001B[31m"; 84 | String GREEN = "\u001B[32m"; 85 | String YELLOW = "\u001B[33m"; 86 | String BLUE = "\u001B[34m"; 87 | String MAGENTA = "\u001B[35m"; 88 | String CYAN = "\u001B[36m"; 89 | String WHITE = "\u001B[37m"; 90 | 91 | // 背景颜色 92 | String BG_BLACK = "\u001B[40m"; 93 | String BG_RED = "\u001B[41m"; 94 | String BG_GREEN = "\u001B[42m"; 95 | String BG_YELLOW = "\u001B[43m"; 96 | String BG_BLUE = "\u001B[44m"; 97 | String BG_MAGENTA = "\u001B[45m"; 98 | String BG_CYAN = "\u001B[46m"; 99 | String BG_WHITE = "\u001B[47m"; 100 | } 101 | 102 | @SuppressWarnings("unused") 103 | private interface ConsoleFont { 104 | // 字体样式 105 | String BOLD = "\u001B[1m"; 106 | String ITALIC = "\u001B[3m"; 107 | String UNDERLINE = "\u001B[4m"; 108 | String INVERSE = "\u001B[7m"; 109 | } 110 | } 111 | 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /src/main/java/com/lemontree/Utils.java: -------------------------------------------------------------------------------- 1 | package com.lemontree; 2 | 3 | import com.alibaba.fastjson2.JSONArray; 4 | import com.alibaba.fastjson2.JSONObject; 5 | 6 | import java.awt.*; 7 | import java.awt.datatransfer.Clipboard; 8 | import java.awt.datatransfer.DataFlavor; 9 | import java.awt.datatransfer.Transferable; 10 | import java.awt.datatransfer.UnsupportedFlavorException; 11 | import java.io.*; 12 | import java.net.*; 13 | import java.net.http.HttpClient; 14 | import java.net.http.HttpConnectTimeoutException; 15 | import java.net.http.HttpRequest; 16 | import java.net.http.HttpResponse; 17 | import java.nio.charset.StandardCharsets; 18 | import java.nio.file.Files; 19 | import java.nio.file.Path; 20 | import java.nio.file.Paths; 21 | import java.nio.file.StandardCopyOption; 22 | import java.rmi.UnexpectedException; 23 | import java.security.MessageDigest; 24 | import java.security.NoSuchAlgorithmException; 25 | import java.text.SimpleDateFormat; 26 | import java.util.TimerTask; 27 | import java.util.regex.Matcher; 28 | import java.util.regex.Pattern; 29 | import java.util.stream.IntStream; 30 | 31 | public class Utils { 32 | private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 33 | private final Logger logger; 34 | private TrayIcon icon; 35 | private String BvID = ""; 36 | private long usedTime; 37 | 38 | public Utils(Logger logger) { 39 | this(logger, null); 40 | } 41 | 42 | public Utils(Logger logger, TrayIcon icon) { 43 | this.logger = logger; 44 | this.icon = icon; 45 | } 46 | 47 | public class Monitor extends TimerTask { 48 | private String lastCheckedString = null; 49 | 50 | @Override 51 | public void run() { 52 | Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 53 | try { 54 | String currentString = getClipBoardString(clipboard); 55 | if(currentString != null && !currentString.equals(lastCheckedString)) { 56 | lastCheckedString = currentString; 57 | Transferable parserContent = parseVideoInfo(currentString); 58 | if(parserContent != null) { 59 | clipboard.setContents(parserContent, null); 60 | displayMessage(); 61 | try { 62 | lastCheckedString = getClipBoardString(clipboard); 63 | } catch(Exception e) { 64 | // Keep lastCheckedString as the original string 65 | } 66 | } 67 | } 68 | } catch(Exception e) { 69 | logger.Error("Error: " + e.getMessage()); 70 | } 71 | } 72 | 73 | private String getClipBoardString(Clipboard clipboard) throws IOException, UnsupportedFlavorException { 74 | Transferable contents = clipboard.getContents(null); 75 | if(contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { 76 | return (String) contents.getTransferData(DataFlavor.stringFlavor); 77 | } 78 | return null; 79 | } 80 | 81 | private Transferable parseVideoInfo(String text) { 82 | try { 83 | return getVideoInfo(text); 84 | } catch(IOException e) { 85 | logger.Error("Error parsing video info: " + e.getMessage()); 86 | return null; 87 | } catch(InterruptedException e) { 88 | throw new RuntimeException(e); 89 | } 90 | } 91 | 92 | private void displayMessage() { 93 | if(icon == null) return; 94 | icon.displayMessage("BParser", 95 | String.format("Parsed video %s in %s ms", BvID, usedTime), 96 | TrayIcon.MessageType.INFO); 97 | } 98 | } 99 | 100 | public Runnable clipMonitor = new Monitor(); 101 | 102 | public void setIcon(TrayIcon icon) { 103 | this.icon = icon; 104 | } 105 | 106 | public String Search(String url, Pattern pattern) { 107 | Matcher matcher = pattern.matcher(url); 108 | if(!matcher.find()) return null; 109 | else return matcher.group(); 110 | } 111 | 112 | /** 113 | * api请求器 114 | * 115 | * @param urlString Api链接 116 | * @param videoID 视频链接 117 | * @return 视频信息 118 | * @throws HttpConnectTimeoutException 错误 119 | */ 120 | public JSONObject request(String urlString, String videoID) throws IOException, InterruptedException { 121 | URI uri = URI.create(urlString + videoID); 122 | HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().header("Accept-Charset", "UTF-8").build(); 123 | 124 | HttpResponse response; 125 | try(HttpClient client = HttpClient.newHttpClient()) { 126 | response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); 127 | if(response.statusCode() == 200) { 128 | String apiData = response.body(); 129 | return JSONObject.parseObject(apiData); 130 | } else throw new HttpConnectTimeoutException("请求失败,状态码: " + response.statusCode()); 131 | } 132 | } 133 | 134 | /** 135 | * 这是为这个项目添加的介绍,不建议复制 136 | */ 137 | public void introduce() { 138 | 139 | System.out.println(Constant.IntroduceBParser); 140 | System.out.println(" \u001B[3mby LemonTree\u001B[0m"); 141 | System.out.println("================================================================"); 142 | } 143 | 144 | public String downloadFile(String urlString) throws IOException { 145 | URI uri = URI.create(urlString); 146 | String fileName = uri.getPath().substring(uri.getPath().lastIndexOf('/') + 1); 147 | String temp = System.getProperty("java.io.tmpdir"); 148 | Path targetFilePath = Paths.get(temp, "BParser", fileName); 149 | 150 | Files.createDirectories(targetFilePath.getParent()); 151 | 152 | HttpRequest request = HttpRequest.newBuilder() 153 | .uri(uri) 154 | .GET() 155 | .build(); 156 | 157 | HttpResponse response; 158 | try(HttpClient client = HttpClient.newHttpClient()) { 159 | response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); 160 | if(response.statusCode() == 200) { 161 | try(InputStream in = response.body()) { 162 | Files.copy(in, targetFilePath, StandardCopyOption.REPLACE_EXISTING); 163 | } 164 | return targetFilePath.toUri().toString(); 165 | } else { 166 | throw new IOException("下载文件失败,状态码:" + response.statusCode()); 167 | } 168 | } catch(InterruptedException e) { 169 | throw new RuntimeException(e); 170 | } 171 | } 172 | 173 | public String strToSHA256(String input) { 174 | try { 175 | MessageDigest digest = MessageDigest.getInstance("SHA-256"); 176 | byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8)); 177 | 178 | StringBuilder hexString = new StringBuilder(); 179 | for(byte hashByte : hashBytes) { 180 | String hex = Integer.toHexString(0xff & hashByte); 181 | if(hex.length() == 1) hexString.append('0'); 182 | hexString.append(hex); 183 | } 184 | 185 | return hexString.toString(); 186 | } catch(NoSuchAlgorithmException e) { 187 | logger.Error("发生错误: " + e); 188 | return "Error"; 189 | } 190 | } 191 | 192 | public Transferable getVideoInfo(String url) throws IOException, InterruptedException { 193 | logger.Info("获取剪切板 | S:" + url.length() + " | " + strToSHA256(url)); 194 | String BvIDMayBeEmpty = Search(url, Constant.BvPattern); 195 | BvID = BvIDMayBeEmpty == null? null: BvIDMayBeEmpty.substring(7, 19); 196 | 197 | if(BvID == null) return null; 198 | else logger.Video("解析到BvId: " + BvID); 199 | long startTime = System.currentTimeMillis(); 200 | 201 | JSONObject videoInfoJson = request(Constant.videoInfoApiUrl, BvID); 202 | 203 | if(videoInfoJson == null) throw new HttpConnectTimeoutException("2"); 204 | 205 | JSONObject BVData = (JSONObject) videoInfoJson.get("data"); 206 | JSONObject VideoStat = (JSONObject) BVData.get("stat"); 207 | String VideoTitle = (String) BVData.get("title"); 208 | String PicUrl = BVData.get("pic").toString(); 209 | 210 | // 对分集视频的判断 211 | String perPageInt = Search(url, Constant.pagePattern); 212 | int page = perPageInt == null? -1: perPageInt.charAt(perPageInt.length() - 1) == '&'? 213 | Integer.parseInt(perPageInt.substring(3, perPageInt.length() - 1)): 214 | Integer.parseInt(perPageInt.substring(3)); 215 | 216 | JSONObject videoPageInfoJson = request(Constant.pageInfoApiUrl, BvID); 217 | JSONArray pageData = videoPageInfoJson.getJSONArray("data"); 218 | 219 | String wholeInfo; 220 | if(pageData.size() <= 1) { 221 | if(page != -1) logger.Warn("在链接中检查到分集,在api请求中没有检测到,按照没有分集处理"); 222 | 223 | wholeInfo = String.format( 224 | "%s
发布时间: %s
up: %s
评论数: %s
收藏数: %s
硬币数: %s
点赞数: %s
https://www.bilibili.com/video/%s ", 225 | VideoTitle, format.format((long) (int) BVData.get("pubdate") * 1000), 226 | JSONObject.parseObject(BVData.get("owner").toString()).get("name"), 227 | VideoStat.get("reply"), VideoStat.get("favorite"), VideoStat.get("coin"), 228 | VideoStat.get("like"), BvID 229 | ); 230 | } else { 231 | int indexOfPage = page == -1? 1: page; 232 | String partName = IntStream.range(0, pageData.size()) 233 | .mapToObj(pageData::getJSONObject) 234 | .filter(partedVideo -> partedVideo.getInteger("page") == indexOfPage) 235 | .findFirst().map(partedVideo -> partedVideo.getString("part")) 236 | .orElse("PART NAME NOT FOUND"); 237 | 238 | wholeInfo = String.format( 239 | "%s
分集: %s
发布时间: %s
up: %s
评论数: %s
收藏数: %s
硬币数: %s
点赞数: %s
https://www.bilibili.com/video/%s ", 240 | VideoTitle, partName, format.format((long) (int) BVData.get("pubdate") * 1000), 241 | JSONObject.parseObject(BVData.get("owner").toString()).get("name"), 242 | VideoStat.get("reply"), VideoStat.get("favorite"), VideoStat.get("coin"), 243 | VideoStat.get("like"), BvID + "?p=" + indexOfPage 244 | ); 245 | } 246 | 247 | 248 | usedTime = System.currentTimeMillis() - startTime; 249 | try { 250 | if(PicUrl == null) logger.Warn("无法获取图片链接"); 251 | Transferable vidInfo = PicUrl == null? 252 | new FormatInfo(null, wholeInfo): new FormatInfo(downloadFile(PicUrl), wholeInfo); 253 | logger.Video("构建视频信息成功, 用时: " + usedTime + "ms"); 254 | return vidInfo; 255 | } catch(Exception e) { 256 | throw new UnexpectedException("构建视频信息失败, 用时: " + usedTime + "ms", e); 257 | } 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /src/main/resources/com/lemontree/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LemonTreeLT/BParser/97c1b3ee96c5f6060292af0849fa9bfd43a6ffa2/src/main/resources/com/lemontree/icon.ico -------------------------------------------------------------------------------- /src/main/resources/com/lemontree/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LemonTreeLT/BParser/97c1b3ee96c5f6060292af0849fa9bfd43a6ffa2/src/main/resources/com/lemontree/icon.png --------------------------------------------------------------------------------