You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.8 KiB
52 lines
1.8 KiB
package com.music.command;
|
|
|
|
import com.music.exception.CrawlerException;
|
|
import com.music.repository.SongRepository;
|
|
import com.music.strategy.CrawlStrategy;
|
|
import com.music.strategy.StrategyFactory;
|
|
import com.music.view.ConsoleView;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
public class CrawlCommand implements Command {
|
|
private static final Logger logger = LoggerFactory.getLogger(CrawlCommand.class);
|
|
private final ConsoleView view;
|
|
private final StrategyFactory factory;
|
|
|
|
public CrawlCommand(ConsoleView view, StrategyFactory factory) {
|
|
this.view = view;
|
|
this.factory = factory;
|
|
}
|
|
|
|
@Override
|
|
public String getName() {
|
|
return "crawl";
|
|
}
|
|
|
|
@Override
|
|
public void execute(String[] args, SongRepository repository) {
|
|
if (args.length < 2) {
|
|
view.printError("用法: crawl <platform> (netease/qq/kugou)");
|
|
return;
|
|
}
|
|
String platform = args[1];
|
|
CrawlStrategy strategy = factory.getStrategy(platform);
|
|
if (strategy == null) {
|
|
view.printError("不支持的平台: " + platform + ",可选:netease, qq, kugou");
|
|
return;
|
|
}
|
|
view.printInfo("正在爬取 " + platform + " 热歌榜...");
|
|
try {
|
|
var songs = strategy.crawl(50); // 爬取前50首
|
|
repository.addAll(songs);
|
|
view.printSuccess(String.format("成功爬取 %d 首歌曲", songs.size()));
|
|
logger.info("爬取完成,平台={}, 数量={}", platform, songs.size());
|
|
} catch (CrawlerException e) {
|
|
view.printError("爬取失败: " + e.getMessage());
|
|
logger.error("爬取异常", e);
|
|
} catch (Exception e) {
|
|
view.printError("未知错误: " + e.getMessage());
|
|
logger.error("未知异常", e);
|
|
}
|
|
}
|
|
}
|