repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
2977094657/BilibiliHistoryFetcher
73,648
routers/viewing_analytics.py
import sqlite3 from datetime import datetime from typing import Optional from fastapi import APIRouter, Query, HTTPException from scripts.utils import load_config, get_output_path router = APIRouter() config = load_config() def get_db(): """获取数据库连接""" db_path = get_output_path(config['db_file']) return sqlite3.connect(db_path) def generate_continuity_insights(continuity_data: dict) -> dict: """生成连续性相关的洞察""" insights = {} # 连续性洞察 max_streak = continuity_data['max_streak'] current_streak = continuity_data['current_streak'] # 根据连续天数生成评价 streak_comment = "" if max_streak >= 30: streak_comment = "看来是B站的重度使用者" elif max_streak >= 14: streak_comment = "看来你对B站情有独钟呢!" else: streak_comment = "你的观看习惯比较随性自由。" insights['continuity'] = f"你最长连续观看B站达到了{max_streak}天,{streak_comment}目前已经连续观看了{current_streak}天。" return insights def analyze_viewing_continuity(cursor, table_name: str) -> dict: """分析观看习惯的连续性 Args: cursor: 数据库游标 table_name: 表名 Returns: dict: 连续性分析结果 """ # 获取所有观看日期 cursor.execute(f""" SELECT DISTINCT date(datetime(view_at + 28800, 'unixepoch')) as view_date FROM {table_name} ORDER BY view_date """) dates = [row[0] for row in cursor.fetchall()] # 计算连续观看天数 max_streak = current_streak = 1 longest_streak_start = longest_streak_end = current_streak_start = dates[0] if dates else None for i in range(1, len(dates)): date1 = datetime.strptime(dates[i-1], '%Y-%m-%d') date2 = datetime.strptime(dates[i], '%Y-%m-%d') if (date2 - date1).days == 1: current_streak += 1 if current_streak > max_streak: max_streak = current_streak longest_streak_start = datetime.strptime(dates[i-max_streak+1], '%Y-%m-%d').strftime('%Y-%m-%d') longest_streak_end = dates[i] else: current_streak = 1 current_streak_start = dates[i] return { 'max_streak': max_streak, 'longest_streak_period': { 'start': longest_streak_start, 'end': longest_streak_end }, 'current_streak': current_streak, 'current_streak_start': current_streak_start } def analyze_time_investment(cursor, table_name: str) -> dict: """分析时间投入强度 Args: cursor: 数据库游标 table_name: 表名 Returns: dict: 时间投入分析结果 """ cursor.execute(f""" SELECT date(datetime(view_at + 28800, 'unixepoch')) as view_date, COUNT(*) as video_count, SUM(CASE WHEN progress = -1 THEN duration ELSE progress END) as total_duration FROM {table_name} GROUP BY view_date ORDER BY total_duration DESC LIMIT 1 """) max_duration_day = cursor.fetchone() cursor.execute(f""" SELECT AVG(daily_duration) as avg_duration FROM ( SELECT date(datetime(view_at + 28800, 'unixepoch')) as view_date, SUM(CASE WHEN progress = -1 THEN duration ELSE progress END) as daily_duration FROM {table_name} GROUP BY view_date ) """) avg_daily_duration = cursor.fetchone()[0] return { 'max_duration_day': { 'date': max_duration_day[0], 'video_count': max_duration_day[1], 'total_duration': max_duration_day[2] }, 'avg_daily_duration': avg_daily_duration } def analyze_completion_rates(cursor, table_name: str) -> dict: """分析视频完成率""" # 获取表结构 cursor.execute(f"PRAGMA table_info({table_name})") columns = {col[1]: idx for idx, col in enumerate(cursor.fetchall())} # 确保必要的列存在 required_columns = ['duration', 'progress', 'author_name', 'author_mid', 'tag_name'] for col in required_columns: if col not in columns: raise ValueError(f"Required column '{col}' not found in table {table_name}") cursor.execute(f"SELECT * FROM {table_name}") histories = cursor.fetchall() # 基础统计 total_videos = len(histories) total_completion = 0 fully_watched = 0 not_started = 0 # UP主统计 author_stats = {} # 分区统计 tag_stats = {} # 时长分布统计 duration_stats = { "短视频(≤5分钟)": {"video_count": 0, "total_completion": 0, "fully_watched": 0, "average_completion_rate": 0}, "中等视频(5-20分钟)": {"video_count": 0, "total_completion": 0, "fully_watched": 0, "average_completion_rate": 0}, "长视频(>20分钟)": {"video_count": 0, "total_completion": 0, "fully_watched": 0, "average_completion_rate": 0} } # 完成率分布 completion_distribution = { "0-10%": 0, "10-30%": 0, "30-50%": 0, "50-70%": 0, "70-90%": 0, "90-100%": 0 } for history in histories: # 获取并转换数据类型 try: duration = float(history[columns['duration']]) if history[columns['duration']] else 0 progress = float(history[columns['progress']]) if history[columns['progress']] else 0 author_name = history[columns['author_name']] author_mid = history[columns['author_mid']] tag_name = history[columns['tag_name']] except (ValueError, TypeError) as e: print(f"Warning: Failed to process record: {history}") continue # 计算完成率 # 当progress为-1时表示已完全观看,计算为100% if progress == -1: completion_rate = 100 else: completion_rate = (progress / duration * 100) if duration > 0 else 0 total_completion += completion_rate # 统计完整观看和未开始观看 if completion_rate >= 90: # 90%以上视为完整观看 fully_watched += 1 elif completion_rate == 0: not_started += 1 # 更新完成率分布 if completion_rate <= 10: completion_distribution["0-10%"] += 1 elif completion_rate <= 30: completion_distribution["10-30%"] += 1 elif completion_rate <= 50: completion_distribution["30-50%"] += 1 elif completion_rate <= 70: completion_distribution["50-70%"] += 1 elif completion_rate <= 90: completion_distribution["70-90%"] += 1 else: completion_distribution["90-100%"] += 1 # UP主统计 if author_name and author_mid: if author_name not in author_stats: author_stats[author_name] = { "author_mid": author_mid, "video_count": 0, "total_completion": 0, "fully_watched": 0 } stats = author_stats[author_name] stats["video_count"] += 1 stats["total_completion"] += completion_rate if completion_rate >= 90: stats["fully_watched"] += 1 # 分区统计 if tag_name: if tag_name not in tag_stats: tag_stats[tag_name] = { "video_count": 0, "total_completion": 0, "fully_watched": 0 } stats = tag_stats[tag_name] stats["video_count"] += 1 stats["total_completion"] += completion_rate if completion_rate >= 90: stats["fully_watched"] += 1 # 时长分布统计 if duration <= 300: # 5分钟 category = "短视频(≤5分钟)" elif duration <= 1200: # 20分钟 category = "中等视频(5-20分钟)" else: category = "长视频(>20分钟)" stats = duration_stats[category] stats["video_count"] += 1 stats["total_completion"] += completion_rate if completion_rate >= 90: stats["fully_watched"] += 1 # 计算总体统计 overall_stats = { "total_videos": total_videos, "average_completion_rate": round(total_completion / total_videos, 2) if total_videos > 0 else 0, "fully_watched_count": fully_watched, "not_started_count": not_started, "fully_watched_rate": round(fully_watched / total_videos * 100, 2) if total_videos > 0 else 0, "not_started_rate": round(not_started / total_videos * 100, 2) if total_videos > 0 else 0 } # 计算各类视频的平均完成率和完整观看率 for category, stats in duration_stats.items(): if stats["video_count"] > 0: stats["average_completion_rate"] = round(stats["total_completion"] / stats["video_count"], 2) stats["fully_watched_rate"] = round(stats["fully_watched"] / stats["video_count"] * 100, 2) else: stats["average_completion_rate"] = 0 stats["fully_watched_rate"] = 0 # 计算UP主平均完成率和完整观看率,并按观看数量筛选和排序 filtered_authors = {} for name, stats in author_stats.items(): if stats["video_count"] >= 5: # 只保留观看数量>=5的UP主 stats["average_completion_rate"] = round(stats["total_completion"] / stats["video_count"], 2) stats["fully_watched_rate"] = round(stats["fully_watched"] / stats["video_count"] * 100, 2) filtered_authors[name] = stats most_watched_authors = {} highest_completion_authors = {} # 计算分区平均完成率和完整观看率,并按观看数量筛选和排序 filtered_tags = {} for tag, stats in tag_stats.items(): if stats["video_count"] >= 5: # 只保留视频数量>=5的分区 stats["average_completion_rate"] = round(stats["total_completion"] / stats["video_count"], 2) stats["fully_watched_rate"] = round(stats["fully_watched"] / stats["video_count"] * 100, 2) filtered_tags[tag] = stats top_tags = {} return { "overall_stats": overall_stats, "duration_based_stats": duration_stats, "completion_distribution": completion_distribution, "tag_completion_rates": top_tags, "most_watched_authors": most_watched_authors, "highest_completion_authors": highest_completion_authors } def generate_completion_insights(completion_data: dict) -> dict: """生成视频完成率相关的洞察""" insights = {} try: # 整体完成率洞察 overall = completion_data.get("overall_stats", {}) if overall: insights["overall_completion"] = ( f"在观看的{overall.get('total_videos', 0)}个视频中,你平均观看完成率为{overall.get('average_completion_rate', 0)}%," f"完整看完的视频占比{overall.get('fully_watched_rate', 0)}%,未开始观看的占比{overall.get('not_started_rate', 0)}%。" ) # 视频时长偏好洞察 duration_stats = completion_data.get("duration_based_stats", {}) if duration_stats: valid_durations = [(k, v) for k, v in duration_stats.items() if v.get("video_count", 0) > 0 and v.get("average_completion_rate", 0) > 0] if valid_durations: max_completion_duration = max(valid_durations, key=lambda x: x[1].get("average_completion_rate", 0)) insights["duration_preference"] = ( f"你最容易看完的是{max_completion_duration[0]},平均完成率达到{max_completion_duration[1].get('average_completion_rate', 0)}%," f"其中完整看完的视频占比{max_completion_duration[1].get('fully_watched_rate', 0)}%。" ) # 分区兴趣洞察 tag_rates = completion_data.get("tag_completion_rates", {}) if tag_rates: valid_tags = [(k, v) for k, v in tag_rates.items() if v.get("video_count", 0) >= 5] # 只考虑观看数量>=5的分区 if valid_tags: top_tag = max(valid_tags, key=lambda x: x[1].get("average_completion_rate", 0)) insights["tag_completion"] = ( f"在经常观看的分区中,你对{top_tag[0]}分区的视频最感兴趣,平均完成率达到{top_tag[1].get('average_completion_rate', 0)}%," f"观看过{top_tag[1].get('video_count', 0)}个该分区的视频。" ) # UP主偏好洞察 most_watched = completion_data.get("most_watched_authors", {}) if most_watched: top_watched = next(iter(most_watched.items()), None) if top_watched: insights["most_watched_author"] = ( f"你观看最多的UP主是{top_watched[0]},观看了{top_watched[1].get('video_count', 0)}个视频," f"平均完成率为{top_watched[1].get('average_completion_rate', 0)}%。" ) highest_completion = completion_data.get("highest_completion_authors", {}) if highest_completion and most_watched: top_completion = next(iter(highest_completion.items()), None) if top_completion and top_completion[0] != next(iter(most_watched.keys())): insights["highest_completion_author"] = ( f"在经常观看的UP主中,你对{top_completion[0]}的视频完成度最高," f"平均完成率达到{top_completion[1].get('average_completion_rate', 0)}%," f"观看过{top_completion[1].get('video_count', 0)}个视频。" ) except Exception as e: print(f"Error generating completion insights: {str(e)}") # 返回一个基础的洞察信息 insights["basic_completion"] = "暂时无法生成详细的观看完成率分析。" return insights def analyze_video_watch_counts(cursor, table_name: str) -> dict: """分析视频观看次数""" # 获取表结构 cursor.execute(f"PRAGMA table_info({table_name})") columns = {col[1]: idx for idx, col in enumerate(cursor.fetchall())} # 确保必要的列存在 required_columns = ['title', 'bvid', 'duration', 'tag_name', 'author_name'] for col in required_columns: if col not in columns: raise ValueError(f"Required column '{col}' not found in table {table_name}") # 获取视频观看次数统计 cursor.execute(f""" SELECT title, bvid, duration, tag_name, author_name, COUNT(*) as watch_count, MIN(view_at) as first_view, MAX(view_at) as last_view FROM {table_name} WHERE bvid IS NOT NULL AND bvid != '' GROUP BY bvid HAVING COUNT(*) > 1 ORDER BY watch_count DESC """) results = cursor.fetchall() # 处理统计结果 most_watched_videos = [] total_rewatched = 0 total_videos = len(results) duration_distribution = { "短视频(≤5分钟)": 0, "中等视频(5-20分钟)": 0, "长视频(>20分钟)": 0 } tag_distribution = {} for row in results: title = row[0] bvid = row[1] duration = float(row[2]) if row[2] else 0 tag_name = row[3] author_name = row[4] watch_count = row[5] first_view = row[6] last_view = row[7] # 统计重复观看的视频时长分布 if duration <= 300: duration_distribution["短视频(≤5分钟)"] += 1 elif duration <= 1200: duration_distribution["中等视频(5-20分钟)"] += 1 else: duration_distribution["长视频(>20分钟)"] += 1 # 记录观看次数最多的视频 if len(most_watched_videos) < 10: most_watched_videos.append({ "title": title, "bvid": bvid, "duration": duration, "tag_name": tag_name, "author_name": author_name, "watch_count": watch_count, "first_view": first_view, "last_view": last_view, "avg_interval": (last_view - first_view) / (watch_count - 1) if watch_count > 1 else 0 }) total_rewatched += watch_count - 1 # 获取总视频数 cursor.execute(f"SELECT COUNT(DISTINCT bvid) FROM {table_name}") total_unique_videos = cursor.fetchone()[0] # 计算重复观看率 rewatch_rate = round(total_videos / total_unique_videos * 100, 2) # 获取分区排名 tag_ranking = sorted( tag_distribution.items(), key=lambda x: x[1], reverse=True )[:10] return { "rewatch_stats": { "total_rewatched_videos": total_videos, "total_unique_videos": total_unique_videos, "rewatch_rate": rewatch_rate, "total_rewatch_count": total_rewatched }, "most_watched_videos": most_watched_videos, "duration_distribution": duration_distribution, "tag_distribution": dict(tag_ranking) } def generate_watch_count_insights(watch_count_data: dict) -> dict: """生成视频观看次数相关的洞察""" insights = {} try: # 重复观看统计洞察 rewatch_stats = watch_count_data.get("rewatch_stats", {}) total_videos = rewatch_stats.get('total_unique_videos', 0) rewatched_videos = rewatch_stats.get('total_rewatched_videos', 0) rewatch_rate = rewatch_stats.get('rewatch_rate', 0) total_rewatches = rewatch_stats.get('total_rewatch_count', 0) if rewatched_videos > 0: avg_watches_per_video = round(total_rewatches/rewatched_videos + 1, 1) insights["rewatch_overview"] = ( f"在你观看的{total_videos}个视频中,有{rewatched_videos}个视频被重复观看," f"重复观看率为{rewatch_rate}%。这些视频总共被额外观看了{total_rewatches}次," f"平均每个重复观看的视频被看了{avg_watches_per_video}次。" ) else: insights["rewatch_overview"] = f"在你观看的{total_videos}个视频中,暂时还没有重复观看的视频。" # 最多观看视频洞察 most_watched = watch_count_data.get("most_watched_videos", []) if most_watched: top_videos = most_watched[:3] # 取前三 top_video = top_videos[0] # 计算平均重看间隔(天) avg_interval_days = round(top_video.get('avg_interval', 0) / (24 * 3600), 1) if avg_interval_days > 0: insights["most_watched_videos"] = ( f"你最喜欢的视频是{top_video.get('author_name', '未知作者')}的《{top_video.get('title', '未知视频')}》," f"共观看了{top_video.get('watch_count', 0)}次,平均每{avg_interval_days}天就会重看一次。" ) else: insights["most_watched_videos"] = ( f"你最喜欢的视频是{top_video.get('author_name', '未知作者')}的《{top_video.get('title', '未知视频')}》," f"共观看了{top_video.get('watch_count', 0)}次。" ) if len(top_videos) > 1: other_favorites = [ f"{v.get('author_name', '未知作者')}的《{v.get('title', '未知视频')}》({v.get('watch_count', 0)}次)" for v in top_videos[1:3] ] insights["most_watched_videos"] += f"紧随其后的是{' 和 '.join(other_favorites)}。" # 重复观看视频时长分布洞察 duration_dist = watch_count_data.get("duration_distribution", {}) if duration_dist: total_rewatched = sum(duration_dist.values()) if total_rewatched > 0: duration_percentages = { k: round(v/total_rewatched * 100, 1) for k, v in duration_dist.items() } sorted_durations = sorted( duration_percentages.items(), key=lambda x: x[1], reverse=True ) insights["duration_preference"] = ( f"在重复观看的视频中,{sorted_durations[0][0]}最多,占比{sorted_durations[0][1]}%。" f"其次是{sorted_durations[1][0]}({sorted_durations[1][1]}%)," f"而{sorted_durations[2][0]}占比{sorted_durations[2][1]}%。" f"这表明你在重复观看时更偏好{sorted_durations[0][0].replace('视频', '')}的内容。" ) # 重复观看分区分布洞察 tag_dist = watch_count_data.get("tag_distribution", {}) if tag_dist: total_tags = sum(tag_dist.values()) if total_tags > 0: top_tags = sorted(tag_dist.items(), key=lambda x: x[1], reverse=True)[:3] tag_insights = [] for tag, count in top_tags: percentage = round(count/total_tags * 100, 1) tag_insights.append(f"{tag}({count}个视频, {percentage}%)") insights["tag_preference"] = ( f"你最常重复观看的内容类型是{tag_insights[0]}。" f"紧随其后的是{' 和 '.join(tag_insights[1:])}。" ) # 生成总体观看行为总结 if rewatched_videos > 0: insights["behavior_summary"] = ( f"总的来说,你是一位{_get_rewatch_habit_description(rewatch_rate)}。" f"你特别喜欢重复观看{_get_preferred_content_type(tag_dist, duration_dist)}的内容。" ) else: insights["behavior_summary"] = "总的来说,你喜欢探索新的内容,很少重复观看同一个视频。" except Exception as e: print(f"Error generating watch count insights: {str(e)}") insights["basic_watch_count"] = "暂时无法生成详细的重复观看分析。" return insights def _get_rewatch_habit_description(rewatch_rate: float) -> str: """根据重复观看率描述用户习惯""" if rewatch_rate < 2: return "喜欢探索新内容的观众" elif rewatch_rate < 5: return "对特定内容会重复观看的观众" else: return "经常重复观看喜欢内容的忠实观众" def _get_preferred_content_type(tag_dist: dict, duration_dist: dict) -> str: """根据分区和时长分布描述用户偏好""" if not tag_dist or not duration_dist: return "多样化" top_tag = max(tag_dist.items(), key=lambda x: x[1])[0] top_duration = max(duration_dist.items(), key=lambda x: x[1])[0] return f"{top_duration.replace('视频', '')}的{top_tag}" def get_available_years(): """获取数据库中所有可用的年份""" conn = get_db() try: cursor = conn.cursor() cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'bilibili_history_%' ORDER BY name DESC """) years = [] for (table_name,) in cursor.fetchall(): try: year = int(table_name.split('_')[-1]) years.append(year) except (ValueError, IndexError): continue return sorted(years, reverse=True) except sqlite3.Error as e: print(f"获取年份列表时发生错误: {e}") return [] finally: if conn: conn.close() def validate_year_and_get_table(year: Optional[int]) -> tuple: """验证年份并返回表名和可用年份列表 Args: year: 要验证的年份,None表示使用最新年份 Returns: tuple: (table_name, target_year, available_years) 或 (None, None, error_response) """ # 获取可用年份列表 available_years = get_available_years() if not available_years: error_response = { "status": "error", "message": "未找到任何历史记录数据" } return None, None, error_response # 如果未指定年份,使用最新的年份 target_year = year if year is not None else available_years[0] # 检查指定的年份是否可用 if year is not None and year not in available_years: error_response = { "status": "error", "message": f"未找到 {year} 年的历史记录数据。可用的年份有:{', '.join(map(str, available_years))}" } return None, None, error_response table_name = f"bilibili_history_{target_year}" return table_name, target_year, available_years @router.get("/monthly-stats", summary="获取月度观看统计分析") async def get_monthly_stats( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取月度观看统计分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含月度观看统计分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'monthly_stats') if cached_response: print(f"从缓存获取 {target_year} 年的月度统计分析数据") return cached_response print(f"开始分析 {target_year} 年的月度观看统计数据") # 月度观看统计 cursor.execute(f""" SELECT strftime('%Y-%m', datetime(view_at + 28800, 'unixepoch')) as month, COUNT(*) as view_count FROM {table_name} GROUP BY month ORDER BY month """) monthly_stats = {row[0]: row[1] for row in cursor.fetchall()} # 计算总视频数和活跃天数 cursor.execute(f"SELECT COUNT(*) FROM {table_name}") total_videos = cursor.fetchone()[0] cursor.execute(f""" SELECT COUNT(DISTINCT strftime('%Y-%m-%d', datetime(view_at + 28800, 'unixepoch'))) FROM {table_name} """) active_days = cursor.fetchone()[0] # 计算平均每日观看数 avg_daily_videos = round(total_videos / active_days, 1) if active_days > 0 else 0 # 生成月度洞察 monthly_insights = {} # 添加总体活动洞察 if total_videos > 0 and active_days > 0: monthly_insights['overall_activity'] = f"今年以来,你在B站观看了{total_videos}个视频,平均每天观看{avg_daily_videos}个视频" if monthly_stats: max_month = max(monthly_stats.items(), key=lambda x: x[1]) min_month = min(monthly_stats.items(), key=lambda x: x[1]) # 计算月度趋势 months = sorted(monthly_stats.keys()) month_trend = "" if len(months) >= 2: first_month_count = monthly_stats[months[0]] last_month_count = monthly_stats[months[-1]] if last_month_count > first_month_count * 1.2: month_trend = "你在B站观看视频的热情正在逐月增长,看来你越来越喜欢B站了呢!" elif last_month_count < first_month_count * 0.8: month_trend = "最近你在B站的活跃度有所下降,可能是工作或学习变得更忙了吧。" else: month_trend = "你在B站的活跃度保持得很稳定,看来已经养成了良好的观看习惯。" monthly_insights['monthly_pattern'] = f"在{max_month[0]}月,你观看了{max_month[1]}个视频,是你最活跃的月份;而在{min_month[0]}月,观看量为{min_month[1]}个。{month_trend}" # 构建响应 response = { "status": "success", "data": { "monthly_stats": monthly_stats, "total_videos": total_videos, "active_days": active_days, "avg_daily_videos": avg_daily_videos, "insights": monthly_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的月度统计分析数据缓存") pattern_cache.cache_patterns(table_name, 'monthly_stats', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/weekly-stats", summary="获取周度观看统计分析") async def get_weekly_stats( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取周度观看统计分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含周度观看统计分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'weekly_stats') if cached_response: print(f"从缓存获取 {target_year} 年的周度统计分析数据") return cached_response print(f"开始分析 {target_year} 年的周度观看统计数据") # 计算活跃天数(用于洞察生成) cursor.execute(f""" SELECT COUNT(DISTINCT strftime('%Y-%m-%d', datetime(view_at + 28800, 'unixepoch'))) as active_days FROM {table_name} """) active_days = cursor.fetchone()[0] or 0 # 每周观看分布(0=周日,1-6=周一至周六) weekday_mapping = {'0': '周日', '1': '周一', '2': '周二', '3': '周三', '4': '周四', '5': '周五', '6': '周六'} # 初始化所有星期的默认值为0 weekly_stats = {day: 0 for day in weekday_mapping.values()} cursor.execute(f""" SELECT strftime('%w', datetime(view_at + 28800, 'unixepoch')) as weekday, COUNT(*) as view_count FROM {table_name} GROUP BY weekday ORDER BY weekday """) # 更新有数据的星期的值 for row in cursor.fetchall(): weekly_stats[weekday_mapping[row[0]]] = row[1] # 季节性观看模式分析 cursor.execute(f""" SELECT CASE WHEN CAST(strftime('%m', datetime(view_at + 28800, 'unixepoch')) AS INTEGER) IN (1,2,3) THEN '春季' WHEN CAST(strftime('%m', datetime(view_at + 28800, 'unixepoch')) AS INTEGER) IN (4,5,6) THEN '夏季' WHEN CAST(strftime('%m', datetime(view_at + 28800, 'unixepoch')) AS INTEGER) IN (7,8,9) THEN '秋季' WHEN CAST(strftime('%m', datetime(view_at + 28800, 'unixepoch')) AS INTEGER) IN (10,11,12) THEN '冬季' END as season, COUNT(*) as view_count, AVG(CASE WHEN progress = -1 THEN duration ELSE progress END) as avg_duration FROM {table_name} WHERE CAST(strftime('%m', datetime(view_at + 28800, 'unixepoch')) AS INTEGER) BETWEEN 1 AND 12 GROUP BY season """) seasonal_patterns = {row[0]: {'view_count': row[1], 'avg_duration': row[2]} for row in cursor.fetchall()} # 生成周度统计洞察 weekly_insights = {} if weekly_stats and active_days > 0: max_weekday = max(weekly_stats.items(), key=lambda x: x[1]) min_weekday = min(weekly_stats.items(), key=lambda x: x[1]) # 计算工作日和周末的平均值 workday_avg = sum(weekly_stats[day] for day in ['周一', '周二', '周三', '周四', '周五']) / 5 weekend_avg = sum(weekly_stats[day] for day in ['周六', '周日']) / 2 if weekend_avg > workday_avg * 1.5: week_pattern = "你是一位周末党,倾向于在周末集中补番或观看视频。" elif workday_avg > weekend_avg: week_pattern = "工作日反而是你观看视频的主要时间,也许是通过B站来缓解工作压力?" else: week_pattern = "你的观看时间分布很均衡,不管是工作日还是周末都保持着适度的观看习惯。" weekly_insights['weekly_pattern'] = f"{week_pattern}其中{max_weekday[0]}是你最喜欢刷B站的日子,平均会看{round(max_weekday[1]/active_days*7, 1)}个视频;而{min_weekday[0]}的观看量最少。" # 构建响应 response = { "status": "success", "data": { "weekly_stats": weekly_stats, "seasonal_patterns": seasonal_patterns, "insights": weekly_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的周度统计分析数据缓存") pattern_cache.cache_patterns(table_name, 'weekly_stats', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/time-slots", summary="获取时段观看分析") async def get_time_slots( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取时段观看分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含时段观看分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'time_slots') if cached_response: print(f"从缓存获取 {target_year} 年的时段分析数据") return cached_response print(f"开始分析 {target_year} 年的时段观看数据") # 每日时段分布(按小时统计) cursor.execute(f""" SELECT strftime('%H', datetime(view_at + 28800, 'unixepoch')) as hour, COUNT(*) as view_count FROM {table_name} GROUP BY hour ORDER BY hour """) daily_time_slots = {f"{int(row[0])}时": row[1] for row in cursor.fetchall()} # 最活跃时段TOP5 cursor.execute(f""" SELECT strftime('%H', datetime(view_at + 28800, 'unixepoch')) as hour, COUNT(*) as view_count FROM {table_name} GROUP BY hour ORDER BY view_count DESC LIMIT 5 """) peak_hours = [{ "hour": f"{int(row[0])}时", "view_count": row[1] } for row in cursor.fetchall()] # 时间投入分析 - 使用已有的函数 time_investment = analyze_time_investment(cursor, table_name) # 单日最大观看记录 cursor.execute(f""" SELECT date(datetime(view_at + 28800, 'unixepoch')) as view_date, COUNT(*) as video_count FROM {table_name} GROUP BY view_date ORDER BY video_count DESC LIMIT 1 """) max_daily_record = cursor.fetchone() max_daily_record = { 'date': max_daily_record[0], 'video_count': max_daily_record[1] } # 生成时段分析洞察 time_slot_insights = {} if daily_time_slots and peak_hours: # 将一天分为几个时间段 morning = sum(daily_time_slots.get(f"{i}时", 0) for i in range(5, 12)) afternoon = sum(daily_time_slots.get(f"{i}时", 0) for i in range(12, 18)) evening = sum(daily_time_slots.get(f"{i}时", 0) for i in range(18, 23)) night = sum(daily_time_slots.get(f"{i}时", 0) for i in range(23, 24)) + sum(daily_time_slots.get(f"{i}时", 0) for i in range(0, 5)) time_slots = [ ("清晨和上午", morning), ("下午", afternoon), ("傍晚和晚上", evening), ("深夜", night) ] primary_slot = max(time_slots, key=lambda x: x[1]) if primary_slot[0] == "深夜": time_advice = "熬夜看视频可能会影响健康,建议调整作息哦!" else: time_advice = "这个时间段的观看习惯很好,既不影响作息,也能享受视频带来的乐趣。" # 获取最高峰时段 top_hour = peak_hours[0]["hour"] if peak_hours else "未知" time_slot_insights['time_preference'] = f"你最喜欢在{primary_slot[0]}观看B站视频,特别是{top_hour}达到观看高峰。{time_advice}" # 生成单日观看记录洞察 if max_daily_record: time_slot_insights['daily_record'] = f"在{max_daily_record['date']}这一天,你创下了单日观看{max_daily_record['video_count']}个视频的记录!这可能是一个特别的日子,也许是在追番、学习或者在家放松的一天。" # 构建响应 response = { "status": "success", "data": { "daily_time_slots": daily_time_slots, "peak_hours": peak_hours, "time_investment": time_investment, "max_daily_record": max_daily_record, "insights": time_slot_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的时段分析数据缓存") pattern_cache.cache_patterns(table_name, 'time_slots', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/continuity", summary="获取观看连续性分析") async def get_viewing_continuity( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取观看连续性分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含观看连续性分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'viewing_continuity') if cached_response: print(f"从缓存获取 {target_year} 年的观看连续性分析数据") return cached_response print(f"开始分析 {target_year} 年的观看连续性数据") # 分析观看连续性 viewing_continuity = analyze_viewing_continuity(cursor, table_name) # 生成连续性洞察 continuity_insights = generate_continuity_insights(viewing_continuity) # 构建响应 response = { "status": "success", "data": { "viewing_continuity": viewing_continuity, "insights": continuity_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的观看连续性分析数据缓存") pattern_cache.cache_patterns(table_name, 'viewing_continuity', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() def analyze_viewing_details(cursor, table_name: str) -> dict: """分析更详细的观看行为,包括设备、总观看时长等 Args: cursor: 数据库游标 table_name: 表名 Returns: dict: 详细观看行为分析结果 """ # 1. 计算总观看时长(根据progress字段) cursor.execute(f""" SELECT SUM(CASE WHEN progress = -1 THEN duration ELSE progress END) as total_watch_seconds FROM {table_name} WHERE progress IS NOT NULL """) total_seconds = cursor.fetchone()[0] or 0 total_hours = round(total_seconds / 3600, 1) # 2. 计算观看B站的总天数 cursor.execute(f""" SELECT COUNT(DISTINCT strftime('%Y-%m-%d', datetime(view_at + 28800, 'unixepoch'))) as total_days FROM {table_name} """) total_days = cursor.fetchone()[0] or 0 # 3. 分析分区观看数据前10 cursor.execute(f""" SELECT main_category, COUNT(*) as view_count, SUM(CASE WHEN progress = -1 THEN duration ELSE progress END) as total_progress FROM {table_name} WHERE main_category IS NOT NULL AND main_category != '' GROUP BY main_category ORDER BY view_count DESC LIMIT 10 """) category_stats = [ { "category": row[0], "view_count": row[1], "watch_hours": round((row[2] or 0) / 3600, 1) } for row in cursor.fetchall() ] # 4. 年度挚爱UP主 cursor.execute(f""" SELECT author_mid, author_name, COUNT(*) as view_count, SUM(CASE WHEN progress = -1 THEN duration ELSE progress END) as total_progress FROM {table_name} WHERE author_mid IS NOT NULL GROUP BY author_mid ORDER BY view_count DESC LIMIT 10 """) favorite_up_stats = [ { "mid": row[0], "name": row[1], "view_count": row[2], "watch_hours": round((row[3] or 0) / 3600, 1) } for row in cursor.fetchall() ] # 5. 寻找深夜观看记录 # 第一步:创建临时表存储深夜观看记录 cursor.execute(f""" CREATE TEMPORARY TABLE IF NOT EXISTS temp_night_views AS SELECT view_at, author_name, title, strftime('%H', datetime(view_at + 28800, 'unixepoch')) as hour, strftime('%M', datetime(view_at + 28800, 'unixepoch')) as minute, -- 将凌晨时间(00:00-05:00)的日期调整为前一天 CASE WHEN strftime('%H', datetime(view_at + 28800, 'unixepoch')) < '05' THEN date(datetime(view_at + 28800 - 86400, 'unixepoch')) ELSE date(datetime(view_at + 28800, 'unixepoch')) END as adjusted_date, -- 计算小时+分钟的浮点数时间 CASE WHEN strftime('%H', datetime(view_at + 28800, 'unixepoch')) < '05' THEN CAST(strftime('%H', datetime(view_at + 28800, 'unixepoch')) AS REAL) + 24 ELSE CAST(strftime('%H', datetime(view_at + 28800, 'unixepoch')) AS REAL) END + CAST(strftime('%M', datetime(view_at + 28800, 'unixepoch')) AS REAL)/100.0 as hour_with_minute FROM {table_name} WHERE strftime('%H', datetime(view_at + 28800, 'unixepoch')) >= '23' OR strftime('%H', datetime(view_at + 28800, 'unixepoch')) < '05' """) # 第二步:创建临时表存储每天最晚的观看时间 cursor.execute(""" CREATE TEMPORARY TABLE IF NOT EXISTS temp_latest_per_day AS SELECT adjusted_date, MAX(hour_with_minute) as latest_hour_with_minute FROM temp_night_views GROUP BY adjusted_date """) # 第三步:查询每天最晚的观看记录 cursor.execute(""" SELECT t.adjusted_date as date, strftime('%H:%M', datetime(t.view_at + 28800, 'unixepoch')) as time, t.author_name, t.title, t.hour, t.minute, t.hour_with_minute FROM temp_night_views t JOIN temp_latest_per_day l ON t.adjusted_date = l.adjusted_date AND t.hour_with_minute = l.latest_hour_with_minute ORDER BY t.hour_with_minute DESC LIMIT 10 """) late_night_views = [ { "date": row[0], "time": row[1], "author": row[2], "title": row[3], "hour": int(row[4]), "minute": row[5], "hour_with_minute": float(row[6]) } for row in cursor.fetchall() ] # 清理临时表 cursor.execute("DROP TABLE IF EXISTS temp_night_views") cursor.execute("DROP TABLE IF EXISTS temp_latest_per_day") # 6. 各时间段的活跃天数百分比 cursor.execute(f""" SELECT CASE WHEN strftime('%H', datetime(view_at + 28800, 'unixepoch')) BETWEEN '05' AND '11' THEN '上午' WHEN strftime('%H', datetime(view_at + 28800, 'unixepoch')) BETWEEN '12' AND '17' THEN '下午' WHEN strftime('%H', datetime(view_at + 28800, 'unixepoch')) BETWEEN '18' AND '22' THEN '晚上' ELSE '深夜' END as time_slot, COUNT(DISTINCT strftime('%Y-%m-%d', datetime(view_at + 28800, 'unixepoch'))) as active_days FROM {table_name} GROUP BY time_slot """) time_slot_days = {} for row in cursor.fetchall(): time_slot_days[row[0]] = { "days": row[1], "percentage": round(row[1] / total_days * 100, 1) if total_days > 0 else 0 } # 7. 查询最常用的设备信息(如果有) cursor.execute(f""" SELECT CASE WHEN dt IN (1, 3, 5, 7) THEN '手机' WHEN dt = 2 THEN '网页' WHEN dt IN (4, 6) THEN '平板' WHEN dt = 33 THEN '电视' ELSE '其他' END as platform, COUNT(*) as count FROM {table_name} GROUP BY platform ORDER BY count DESC LIMIT 3 """) devices = [{"name": row[0], "count": row[1]} for row in cursor.fetchall()] return { "total_watch_hours": total_hours, "total_days": total_days, "top_categories": category_stats, "favorite_up_users": favorite_up_stats, "late_night_views": late_night_views, "time_slot_activity": time_slot_days, "devices": devices } def generate_viewing_report(viewing_details: dict) -> dict: """根据观看数据生成综合报告和亮点 Args: viewing_details: 观看详细数据 Returns: dict: 包含各种总结语句的报告 """ report = {} # 1. 总观看时长和天数总结 report["total_summary"] = f"和B站共度的{viewing_details['total_days']}天里,你观看超过{viewing_details['total_watch_hours']}小时的内容" # 2. 时间段访问情况 time_slots = viewing_details["time_slot_activity"] max_slot = max(time_slots.items(), key=lambda x: x[1]["percentage"]) if time_slots else None if max_slot: report["time_slot_summary"] = f"{max_slot[0]}时段访问B站天数超过{max_slot[1]['percentage']}%" # 3. 深夜观看记录 if viewing_details["late_night_views"]: # late_night_views已按照最晚时间排序,首条记录是最晚的 latest_view = viewing_details["late_night_views"][0] report["late_night_summary"] = f"{latest_view['date']}你迟迟不肯入睡,{latest_view['time']}还在看{latest_view['author']}的《{latest_view['title']}》" # 4. 分区观看总结 if viewing_details["top_categories"]: top_category = viewing_details["top_categories"][0] report["category_summary"] = f"你最喜欢的分区是{top_category['category']},共观看{top_category['view_count']}个视频,时长{top_category['watch_hours']}小时" # 5. 年度挚爱UP总结 if viewing_details["favorite_up_users"]: top_up = viewing_details["favorite_up_users"][0] report["up_summary"] = f"年度挚爱UP主是{top_up['name']},共观看{top_up['view_count']}个视频,时长{top_up['watch_hours']}小时" # 6. 设备使用总结 if viewing_details["devices"]: top_device = viewing_details["devices"][0] report["device_summary"] = f"你最常用的观看设备是{top_device['name']},共使用{top_device['count']}次" return report @router.get("/viewing/", summary="获取观看行为数据分析") async def get_viewing_details( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取观看行为数据分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含观看行为分析的详细数据和总结报告 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取完整响应 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'viewing_details') if cached_response: print(f"从缓存获取 {target_year} 年的观看行为分析数据") return cached_response print(f"开始分析 {target_year} 年的观看行为数据") # 获取详细观看数据 viewing_details = analyze_viewing_details(cursor, table_name) # 生成综合报告 viewing_report = generate_viewing_report(viewing_details) # 构建完整响应 response = { "status": "success", "data": { "details": viewing_details, "report": viewing_report, "year": target_year, "available_years": available_years } } # 无论是否启用缓存,都更新缓存数据 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的观看行为分析数据缓存") pattern_cache.cache_patterns(table_name, 'viewing_details', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @router.get("/watch-counts", summary="获取重复观看分析") async def get_viewing_watch_counts( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取用户重复观看分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含重复观看分析结果的响应 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'watch_counts') if cached_response: print(f"从缓存获取 {target_year} 年的重复观看分析数据") return cached_response print(f"开始分析 {target_year} 年的重复观看数据") # 获取重复观看分析数据 watch_count_data = analyze_video_watch_counts(cursor, table_name) # 生成重复观看洞察 watch_count_insights = generate_watch_count_insights(watch_count_data) # 构建响应 response = { "status": "success", "data": { "watch_counts": watch_count_data, "insights": watch_count_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的重复观看分析数据缓存") pattern_cache.cache_patterns(table_name, 'watch_counts', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/completion-rates", summary="获取视频完成率分析") async def get_viewing_completion_rates( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取用户视频完成率分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含视频完成率分析结果的响应 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'completion_rates') if cached_response: print(f"从缓存获取 {target_year} 年的视频完成率分析数据") return cached_response print(f"开始分析 {target_year} 年的视频完成率数据") # 获取视频完成率分析数据 completion_data = analyze_completion_rates(cursor, table_name) # 生成完成率洞察 completion_insights = generate_completion_insights(completion_data) # 构建响应 response = { "status": "success", "data": { "completion_rates": completion_data, "insights": completion_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的视频完成率分析数据缓存") pattern_cache.cache_patterns(table_name, 'completion_rates', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() def analyze_author_completion_rates(cursor, table_name: str) -> dict: """专门分析UP主完成率数据,使用智能综合评分算法""" # 获取表结构 cursor.execute(f"PRAGMA table_info({table_name})") columns = {col[1]: idx for idx, col in enumerate(cursor.fetchall())} # 确保必要的列存在 required_columns = ['duration', 'progress', 'author_name', 'author_mid'] for col in required_columns: if col not in columns: raise ValueError(f"Required column '{col}' not found in table {table_name}") # 获取所有历史记录 cursor.execute(f"SELECT * FROM {table_name}") histories = cursor.fetchall() author_stats = {} for history in histories: # 获取并转换数据类型 try: duration = float(history[columns['duration']]) if history[columns['duration']] else 0 progress = float(history[columns['progress']]) if history[columns['progress']] else 0 author_name = history[columns['author_name']] author_mid = history[columns['author_mid']] except (ValueError, TypeError): continue # 计算完成率 if progress == -1: completion_rate = 100 else: completion_rate = (progress / duration * 100) if duration > 0 else 0 # UP主统计 if author_name and author_mid: if author_name not in author_stats: author_stats[author_name] = { "author_mid": author_mid, "video_count": 0, "total_completion": 0, "fully_watched": 0 } stats = author_stats[author_name] stats["video_count"] += 1 stats["total_completion"] += completion_rate if completion_rate >= 90: stats["fully_watched"] += 1 # 计算UP主平均完成率和完整观看率,并按观看数量筛选 filtered_authors = {} for name, stats in author_stats.items(): if stats["video_count"] >= 5: # 只保留观看数量>=5的UP主 stats["average_completion_rate"] = round(stats["total_completion"] / stats["video_count"], 2) stats["fully_watched_rate"] = round(stats["fully_watched"] / stats["video_count"] * 100, 2) filtered_authors[name] = stats # 使用新的智能评分算法 scored_authors = calculate_comprehensive_author_scores(filtered_authors) return { "most_watched_authors": scored_authors["most_watched_authors"], "highest_completion_authors": scored_authors["highest_completion_authors"], "most_valuable_authors": scored_authors["most_valuable_authors"], "potential_authors": scored_authors["potential_authors"] } def calculate_comprehensive_author_scores(authors_data: dict) -> dict: """计算UP主综合评分并分类""" import math if not authors_data: return { "most_watched_authors": {}, "highest_completion_authors": {}, "most_valuable_authors": {}, "potential_authors": {} } # 计算观看数量的最大值和最小值,用于标准化 view_counts = [stats["video_count"] for stats in authors_data.values()] max_views = max(view_counts) min_views = min(view_counts) view_range = max_views - min_views if max_views > min_views else 1 # 为每个UP主计算综合评分 scored_authors = {} for name, stats in authors_data.items(): # 1. 观看数量标准化 (0-100) normalized_views = (stats["video_count"] - min_views) / view_range * 100 # 2. 置信度计算 (避免小样本偏差) confidence = min(1.0, stats["video_count"] / 20) # 3. 综合评分计算 # 权重: 观看数量25%, 完成率50%, 完整观看率25% comprehensive_score = ( normalized_views * 0.25 + stats["average_completion_rate"] * 0.5 + stats["fully_watched_rate"] * 0.25 ) * confidence # 4. 计算特殊指标 # 忠诚度指标:观看数量 * 完成率的平方根 loyalty_score = stats["video_count"] * math.sqrt(stats["average_completion_rate"] / 100) # 质量指标:完成率和完整观看率的加权平均 quality_score = stats["average_completion_rate"] * 0.7 + stats["fully_watched_rate"] * 0.3 scored_authors[name] = { **stats, "comprehensive_score": round(comprehensive_score, 2), "loyalty_score": round(loyalty_score, 2), "quality_score": round(quality_score, 2), "confidence": round(confidence, 2), "normalized_views": round(normalized_views, 2) } # 按不同维度排序分类 # 1. 观看次数最多的UP主 (传统排序) most_watched_authors = dict(sorted( scored_authors.items(), key=lambda x: x[1]["video_count"], reverse=True )[:10]) # 2. 完成率最高的UP主 (传统排序) highest_completion_authors = dict(sorted( scored_authors.items(), key=lambda x: x[1]["average_completion_rate"], reverse=True )[:10]) # 3. 最有价值UP主 (综合评分最高) most_valuable_authors = dict(sorted( scored_authors.items(), key=lambda x: x[1]["comprehensive_score"], reverse=True )[:10]) # 4. 潜力UP主 (高质量但观看数量不是最多的) potential_authors = {} for name, stats in scored_authors.items(): # 筛选条件:质量评分>85,但观看数量不在前3 if (stats["quality_score"] > 85 and stats["video_count"] < sorted(view_counts, reverse=True)[min(2, len(view_counts)-1)]): potential_authors[name] = stats # 潜力UP主按质量评分排序,取前5 potential_authors = dict(sorted( potential_authors.items(), key=lambda x: x[1]["quality_score"], reverse=True )[:5]) return { "most_watched_authors": most_watched_authors, "highest_completion_authors": highest_completion_authors, "most_valuable_authors": most_valuable_authors, "potential_authors": potential_authors } def generate_author_completion_insights(author_data: dict) -> dict: """生成UP主完成率相关的智能洞察""" insights = {} try: # 1. 最有价值UP主洞察(综合评分最高) most_valuable = author_data.get("most_valuable_authors", {}) if most_valuable: top_valuable = next(iter(most_valuable.items()), None) if top_valuable: name, stats = top_valuable insights["most_valuable_author"] = ( f"综合来看,{name}是你最有价值的UP主,观看了{stats.get('video_count', 0)}个视频," f"平均完成率高达{stats.get('average_completion_rate', 0)}%," f"完整观看率{stats.get('fully_watched_rate', 0)}%,综合评分{stats.get('comprehensive_score', 0)}分。" ) # 2. 观看最多UP主洞察(如果与最有价值UP主不同) most_watched = author_data.get("most_watched_authors", {}) if most_watched: top_watched = next(iter(most_watched.items()), None) if top_watched and (not most_valuable or top_watched[0] != next(iter(most_valuable.keys()))): name, stats = top_watched insights["most_watched_author"] = ( f"你观看最多的UP主是{name},观看了{stats.get('video_count', 0)}个视频," f"平均完成率为{stats.get('average_completion_rate', 0)}%,是你的喜爱观看对象。" ) # 3. 生成综合观看行为分析 if most_valuable: total_authors = len(author_data.get("most_watched_authors", {})) insights["viewing_behavior_summary"] = ( f"在你经常观看的{total_authors}位UP主中,你展现出了很好的内容鉴赏能力," f"特别偏爱高质量内容,对喜欢的UP主有很高的完成度和喜爱度。" ) except Exception as e: print(f"Error generating author completion insights: {str(e)}") insights["basic_author"] = "暂时无法生成详细的UP主完成率分析。" return insights @router.get("/author-completion", summary="获取UP主完成率分析") async def get_viewing_author_completion( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取UP主完成率分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含UP主完成率分析结果的响应 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'author_completion') if cached_response: print(f"从缓存获取 {target_year} 年的UP主完成率分析数据") return cached_response print(f"开始分析 {target_year} 年的UP主完成率数据") # 获取UP主完成率分析数据 author_data = analyze_author_completion_rates(cursor, table_name) # 生成UP主完成率洞察 author_insights = generate_author_completion_insights(author_data) # 构建响应 response = { "status": "success", "data": { "completion_rates": author_data, "insights": author_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的UP主完成率分析数据缓存") pattern_cache.cache_patterns(table_name, 'author_completion', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() def analyze_tag_analysis(cursor, table_name: str) -> dict: """专门分析标签数据,包括分布和完成率""" # 获取表结构 cursor.execute(f"PRAGMA table_info({table_name})") columns = {col[1]: idx for idx, col in enumerate(cursor.fetchall())} # 确保必要的列存在 required_columns = ['duration', 'progress', 'tag_name'] for col in required_columns: if col not in columns: raise ValueError(f"Required column '{col}' not found in table {table_name}") # 获取所有历史记录 cursor.execute(f"SELECT * FROM {table_name}") histories = cursor.fetchall() tag_stats = {} tag_distribution = {} for history in histories: # 获取并转换数据类型 try: duration = float(history[columns['duration']]) if history[columns['duration']] else 0 progress = float(history[columns['progress']]) if history[columns['progress']] else 0 tag_name = history[columns['tag_name']] except (ValueError, TypeError): continue # 计算完成率 if progress == -1: completion_rate = 100 else: completion_rate = (progress / duration * 100) if duration > 0 else 0 # 标签分布统计 if tag_name: tag_distribution[tag_name] = tag_distribution.get(tag_name, 0) + 1 # 标签完成率统计 if tag_name not in tag_stats: tag_stats[tag_name] = { "video_count": 0, "total_completion": 0, "fully_watched": 0 } stats = tag_stats[tag_name] stats["video_count"] += 1 stats["total_completion"] += completion_rate if completion_rate >= 90: stats["fully_watched"] += 1 # 计算标签平均完成率和完整观看率,并按观看数量筛选 filtered_tags = {} for tag, stats in tag_stats.items(): if stats["video_count"] >= 5: # 只保留视频数量>=5的标签 stats["average_completion_rate"] = round(stats["total_completion"] / stats["video_count"], 2) stats["fully_watched_rate"] = round(stats["fully_watched"] / stats["video_count"] * 100, 2) filtered_tags[tag] = stats # 获取完成率最高的标签 top_completion_tags = dict(sorted( filtered_tags.items(), key=lambda x: x[1]["average_completion_rate"], reverse=True )[:10]) # 获取观看最多的标签 top_watched_tags = dict(sorted( tag_distribution.items(), key=lambda x: x[1], reverse=True )[:10]) return { "tag_distribution": top_watched_tags, "tag_completion_rates": top_completion_tags } def generate_tag_analysis_insights(tag_data: dict) -> dict: """生成标签分析相关的洞察""" insights = {} try: # 标签偏好洞察 tag_distribution = tag_data.get("tag_distribution", {}) if tag_distribution: top_tag = next(iter(tag_distribution.items()), None) if top_tag: insights["tag_preference"] = ( f"你最喜欢观看{top_tag[0]}分区的视频,共观看了{top_tag[1]}个视频。" ) # 标签完成率洞察 tag_completion = tag_data.get("tag_completion_rates", {}) if tag_completion: top_completion = next(iter(tag_completion.items()), None) if top_completion: insights["tag_completion"] = ( f"在经常观看的分区中,你对{top_completion[0]}分区的视频最感兴趣," f"平均完成率达到{top_completion[1].get('average_completion_rate', 0)}%," f"观看过{top_completion[1].get('video_count', 0)}个该分区的视频。" ) except Exception as e: print(f"Error generating tag analysis insights: {str(e)}") insights["basic_tag"] = "暂时无法生成详细的标签分析。" return insights @router.get("/tag-analysis", summary="获取标签分析") async def get_viewing_tag_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取标签分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含标签分析结果的响应 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'tag_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的标签分析数据") return cached_response print(f"开始分析 {target_year} 年的标签数据") # 获取标签分析数据 tag_data = analyze_tag_analysis(cursor, table_name) # 生成标签分析洞察 tag_insights = generate_tag_analysis_insights(tag_data) # 构建响应 response = { "status": "success", "data": { "watch_counts": {"tag_distribution": tag_data["tag_distribution"]}, "completion_rates": {"tag_completion_rates": tag_data["tag_completion_rates"]}, "insights": tag_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的标签分析数据缓存") pattern_cache.cache_patterns(table_name, 'tag_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() def analyze_duration_analysis(cursor, table_name: str) -> dict: """专门分析视频时长数据""" # 获取表结构 cursor.execute(f"PRAGMA table_info({table_name})") columns = {col[1]: idx for idx, col in enumerate(cursor.fetchall())} # 确保必要的列存在 required_columns = ['duration', 'view_at'] for col in required_columns: if col not in columns: raise ValueError(f"Required column '{col}' not found in table {table_name}") # 获取所有历史记录 cursor.execute(f"SELECT * FROM {table_name}") histories = cursor.fetchall() print(f"Debug: 总共获取到 {len(histories)} 条历史记录") if len(histories) > 0: print(f"Debug: 第一条记录示例: {histories[0]}") print(f"Debug: 列映射: {columns}") # 时段分类 time_periods = { '凌晨': {'start': 0, 'end': 6}, '上午': {'start': 6, 'end': 12}, '下午': {'start': 12, 'end': 18}, '晚上': {'start': 18, 'end': 24} } # 初始化时长相关性数据 duration_correlation = {} for period in time_periods.keys(): duration_correlation[period] = { '短视频': {'video_count': 0, 'total_duration': 0, 'avg_duration': 0}, '中等视频': {'video_count': 0, 'total_duration': 0, 'avg_duration': 0}, '长视频': {'video_count': 0, 'total_duration': 0, 'avg_duration': 0} } processed_count = 0 valid_count = 0 for history in histories: processed_count += 1 try: duration = float(history[columns['duration']]) if history[columns['duration']] else 0 view_at = history[columns['view_at']] if not view_at or duration <= 0: if processed_count <= 5: # 只打印前5条的调试信息 print(f"Debug: 跳过记录 {processed_count}: view_at={view_at}, duration={duration}") continue # 解析观看时间 - view_at 是 Unix 时间戳 from datetime import datetime try: # view_at 是 Unix 时间戳,需要转换为 datetime 对象 view_time = datetime.fromtimestamp(int(view_at)) hour = view_time.hour except (ValueError, TypeError, OSError): continue # 确定时段 period = None for p, time_range in time_periods.items(): if time_range['start'] <= hour < time_range['end']: period = p break if not period: continue # 确定时长类型 if duration < 300: # 5分钟以下 duration_type = '短视频' elif duration < 1200: # 20分钟以下 duration_type = '中等视频' else: duration_type = '长视频' # 更新统计 stats = duration_correlation[period][duration_type] stats['video_count'] += 1 stats['total_duration'] += duration valid_count += 1 if valid_count <= 5: # 只打印前5条有效记录的调试信息 print(f"Debug: 有效记录 {valid_count}: period={period}, duration_type={duration_type}, duration={duration}") except (ValueError, TypeError): if processed_count <= 5: print(f"Debug: 数据转换失败,记录 {processed_count}") continue # 计算平均时长 for period in duration_correlation: for duration_type in duration_correlation[period]: stats = duration_correlation[period][duration_type] if stats['video_count'] > 0: stats['avg_duration'] = stats['total_duration'] / stats['video_count'] print(f"Debug: 处理完成 - 总记录数: {processed_count}, 有效记录数: {valid_count}") print(f"Debug: 最终统计结果: {duration_correlation}") return duration_correlation def generate_duration_analysis_insights(duration_data: dict) -> dict: """生成视频时长分析相关的洞察""" insights = {} try: # 计算总体时长偏好 total_counts = {'短视频': 0, '中等视频': 0, '长视频': 0} for period in duration_data: for duration_type in duration_data[period]: total_counts[duration_type] += duration_data[period][duration_type]['video_count'] if sum(total_counts.values()) > 0: # 找出最喜欢的时长类型 preferred_type = max(total_counts.items(), key=lambda x: x[1]) total_videos = sum(total_counts.values()) preference_rate = round(preferred_type[1] / total_videos * 100, 1) # 找出最活跃的时段和对应的时长偏好 max_period_count = 0 max_period = None max_period_type = None for period in duration_data: for duration_type in duration_data[period]: count = duration_data[period][duration_type]['video_count'] if count > max_period_count: max_period_count = count max_period = period max_period_type = duration_type insights["duration_preference"] = ( f"你最喜欢观看{preferred_type[0]},占总观看量的{preference_rate}%。" f"特别是在{max_period}时段,你更偏向于观看{max_period_type}。" ) except Exception as e: print(f"Error generating duration analysis insights: {str(e)}") insights["basic_duration"] = "暂时无法生成详细的时长分析。" return insights @router.get("/duration-analysis", summary="获取视频时长分析") async def get_viewing_duration_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取视频时长分析 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含视频时长分析结果的响应 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'duration_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的视频时长分析数据") return cached_response print(f"开始分析 {target_year} 年的视频时长数据") # 获取视频时长分析数据 duration_data = analyze_duration_analysis(cursor, table_name) # 生成时长分析洞察 duration_insights = generate_duration_analysis_insights(duration_data) # 构建响应 response = { "status": "success", "data": { "duration_correlation": duration_data, "insights": duration_insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的视频时长分析数据缓存") pattern_cache.cache_patterns(table_name, 'duration_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close()
281677160/openwrt-package
11,114
luci-app-homeproxy/root/etc/init.d/homeproxy
#!/bin/sh /etc/rc.common # SPDX-License-Identifier: GPL-2.0-only # # Copyright (C) 2022-2023 ImmortalWrt.org USE_PROCD=1 START=99 STOP=10 CONF="homeproxy" PROG="/usr/bin/sing-box" HP_DIR="/etc/homeproxy" RUN_DIR="/var/run/homeproxy" LOG_PATH="$RUN_DIR/homeproxy.log" # we don't know which is the default server, just take the first one DNSMASQ_UCI_CONFIG="$(uci -q show "dhcp.@dnsmasq[0]" | awk 'NR==1 {split($0, conf, /[.=]/); print conf[2]}')" if [ -f "/tmp/etc/dnsmasq.conf.$DNSMASQ_UCI_CONFIG" ]; then DNSMASQ_DIR="$(awk -F '=' '/^conf-dir=/ {print $2}' "/tmp/etc/dnsmasq.conf.$DNSMASQ_UCI_CONFIG")/dnsmasq-homeproxy.d" else DNSMASQ_DIR="/tmp/dnsmasq.d/dnsmasq-homeproxy.d" fi log() { echo -e "$(date "+%Y-%m-%d %H:%M:%S") [DAEMON] $*" >> "$LOG_PATH" } start_service() { config_load "$CONF" local routing_mode proxy_mode config_get routing_mode "config" "routing_mode" "bypass_mainland_china" config_get proxy_mode "config" "proxy_mode" "redirect_tproxy" local outbound_node if [ "$routing_mode" != "custom" ]; then config_get outbound_node "config" "main_node" "nil" else config_get outbound_node "routing" "default_outbound" "nil" fi local server_enabled config_get_bool server_enabled "server" "enabled" "0" if [ "$outbound_node" = "nil" ] && [ "$server_enabled" = "0" ]; then return 1 fi mkdir -p "$RUN_DIR" if [ "$outbound_node" != "nil" ]; then # Generate/Validate client config ucode -S "$HP_DIR/scripts/generate_client.uc" 2>>"$LOG_PATH" if [ ! -e "$RUN_DIR/sing-box-c.json" ]; then log "Error: failed to generate client configuration." return 1 elif ! "$PROG" check --config "$RUN_DIR/sing-box-c.json" 2>>"$LOG_PATH"; then log "Error: wrong client configuration detected." return 1 fi # Auto update local auto_update auto_update_time config_get_bool auto_update "subscription" "auto_update" "0" if [ "$auto_update" = "1" ]; then config_get auto_update_time "subscription" "auto_update_time" "2" sed -i "/#${CONF}_autosetup/d" "/etc/crontabs/root" 2>"/dev/null" echo -e "0 $auto_update_time * * * $HP_DIR/scripts/update_crond.sh #${CONF}_autosetup" >> "/etc/crontabs/root" /etc/init.d/cron restart fi # DNSMasq rules local ipv6_support dns_port config_get_bool ipv6_support "config" "ipv6_support" "0" config_get dns_port "infra" "dns_port" "5333" mkdir -p "$DNSMASQ_DIR" echo -e "conf-dir=$DNSMASQ_DIR" > "$DNSMASQ_DIR/../dnsmasq-homeproxy.conf" case "$routing_mode" in "bypass_mainland_china"|"custom"|"global") cat <<-EOF >> "$DNSMASQ_DIR/redirect-dns.conf" no-poll no-resolv server=127.0.0.1#$dns_port EOF ;; "gfwlist") local gfw_nftset_v6 [ "$ipv6_support" -eq "0" ] || gfw_nftset_v6=",6#inet#fw4#homeproxy_gfw_list_v6" sed -r -e "s/(.*)/server=\/\1\/127.0.0.1#$dns_port\nnftset=\/\1\\/4#inet#fw4#homeproxy_gfw_list_v4$gfw_nftset_v6/g" \ "$HP_DIR/resources/gfw_list.txt" > "$DNSMASQ_DIR/gfw_list.conf" ;; "proxy_mainland_china") sed -r -e "s/(.*)/server=\/\1\/127.0.0.1#$dns_port/g" \ "$HP_DIR/resources/china_list.txt" > "$DNSMASQ_DIR/china_list.conf" ;; esac if [ "$routing_mode" != "custom" ] && [ -s "$HP_DIR/resources/proxy_list.txt" ]; then local wan_nftset_v6 [ "$ipv6_support" -eq "0" ] || wan_nftset_v6=",6#inet#fw4#homeproxy_wan_proxy_addr_v6" sed -r -e '/^\s*$/d' -e "s/(.*)/server=\/\1\/127.0.0.1#$dns_port\nnftset=\/\1\\/4#inet#fw4#homeproxy_wan_proxy_addr_v4$wan_nftset_v6/g" \ "$HP_DIR/resources/proxy_list.txt" > "$DNSMASQ_DIR/proxy_list.conf" fi /etc/init.d/dnsmasq restart >"/dev/null" 2>&1 # Setup routing table local table_mark config_get table_mark "infra" "table_mark" "100" case "$proxy_mode" in "redirect_tproxy") local outbound_udp_node config_get outbound_udp_node "config" "main_udp_node" "nil" if [ "$outbound_udp_node" != "nil" ] || [ "$routing_mode" = "custom" ]; then local tproxy_mark config_get tproxy_mark "infra" "tproxy_mark" "101" ip rule add fwmark "$tproxy_mark" table "$table_mark" ip route add local 0.0.0.0/0 dev lo table "$table_mark" if [ "$ipv6_support" -eq "1" ]; then ip -6 rule add fwmark "$tproxy_mark" table "$table_mark" ip -6 route add local ::/0 dev lo table "$table_mark" fi fi ;; "redirect_tun"|"tun") local tun_name tun_mark config_get tun_name "infra" "tun_name" "singtun0" config_get tun_mark "infra" "tun_mark" "102" ip tuntap add mode tun user root name "$tun_name" sleep 1s ip link set "$tun_name" up ip route replace default dev "$tun_name" table "$table_mark" ip rule add fwmark "$tun_mark" lookup "$table_mark" ip -6 route replace default dev "$tun_name" table "$table_mark" ip -6 rule add fwmark "$tun_mark" lookup "$table_mark" ;; esac # sing-box (client) procd_open_instance "sing-box-c" procd_set_param command "$PROG" procd_append_param command run --config "$RUN_DIR/sing-box-c.json" # QUIC-GO GSO is broken on kernel 6.6 currently uname -r | grep -Eq "^6\.6" && procd_set_param env "QUIC_GO_DISABLE_GSO"="true" if [ -x "/sbin/ujail" ] && [ "$routing_mode" != "custom" ] && ! grep -Eq '"type": "(wireguard|tun)"' "$RUN_DIR/sing-box-c.json"; then procd_add_jail "sing-box-c" log procfs procd_add_jail_mount "$RUN_DIR/sing-box-c.json" procd_add_jail_mount_rw "$RUN_DIR/sing-box-c.log" [ "$routing_mode" != "bypass_mainland_china" ] || procd_add_jail_mount_rw "$RUN_DIR/cache.db" procd_add_jail_mount "$HP_DIR/certs/" procd_add_jail_mount "/etc/ssl/" procd_add_jail_mount "/etc/localtime" procd_add_jail_mount "/etc/TZ" procd_set_param capabilities "/etc/capabilities/homeproxy.json" procd_set_param no_new_privs 1 procd_set_param user sing-box procd_set_param group sing-box fi procd_set_param limits core="unlimited" procd_set_param limits nofile="1000000 1000000" procd_set_param stderr 1 procd_set_param respawn procd_close_instance fi if [ "$server_enabled" = "1" ]; then # Generate/Validate server config ucode -S "$HP_DIR/scripts/generate_server.uc" 2>>"$LOG_PATH" if [ ! -e "$RUN_DIR/sing-box-s.json" ]; then log "Error: failed to generate server configuration." return 1 elif ! "$PROG" check --config "$RUN_DIR/sing-box-s.json" 2>>"$LOG_PATH"; then log "Error: wrong server configuration detected." return 1 fi # sing-box (server) procd_open_instance "sing-box-s" procd_set_param command "$PROG" procd_append_param command run --config "$RUN_DIR/sing-box-s.json" # QUIC-GO GSO is broken on kernel 6.6 currently uname -r | grep -Eq "^6\.6" && procd_set_param env "QUIC_GO_DISABLE_GSO"="true" if [ -x "/sbin/ujail" ]; then procd_add_jail "sing-box-s" log procfs procd_add_jail_mount "$RUN_DIR/sing-box-s.json" procd_add_jail_mount_rw "$RUN_DIR/sing-box-s.log" procd_add_jail_mount_rw "$HP_DIR/certs/" procd_add_jail_mount "/etc/acme/" procd_add_jail_mount "/etc/ssl/" procd_add_jail_mount "/etc/localtime" procd_add_jail_mount "/etc/TZ" procd_set_param capabilities "/etc/capabilities/homeproxy.json" procd_set_param no_new_privs 1 procd_set_param user sing-box procd_set_param group sing-box fi procd_set_param limits core="unlimited" procd_set_param limits nofile="1000000 1000000" procd_set_param stderr 1 procd_set_param respawn procd_close_instance fi # log-cleaner procd_open_instance "log-cleaner" procd_set_param command "$HP_DIR/scripts/clean_log.sh" procd_set_param respawn procd_close_instance case "$routing_mode" in "bypass_mainland_china") # Prepare cache db [ -e "$RUN_DIR/cache.db" ] || touch "$RUN_DIR/cache.db" ;; "custom") # Prepare ruleset directory [ -d "$HP_DIR/ruleset" ] || mkdir -p "$HP_DIR/ruleset" ;; esac [ "$outbound_node" = "nil" ] || echo > "$RUN_DIR/sing-box-c.log" if [ "$server_enabled" = "1" ]; then echo > "$RUN_DIR/sing-box-s.log" mkdir -p "$HP_DIR/certs" fi # Update permissions for ujail chown -R sing-box:sing-box "$RUN_DIR" # Setup firewall ucode "$HP_DIR/scripts/firewall_pre.uc" [ "$outbound_node" = "nil" ] || utpl -S "$HP_DIR/scripts/firewall_post.ut" > "$RUN_DIR/fw4_post.nft" fw4 reload >"/dev/null" 2>&1 log "sing-box $(sing-box version -n) started." } stop_service() { sed -i "/#${CONF}_autosetup/d" "/etc/crontabs/root" 2>"/dev/null" /etc/init.d/cron restart >"/dev/null" 2>&1 # Setup firewall # Load config config_load "$CONF" local table_mark tproxy_mark tun_mark tun_name config_get table_mark "infra" "table_mark" "100" config_get tproxy_mark "infra" "tproxy_mark" "101" config_get tun_mark "infra" "tun_mark" "102" config_get tun_name "infra" "tun_name" "singtun0" # Tproxy ip rule del fwmark "$tproxy_mark" table "$table_mark" 2>"/dev/null" ip route del local 0.0.0.0/0 dev lo table "$table_mark" 2>"/dev/null" ip -6 rule del fwmark "$tproxy_mark" table "$table_mark" 2>"/dev/null" ip -6 route del local ::/0 dev lo table "$table_mark" 2>"/dev/null" # TUN ip route del default dev "$tun_name" table "$table_mark" 2>"/dev/null" ip rule del fwmark "$tun_mark" table "$table_mark" 2>"/dev/null" ip -6 route del default dev "$tun_name" table "$table_mark" 2>"/dev/null" ip -6 rule del fwmark "$tun_mark" table "$table_mark" 2>"/dev/null" # Nftables rules for i in "homeproxy_dstnat_redir" "homeproxy_output_redir" \ "homeproxy_redirect" "homeproxy_redirect_proxy" \ "homeproxy_redirect_proxy_port" "homeproxy_redirect_lanac" \ "homeproxy_mangle_prerouting" "homeproxy_mangle_output" \ "homeproxy_mangle_tproxy" "homeproxy_mangle_tproxy_port" \ "homeproxy_mangle_tproxy_lanac" "homeproxy_mangle_mark" \ "homeproxy_mangle_tun" "homeproxy_mangle_tun_mark"; do nft flush chain inet fw4 "$i" nft delete chain inet fw4 "$i" done 2>"/dev/null" for i in "homeproxy_local_addr_v4" "homeproxy_local_addr_v6" \ "homeproxy_gfw_list_v4" "homeproxy_gfw_list_v6" \ "homeproxy_mainland_addr_v4" "homeproxy_mainland_addr_v6" \ "homeproxy_wan_proxy_addr_v4" "homeproxy_wan_proxy_addr_v6" \ "homeproxy_wan_direct_addr_v4" "homeproxy_wan_direct_addr_v6" \ "homeproxy_routing_port"; do nft flush set inet fw4 "$i" nft delete set inet fw4 "$i" done 2>"/dev/null" echo 2>"/dev/null" > "$RUN_DIR/fw4_forward.nft" echo 2>"/dev/null" > "$RUN_DIR/fw4_input.nft" echo 2>"/dev/null" > "$RUN_DIR/fw4_post.nft" fw4 reload >"/dev/null" 2>&1 # Remove DNS hijack rm -rf "$DNSMASQ_DIR/../dnsmasq-homeproxy.conf" "$DNSMASQ_DIR" /etc/init.d/dnsmasq restart >"/dev/null" 2>&1 rm -f "$RUN_DIR/sing-box-c.json" "$RUN_DIR/sing-box-c.log" \ "$RUN_DIR/sing-box-s.json" "$RUN_DIR/sing-box-s.log" log "Service stopped." } service_stopped() { # Load config config_load "$CONF" local tun_name config_get tun_name "infra" "tun_name" "singtun0" # TUN ip link set "$tun_name" down 2>"/dev/null" ip tuntap del mode tun name "$tun_name" 2>"/dev/null" } reload_service() { log "Reloading service..." stop start } service_triggers() { procd_add_reload_trigger "$CONF" procd_add_interface_trigger "interface.*.up" wan /etc/init.d/$CONF reload }
2977094657/BilibiliHistoryFetcher
35,576
routers/video_summary.py
import json import os import sqlite3 import time from typing import Optional, List, Dict, Any, Union import requests import yaml from fastapi import APIRouter, HTTPException, Body, BackgroundTasks from pydantic import BaseModel, Field from scripts.utils import get_output_path, load_config from scripts.wbi_sign import get_wbi_sign # 导入DeepSeek API相关模块 from routers.deepseek import chat_completion, ChatMessage, ChatRequest router = APIRouter() config = load_config() # 获取是否缓存空摘要的配置,默认为True CACHE_EMPTY_SUMMARY = config.get('CACHE_EMPTY_SUMMARY', True) # 定义配置模型 class SummaryConfig(BaseModel): cache_empty_summary: bool = True class VideoSummaryPrompt(BaseModel): default_prompt: str = Field(..., description="默认提示词,用于重置") custom_prompt: str = Field(..., description="用户自定义提示词") # 数据模型定义 class OutlinePoint(BaseModel): timestamp: int content: str class OutlinePart(BaseModel): title: str part_outline: List[OutlinePoint] timestamp: int class VideoSummaryResponse(BaseModel): bvid: str cid: int up_mid: int stid: Optional[str] = None summary: Optional[str] = None outline: Optional[List[OutlinePart]] = None result_type: int = 0 status_message: str = "" # 用于解释result_type的含义 has_summary: bool = False # 表示是否存在摘要内容 fetch_time: int update_time: Optional[int] = None from_cache: bool = False class SummaryRequest(BaseModel): bvid: str cid: int up_mid: int def get_db(): """获取数据库连接""" db_path = get_output_path(config['db_file']) # 检查数据库文件是否存在 db_exists = os.path.exists(db_path) try: # 连接数据库 conn = sqlite3.connect(db_path) cursor = conn.cursor() # 设置数据库兼容性参数 pragmas = [ ('legacy_file_format', 1), ('journal_mode', 'DELETE'), ('synchronous', 'NORMAL'), ('user_version', 317), # 使用固定的用户版本号 ('encoding', 'UTF8') # 设置数据库编码为UTF8 (不使用连字符) ] for pragma, value in pragmas: cursor.execute(f'PRAGMA {pragma}={value}') conn.commit() # 确保视频摘要表存在 from config.sql_statements_sqlite import CREATE_TABLE_VIDEO_SUMMARY, CREATE_INDEXES_VIDEO_SUMMARY cursor.execute(CREATE_TABLE_VIDEO_SUMMARY) # 创建索引 for index_sql in CREATE_INDEXES_VIDEO_SUMMARY: cursor.execute(index_sql) conn.commit() return conn except sqlite3.Error as e: print(f"数据库连接错误: {str(e)}") if 'conn' in locals() and conn: conn.close() raise HTTPException( status_code=500, detail=f"数据库连接失败: {str(e)}" ) def get_video_summary_from_db(bvid: str, cid: int) -> Optional[Dict[str, Any]]: """从数据库获取视频摘要""" conn = get_db() try: cursor = conn.cursor() cursor.execute(""" SELECT bvid, cid, up_mid, stid, summary, outline, result_type, fetch_time, update_time FROM video_summary WHERE bvid = ? AND cid = ? """, (bvid, cid)) result = cursor.fetchone() if result: result_type = result[6] status_message = get_status_message(result_type) # 判断是否有有效摘要 (result_type为1或2表示有摘要) has_summary = result_type > 0 return { "bvid": result[0], "cid": result[1], "up_mid": result[2], "stid": result[3], "summary": result[4], "outline": json.loads(result[5]) if result[5] else None, "result_type": result_type, "status_message": status_message, "has_summary": has_summary, "fetch_time": result[7], "update_time": result[8], "from_cache": True } return None except sqlite3.Error as e: print(f"查询数据库时发生错误: {e}") return None finally: if conn: conn.close() # 添加一个辅助函数获取状态消息 def get_status_message(result_type: int) -> str: """ 根据result_type获取对应的状态消息 官方状态码含义: - 0: 没有摘要 - 1: 仅存在摘要总结 - 2: 存在摘要以及提纲 """ if result_type == 0: return "该视频没有摘要" elif result_type == 1: return "该视频仅有摘要总结" elif result_type == 2: return "该视频有摘要总结和提纲" elif result_type == -1: return "该视频不支持AI摘要(可能含有敏感内容或其他因素导致)" else: return f"未知状态码: {result_type}" def save_video_summary_to_db( bvid: str, cid: int, up_mid: int, stid: str, summary: str, outline: Union[List[Dict], None], result_type: int ) -> bool: """保存视频摘要到数据库""" conn = get_db() try: cursor = conn.cursor() current_time = int(time.time()) # 检查是否已存在 cursor.execute( "SELECT id FROM video_summary WHERE bvid = ? AND cid = ?", (bvid, cid) ) existing = cursor.fetchone() if existing: # 更新现有记录 from config.sql_statements_sqlite import UPDATE_VIDEO_SUMMARY cursor.execute( UPDATE_VIDEO_SUMMARY, ( stid, summary, json.dumps(outline, ensure_ascii=False) if outline else None, result_type, current_time, bvid, cid ) ) else: # 插入新记录 from config.sql_statements_sqlite import INSERT_VIDEO_SUMMARY # 生成ID (使用时间戳+随机数) id = int(f"{current_time}{hash(bvid + str(cid)) % 10000:04d}") cursor.execute( INSERT_VIDEO_SUMMARY, ( id, bvid, cid, up_mid, stid, summary, json.dumps(outline, ensure_ascii=False) if outline else None, result_type, current_time, current_time ) ) conn.commit() return True except sqlite3.Error as e: print(f"保存到数据库时发生错误: {e}") conn.rollback() return False finally: if conn: conn.close() async def fetch_video_summary_from_api(bvid: str, cid: int, up_mid: int) -> Dict[str, Any]: """从B站API获取视频摘要""" try: # 获取wbi签名 wbi_params = { 'bvid': bvid, 'cid': cid, 'up_mid': up_mid } signed_params = get_wbi_sign(wbi_params) # 构建请求URL url = "https://api.bilibili.com/x/web-interface/view/conclusion/get" # 从配置中读取SESSDATA sessdata = config.get('SESSDATA', '') # 添加必要的HTTP头信息 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "Referer": "https://www.bilibili.com/" } # 如果有SESSDATA,添加到Cookie if sessdata: headers["Cookie"] = f"SESSDATA={sessdata}" # 发送请求 response = requests.get(url, params=signed_params, headers=headers) data = response.json() # 记录原始返回数据用于调试 print(f"API返回数据: {json.dumps(data, ensure_ascii=False)}") # 根据返回的code进行处理 if data['code'] == 0: # API请求成功 return data['data'] elif data['code'] == -1: # 不支持AI摘要或请求异常 return { 'model_result': { 'result_type': -1, # 使用-1表示不支持AI摘要 'summary': '该视频不支持AI摘要(可能含有敏感内容或其他因素导致)', 'outline': None }, 'stid': '' } else: # 其他错误情况 raise HTTPException( status_code=400, detail=f"获取视频摘要失败: {data['message']} (code: {data['code']})" ) except Exception as e: # 记录详细错误信息 print(f"获取视频摘要时发生错误: {str(e)}") raise HTTPException( status_code=500, detail=f"获取视频摘要时发生错误: {str(e)}" ) @router.get("/get_summary", summary="获取视频摘要", response_model=VideoSummaryResponse) async def get_video_summary(bvid: str, cid: int, up_mid: int, force_refresh: Optional[bool] = False): """ 获取视频摘要 - **bvid**: 视频的BVID - **cid**: 视频的CID - **up_mid**: UP主的MID - **force_refresh**: 是否强制刷新(不使用缓存) """ # 处理force_refresh参数,确保是正确的布尔值 if isinstance(force_refresh, str): force_refresh = force_refresh.lower() == 'true' try: # 首先尝试从数据库获取 if not force_refresh: db_result = get_video_summary_from_db(bvid, cid) if db_result: return db_result # 从API获取 api_result = await fetch_video_summary_from_api(bvid, cid, up_mid) # 解析API结果 result_type = api_result.get('model_result', {}).get('result_type', 0) summary = api_result.get('model_result', {}).get('summary', '') outline_data = api_result.get('model_result', {}).get('outline', None) stid = api_result.get('stid', '') # 获取状态消息 status_message = get_status_message(result_type) # 判断是否有有效摘要 (result_type为1或2表示有摘要) has_summary = result_type > 0 # 根据配置决定是否保存到数据库 # 如果CACHE_EMPTY_SUMMARY为True,则保存所有结果 # 如果CACHE_EMPTY_SUMMARY为False,则只保存有摘要的结果 should_save = has_summary or CACHE_EMPTY_SUMMARY if should_save: # 保存到数据库 save_success = save_video_summary_to_db( bvid=bvid, cid=cid, up_mid=up_mid, stid=stid, summary=summary, outline=outline_data, result_type=result_type ) if not save_success: print(f"警告: 保存视频摘要到数据库失败: {bvid}, {cid}") else: print(f"跳过保存无摘要数据到数据库: {bvid}, {cid}, result_type={result_type}") # 保存B站获取的摘要到./output/BSummary/{cid}目录 # 不管是否有摘要内容,都保存,因为判断太耗时间 try: # 创建保存目录 save_dir = os.path.join("output", "BSummary", str(cid)) os.makedirs(save_dir, exist_ok=True) # 构建完整的响应数据 response_data = { "bvid": bvid, "cid": cid, "up_mid": up_mid, "stid": stid, "summary": summary, "outline": outline_data, "result_type": result_type, "status_message": status_message, "has_summary": has_summary, "fetch_time": int(time.time()), "update_time": int(time.time()), "from_cache": False, "api_response": api_result # 保存原始API响应 } # 保存完整响应数据 response_path = os.path.join(save_dir, f"{cid}_response.json") with open(response_path, 'w', encoding='utf-8') as f: json.dump(response_data, f, ensure_ascii=False, indent=2) # 如果有摘要,单独保存摘要内容到文本文件,方便查看 if has_summary: summary_path = os.path.join(save_dir, f"{cid}_summary.txt") with open(summary_path, 'w', encoding='utf-8') as f: f.write(summary) # 如果有提纲,单独保存提纲 if outline_data: outline_path = os.path.join(save_dir, f"{cid}_outline.json") with open(outline_path, 'w', encoding='utf-8') as f: json.dump(outline_data, f, ensure_ascii=False, indent=2) print(f"已保存B站摘要到: {save_dir}") except Exception as e: # 保存到文件失败不影响API返回 print(f"警告: 保存B站摘要到文件失败: {str(e)}") # 返回结果 return { "bvid": bvid, "cid": cid, "up_mid": up_mid, "stid": stid, "summary": summary, "outline": outline_data, "result_type": result_type, "status_message": status_message, "has_summary": has_summary, "fetch_time": int(time.time()), "update_time": int(time.time()), "from_cache": False } except Exception as e: # 捕获所有可能的异常,确保API有良好的错误处理 print(f"获取视频摘要出错: {str(e)}") raise HTTPException( status_code=500, detail=f"获取视频摘要失败: {str(e)}" ) # 配置操作函数 def save_config(new_config: Dict[str, Any]) -> bool: """保存配置到配置文件,只修改指定的配置项,保持文件其余部分不变""" try: # 获取配置文件路径 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config', 'config.yaml') # 读取配置文件内容 with open(config_path, 'r', encoding='utf-8') as f: config_content = f.read() # 只更新指定的字段 for key, value in new_config.items(): # 对于布尔值,需要特殊处理 if isinstance(value, bool): value_str = str(value).lower() else: value_str = str(value) # 使用正则表达式查找并替换配置项 import re pattern = rf'^{key}\s*:.*$' replacement = f'{key}: {value_str}' config_content = re.sub(pattern, replacement, config_content, flags=re.MULTILINE) # 写回配置文件 with open(config_path, 'w', encoding='utf-8') as f: f.write(config_content) # 更新全局变量 global config, CACHE_EMPTY_SUMMARY config.update(new_config) # 只更新指定的字段 CACHE_EMPTY_SUMMARY = config.get('CACHE_EMPTY_SUMMARY', True) return True except Exception as e: print(f"保存配置失败: {str(e)}") return False # 添加配置接口 @router.get("/config", summary="获取摘要相关配置", response_model=SummaryConfig) async def get_summary_config(): """获取摘要相关配置""" return { "cache_empty_summary": CACHE_EMPTY_SUMMARY } @router.post("/config", summary="更新摘要相关配置", response_model=SummaryConfig) async def update_summary_config(config_data: SummaryConfig = Body(...)): """ 更新摘要相关配置 - **cache_empty_summary**: 是否缓存空摘要结果 """ # 准备要更新的配置项,只包含CACHE_EMPTY_SUMMARY字段 config_updates = { "CACHE_EMPTY_SUMMARY": config_data.cache_empty_summary } try: # 读取当前配置 config_path = get_output_path("config/config.yaml") with open(config_path, 'r', encoding='utf-8') as f: current_config = yaml.safe_load(f) # 更新配置 current_config.update(config_updates) # 写回配置文件 with open(config_path, 'w', encoding='utf-8') as f: yaml.dump(current_config, f, default_flow_style=False, allow_unicode=True) # 更新全局配置 global config, CACHE_EMPTY_SUMMARY config = load_config() CACHE_EMPTY_SUMMARY = config.get('CACHE_EMPTY_SUMMARY', True) return { "cache_empty_summary": CACHE_EMPTY_SUMMARY } except Exception as e: raise HTTPException( status_code=500, detail=f"更新配置失败: {str(e)}" ) # 自定义视频摘要请求模型 class CustomSummaryRequest(BaseModel): bvid: str cid: int up_mid: int subtitle_content: str = Field(..., description="视频字幕内容") model: Optional[str] = Field("deepseek-chat", description="DeepSeek模型名称") temperature: Optional[float] = Field(0.7, description="生成温度,控制创造性") max_tokens: Optional[int] = Field(1000, description="最大生成标记数") # 添加 TokenDetails 和 UsageInfo 模型 class TokenDetails(BaseModel): cached_tokens: Optional[int] = None class UsageInfo(BaseModel): prompt_tokens: int completion_tokens: int total_tokens: int prompt_tokens_details: Optional[TokenDetails] = None # 自定义视频摘要响应模型 class CustomSummaryResponse(BaseModel): bvid: str cid: int up_mid: int summary: str success: bool message: str from_deepseek: bool = True tokens_used: Optional[UsageInfo] = None processing_time: Optional[float] = None # 使用DeepSeek API生成自定义视频摘要 async def generate_custom_summary(subtitle_content: str, model: str = "deepseek-chat", temperature: float = 0.7, max_tokens: int = 8000, top_p: float = 1.0, stream: bool = False, json_mode: bool = False, frequency_penalty: float = 0.0, presence_penalty: float = 0.0, background_tasks: BackgroundTasks = None) -> Dict[str, Any]: """生成自定义视频摘要""" try: # 加载配置获取提示词 config = load_config() prompt = config.get('deepseek', {}).get('video_summary', {}).get('custom_prompt', '') if not prompt: raise ValueError("未找到有效的提示词配置") # 构建消息列表 messages = [ {"role": "system", "content": prompt}, {"role": "user", "content": subtitle_content} ] # 调用DeepSeek API start_time = time.time() response = await chat_completion( request=ChatRequest( messages=[ChatMessage(**msg) for msg in messages], model=model, temperature=temperature, max_tokens=max_tokens, top_p=top_p, stream=stream, json_mode=json_mode ), background_tasks=background_tasks ) processing_time = time.time() - start_time # 构造符合 UsageInfo 模型的 tokens_used 数据 usage = response.get("usage", {}) tokens_used = { "prompt_tokens": usage.get("prompt_tokens", 0), "completion_tokens": usage.get("completion_tokens", 0), "total_tokens": usage.get("total_tokens", 0), "prompt_tokens_details": { "cached_tokens": usage.get("prompt_tokens_details", {}).get("cached_tokens", 0) } if usage.get("prompt_tokens_details") else None } return { "success": True, "summary": response["content"], "tokens_used": tokens_used, "processing_time": processing_time } except Exception as e: return { "success": False, "message": f"生成摘要失败: {str(e)}" } @router.post("/custom_summary", summary="使用DeepSeek生成自定义视频摘要", response_model=CustomSummaryResponse) async def create_custom_summary(request: CustomSummaryRequest, background_tasks: BackgroundTasks): """ 使用DeepSeek API生成自定义视频摘要 - **bvid**: 视频的BVID - **cid**: 视频的CID - **up_mid**: UP主的MID - **subtitle_content**: 视频字幕内容 - **model**: DeepSeek模型名称,默认为deepseek-chat - **temperature**: 生成温度,控制创造性,默认为0.7 - **max_tokens**: 最大生成标记数,默认为1000 """ try: # 生成自定义摘要 result = await generate_custom_summary( subtitle_content=request.subtitle_content, model=request.model, temperature=request.temperature, max_tokens=request.max_tokens, background_tasks=background_tasks ) # 如果生成成功且配置允许,保存到数据库 if result["success"] and result["summary"] and CACHE_EMPTY_SUMMARY: try: # 保存到数据库 save_success = save_video_summary_to_db( bvid=request.bvid, cid=request.cid, up_mid=request.up_mid, stid="custom_deepseek", # 使用特殊标识表示这是自定义摘要 summary=result["summary"], outline=None, # 自定义摘要暂不支持提纲 result_type=1 # 使用1表示有摘要但无提纲 ) if not save_success: print(f"警告: 保存自定义视频摘要到数据库失败: {request.bvid}, {request.cid}") except Exception as e: print(f"保存自定义摘要到数据库时出错: {str(e)}") # 构建并返回响应 return { "bvid": request.bvid, "cid": request.cid, "up_mid": request.up_mid, "summary": result["summary"], "success": result["success"], "message": result.get("message", ""), "from_deepseek": True, "tokens_used": result.get("tokens_used"), "processing_time": result.get("processing_time") } except Exception as e: raise HTTPException( status_code=500, detail=f"生成自定义摘要时发生错误: {str(e)}" ) # 从字幕文件生成摘要的请求模型 class SubtitleFileRequest(BaseModel): bvid: str cid: int up_mid: int subtitle_file: str = Field(..., description="字幕文件路径,支持SRT或JSON格式") model: Optional[str] = Field("deepseek-chat", description="DeepSeek模型名称") temperature: Optional[float] = Field(0.7, description="生成温度,控制创造性") max_tokens: Optional[int] = Field(1000, description="最大生成标记数") @router.post("/summarize_from_subtitle", summary="从字幕文件生成视频摘要", response_model=CustomSummaryResponse) async def summarize_from_subtitle(request: SubtitleFileRequest, background_tasks: BackgroundTasks): """ 从字幕文件生成视频摘要 - **bvid**: 视频的BVID - **cid**: 视频的CID - **up_mid**: UP主的MID - **subtitle_file**: 字幕文件路径,支持SRT或JSON格式 - **model**: DeepSeek模型名称,默认为deepseek-chat - **temperature**: 生成温度,控制创造性,默认为0.7 - **max_tokens**: 最大生成标记数,默认为1000 """ try: # 检查字幕文件是否存在 if not os.path.exists(request.subtitle_file): raise HTTPException( status_code=400, detail=f"字幕文件不存在: {request.subtitle_file}" ) # 读取字幕文件内容 subtitle_content = "" file_ext = os.path.splitext(request.subtitle_file)[1].lower() if file_ext == '.srt': # 处理SRT格式 with open(request.subtitle_file, 'r', encoding='utf-8') as f: lines = f.readlines() # 提取字幕文本,忽略时间戳和序号 current_text = "" for line in lines: line = line.strip() # 跳过空行、序号行和时间戳行 if not line or line.isdigit() or '-->' in line: continue current_text += line + " " subtitle_content = current_text elif file_ext == '.json': # 处理JSON格式 with open(request.subtitle_file, 'r', encoding='utf-8') as f: subtitle_data = json.load(f) # 根据JSON结构提取字幕文本 if isinstance(subtitle_data, list): # 假设是包含字幕段落的列表 for item in subtitle_data: if isinstance(item, dict) and 'content' in item: subtitle_content += item['content'] + " " elif isinstance(subtitle_data, dict) and 'body' in subtitle_data: # B站字幕格式 for item in subtitle_data['body']: if 'content' in item: subtitle_content += item['content'] + " " else: raise HTTPException( status_code=400, detail=f"不支持的字幕文件格式: {file_ext},仅支持.srt和.json" ) if not subtitle_content: raise HTTPException( status_code=400, detail="无法从字幕文件中提取文本内容" ) # 创建自定义摘要请求 summary_request = CustomSummaryRequest( bvid=request.bvid, cid=request.cid, up_mid=request.up_mid, subtitle_content=subtitle_content, model=request.model, temperature=request.temperature, max_tokens=request.max_tokens ) # 调用自定义摘要生成函数 return await create_custom_summary(summary_request, background_tasks) except HTTPException: raise except Exception as e: raise HTTPException( status_code=500, detail=f"从字幕文件生成摘要时发生错误: {str(e)}" ) @router.get("/prompt", summary="获取视频摘要提示词配置", response_model=VideoSummaryPrompt) async def get_summary_prompt(): """获取视频摘要提示词配置""" try: config = load_config() prompt_config = config.get('deepseek', {}).get('video_summary', {}) return VideoSummaryPrompt( default_prompt=prompt_config.get('default_prompt', ''), custom_prompt=prompt_config.get('custom_prompt', '') ) except Exception as e: raise HTTPException( status_code=500, detail=f"获取提示词配置失败: {str(e)}" ) @router.post("/prompt", summary="更新视频摘要提示词", response_model=VideoSummaryPrompt) async def update_summary_prompt(prompt: str = Body(..., description="新的提示词")): """更新视频摘要提示词配置""" try: config = load_config() # 将多行文本转换为单行(替换换行符为\n) prompt = prompt.replace('\r\n', '\n').replace('\r', '\n') prompt = prompt.replace('\n', '\\n') # 更新配置 if 'deepseek' not in config: config['deepseek'] = {} if 'video_summary' not in config['deepseek']: config['deepseek']['video_summary'] = {} # 保持默认提示词不变,只更新自定义提示词 config['deepseek']['video_summary']['custom_prompt'] = prompt # 保存配置 if not save_config(config): raise HTTPException( status_code=500, detail="保存配置失败" ) return VideoSummaryPrompt( default_prompt=config['deepseek']['video_summary']['default_prompt'], custom_prompt=prompt ) except Exception as e: raise HTTPException( status_code=500, detail=f"更新提示词配置失败: {str(e)}" ) @router.post("/prompt/reset", summary="重置视频摘要提示词到默认值", response_model=VideoSummaryPrompt) async def reset_summary_prompt(): """重置视频摘要提示词到默认值""" try: config = load_config() if 'deepseek' not in config: config['deepseek'] = {} if 'video_summary' not in config['deepseek']: config['deepseek']['video_summary'] = {} # 将自定义提示词重置为默认提示词 default_prompt = config['deepseek']['video_summary']['default_prompt'] config['deepseek']['video_summary']['custom_prompt'] = default_prompt # 保存配置 if not save_config(config): raise HTTPException( status_code=500, detail="保存配置失败" ) return VideoSummaryPrompt( default_prompt=default_prompt, custom_prompt=default_prompt ) except Exception as e: raise HTTPException( status_code=500, detail=f"重置提示词配置失败: {str(e)}" ) # 添加新的请求模型 class CidSummaryRequest(BaseModel): cid: int = Field(..., description="视频的CID") model: Optional[str] = Field(config.get('deepseek', {}).get('default_model', 'deepseek-chat'), description="DeepSeek模型名称") temperature: Optional[float] = Field(config.get('deepseek', {}).get('default_settings', {}).get('temperature', 1.0), description="生成温度,控制创造性") max_tokens: Optional[int] = Field(config.get('deepseek', {}).get('default_settings', {}).get('max_tokens', 8000), description="最大生成标记数") top_p: Optional[float] = Field(config.get('deepseek', {}).get('default_settings', {}).get('top_p', 1.0), description="核采样阈值,控制输出的多样性") stream: Optional[bool] = Field(False, description="是否使用流式输出") json_mode: Optional[bool] = Field(False, description="是否使用JSON模式输出") frequency_penalty: Optional[float] = Field(config.get('deepseek', {}).get('default_settings', {}).get('frequency_penalty', 0.0), description="频率惩罚,避免重复") presence_penalty: Optional[float] = Field(config.get('deepseek', {}).get('default_settings', {}).get('presence_penalty', 0.0), description="存在惩罚,增加话题多样性") @router.post("/summarize_by_cid", summary="根据CID生成视频摘要", response_model=CustomSummaryResponse) async def summarize_by_cid(request: CidSummaryRequest, background_tasks: BackgroundTasks): """根据CID生成视频摘要 参数: - **cid**: 视频的CID - **model**: DeepSeek模型名称,默认为deepseek-chat - **temperature**: 生成温度,控制创造性,默认为0.7 - **max_tokens**: 最大生成标记数,默认为1000 """ # 构建字幕文件路径 stt_dir = os.path.join("output", "stt", str(request.cid)) json_path = os.path.join(stt_dir, f"{request.cid}.json") # 检查字幕文件是否存在 if not os.path.exists(json_path): raise HTTPException( status_code=404, detail=f"未找到CID {request.cid} 的字幕文件" ) # 读取字幕文件 - 直接作为文本读取,不尝试解析为JSON try: with open(json_path, 'r', encoding='utf-8') as f: subtitle_content = f.read().strip() # 如果内容为空,抛出错误 if not subtitle_content: raise HTTPException( status_code=400, detail="字幕文件内容为空" ) # 构造一个简单的元数据字典,用于返回结果 subtitle_data = { "bvid": "", # 这些字段可能在纯文本文件中不存在 "up_mid": 0 } except json.JSONDecodeError: # 如果JSON解析失败,直接读取为文本 with open(json_path, 'r', encoding='utf-8') as f: subtitle_content = f.read().strip() # 构造一个简单的元数据字典 subtitle_data = { "bvid": "", "up_mid": 0 } except Exception as e: raise HTTPException( status_code=500, detail=f"读取字幕文件时出错: {str(e)}" ) # 生成摘要 result = await generate_custom_summary( subtitle_content=subtitle_content, model=request.model, temperature=request.temperature, max_tokens=request.max_tokens, top_p=request.top_p, stream=request.stream, json_mode=request.json_mode, frequency_penalty=request.frequency_penalty, presence_penalty=request.presence_penalty, background_tasks=background_tasks ) # 构建响应数据 response_data = { "bvid": subtitle_data.get('bvid', ''), "cid": request.cid, "up_mid": subtitle_data.get('up_mid', 0), "summary": result.get('summary', ''), "success": result.get('success', False), "message": result.get('message', ''), "from_deepseek": True, "tokens_used": result.get('tokens_used'), "processing_time": result.get('processing_time') } # 保存摘要内容到文件 if result.get('success', False) and result.get('summary'): try: # 创建保存目录 summary_dir = os.path.join("output", "summary", str(request.cid)) os.makedirs(summary_dir, exist_ok=True) # 保存摘要内容 summary_path = os.path.join(summary_dir, f"{request.cid}_summary.txt") with open(summary_path, 'w', encoding='utf-8') as f: f.write(result.get('summary', '')) # 保存完整响应数据(包括token使用情况等) response_path = os.path.join(summary_dir, f"{request.cid}_response.json") with open(response_path, 'w', encoding='utf-8') as f: json.dump(response_data, f, ensure_ascii=False, indent=4) print(f"摘要已保存到: {summary_path}") print(f"完整响应已保存到: {response_path}") except Exception as e: print(f"保存摘要时出错: {str(e)}") # 不影响正常返回,只记录错误 return response_data # 添加新的响应模型,用于检查本地摘要 class LocalSummaryCheckResponse(BaseModel): cid: int exists: bool summary_path: Optional[str] = None response_path: Optional[str] = None full_response: Optional[Dict[str, Any]] = None message: str @router.get("/check_local_summary/{cid}", summary="检查本地是否存在摘要文件", response_model=LocalSummaryCheckResponse) async def check_local_summary(cid: int, include_content: bool = True): """ 检查本地是否存在指定CID的摘要文件 参数: - **cid**: 视频的CID - **include_content**: 是否包含完整响应数据,默认为True 返回: - **exists**: 是否存在摘要文件 - **summary_path**: 摘要文件路径(如果存在) - **response_path**: 响应数据文件路径(如果存在) - **full_response**: 完整响应数据(如果存在且include_content=True) - **message**: 提示信息 """ try: # 构建摘要文件路径 summary_dir = os.path.join("output", "summary", str(cid)) summary_path = os.path.join(summary_dir, f"{cid}_summary.txt") response_path = os.path.join(summary_dir, f"{cid}_response.json") # 检查文件是否存在 summary_exists = os.path.exists(summary_path) response_exists = os.path.exists(response_path) # 如果两个文件都不存在,返回不存在的响应 if not summary_exists and not response_exists: return { "cid": cid, "exists": False, "summary_path": None, "response_path": None, "full_response": None, "message": f"未找到CID {cid} 的本地摘要文件" } # 构建响应数据 result = { "cid": cid, "exists": True, "summary_path": summary_path if summary_exists else None, "response_path": response_path if response_exists else None, "full_response": None, "message": f"找到CID {cid} 的本地摘要文件" } # 如果需要包含内容 if include_content: # 读取完整响应数据 if response_exists: try: with open(response_path, 'r', encoding='utf-8') as f: result["full_response"] = json.load(f) except Exception as e: result["message"] += f",但读取响应数据失败: {str(e)}" # 如果读取JSON失败,尝试从TXT文件构建简单响应 if summary_exists: try: with open(summary_path, 'r', encoding='utf-8') as f: summary_content = f.read() # 构建简单的响应对象 result["full_response"] = { "cid": cid, "summary": summary_content, "success": True, "message": "从摘要文件读取", "from_deepseek": True } except Exception as e2: result["message"] += f",读取摘要文件也失败: {str(e2)}" # 如果没有响应数据文件,但有摘要文件 elif summary_exists: try: with open(summary_path, 'r', encoding='utf-8') as f: summary_content = f.read() # 构建简单的响应对象 result["full_response"] = { "cid": cid, "summary": summary_content, "success": True, "message": "从摘要文件读取", "from_deepseek": True } except Exception as e: result["message"] += f",但读取摘要内容失败: {str(e)}" return result except Exception as e: raise HTTPException( status_code=500, detail=f"检查本地摘要文件时出错: {str(e)}" )
2929004360/ruoyi-sign
1,224
ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java
package com.ruoyi.common.utils.ip; import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.utils.RegionUtil; import com.ruoyi.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 获取地址类 * * @author ruoyi */ public class AddressUtils { private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); // 未知地址 public static final String UNKNOWN = "XX XX"; public static String getRealAddressByIP(String ip) { String address = UNKNOWN; // 内网不查询 if (IpUtils.internalIp(ip)) { return "内网IP"; } if (RuoYiConfig.isAddressEnabled()) { try { String rspStr = RegionUtil.getRegion(ip); if (StringUtils.isEmpty(rspStr)) { log.error("获取地理位置异常 {}", ip); return UNKNOWN; } String[] obj = rspStr.split("\\|"); String region = obj[2]; String city = obj[3]; return String.format("%s %s", region, city); } catch (Exception e) { log.error("获取地理位置异常 {}", e); } } return address; } }
2929004360/ruoyi-sign
10,417
ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/IpUtils.java
package com.ruoyi.common.utils.ip; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.http.HttpServletRequest; import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.StringUtils; /** * 获取IP方法 * * @author ruoyi */ public class IpUtils { public final static String REGX_0_255 = "(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)"; // 匹配 ip public final static String REGX_IP = "((" + REGX_0_255 + "\\.){3}" + REGX_0_255 + ")"; public final static String REGX_IP_WILDCARD = "(((\\*\\.){3}\\*)|(" + REGX_0_255 + "(\\.\\*){3})|(" + REGX_0_255 + "\\." + REGX_0_255 + ")(\\.\\*){2}" + "|((" + REGX_0_255 + "\\.){3}\\*))"; // 匹配网段 public final static String REGX_IP_SEG = "(" + REGX_IP + "\\-" + REGX_IP + ")"; /** * 获取客户端IP * * @return IP地址 */ public static String getIpAddr() { return getIpAddr(ServletUtils.getRequest()); } /** * 获取客户端IP * * @param request 请求对象 * @return IP地址 */ public static String getIpAddr(HttpServletRequest request) { if (request == null) { return "unknown"; } String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip); } /** * 检查是否为内部IP地址 * * @param ip IP地址 * @return 结果 */ public static boolean internalIp(String ip) { byte[] addr = textToNumericFormatV4(ip); return internalIp(addr) || "127.0.0.1".equals(ip); } /** * 检查是否为内部IP地址 * * @param addr byte地址 * @return 结果 */ private static boolean internalIp(byte[] addr) { if (StringUtils.isNull(addr) || addr.length < 2) { return true; } final byte b0 = addr[0]; final byte b1 = addr[1]; // 10.x.x.x/8 final byte SECTION_1 = 0x0A; // 172.16.x.x/12 final byte SECTION_2 = (byte) 0xAC; final byte SECTION_3 = (byte) 0x10; final byte SECTION_4 = (byte) 0x1F; // 192.168.x.x/16 final byte SECTION_5 = (byte) 0xC0; final byte SECTION_6 = (byte) 0xA8; switch (b0) { case SECTION_1: return true; case SECTION_2: if (b1 >= SECTION_3 && b1 <= SECTION_4) { return true; } case SECTION_5: switch (b1) { case SECTION_6: return true; } default: return false; } } /** * 将IPv4地址转换成字节 * * @param text IPv4地址 * @return byte 字节 */ public static byte[] textToNumericFormatV4(String text) { if (text.length() == 0) { return null; } byte[] bytes = new byte[4]; String[] elements = text.split("\\.", -1); try { long l; int i; switch (elements.length) { case 1: l = Long.parseLong(elements[0]); if ((l < 0L) || (l > 4294967295L)) { return null; } bytes[0] = (byte) (int) (l >> 24 & 0xFF); bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF); bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 2: l = Integer.parseInt(elements[0]); if ((l < 0L) || (l > 255L)) { return null; } bytes[0] = (byte) (int) (l & 0xFF); l = Integer.parseInt(elements[1]); if ((l < 0L) || (l > 16777215L)) { return null; } bytes[1] = (byte) (int) (l >> 16 & 0xFF); bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 3: for (i = 0; i < 2; ++i) { l = Integer.parseInt(elements[i]); if ((l < 0L) || (l > 255L)) { return null; } bytes[i] = (byte) (int) (l & 0xFF); } l = Integer.parseInt(elements[2]); if ((l < 0L) || (l > 65535L)) { return null; } bytes[2] = (byte) (int) (l >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 4: for (i = 0; i < 4; ++i) { l = Integer.parseInt(elements[i]); if ((l < 0L) || (l > 255L)) { return null; } bytes[i] = (byte) (int) (l & 0xFF); } break; default: return null; } } catch (NumberFormatException e) { return null; } return bytes; } /** * 获取IP地址 * * @return 本地IP地址 */ public static String getHostIp() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { } return "127.0.0.1"; } /** * 获取主机名 * * @return 本地主机名 */ public static String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { } return "未知"; } /** * 从多级反向代理中获得第一个非unknown IP地址 * * @param ip 获得的IP地址 * @return 第一个非unknown IP地址 */ public static String getMultistageReverseProxyIp(String ip) { // 多级反向代理检测 if (ip != null && ip.indexOf(",") > 0) { final String[] ips = ip.trim().split(","); for (String subIp : ips) { if (false == isUnknown(subIp)) { ip = subIp; break; } } } return StringUtils.substring(ip, 0, 255); } /** * 检测给定字符串是否为未知,多用于检测HTTP请求相关 * * @param checkString 被检测的字符串 * @return 是否未知 */ public static boolean isUnknown(String checkString) { return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString); } /** * 是否为IP */ public static boolean isIP(String ip) { return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP); } /** * 是否为IP,或 *为间隔的通配符地址 */ public static boolean isIpWildCard(String ip) { return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP_WILDCARD); } /** * 检测参数是否在ip通配符里 */ public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip) { String[] s1 = ipWildCard.split("\\."); String[] s2 = ip.split("\\."); boolean isMatchedSeg = true; for (int i = 0; i < s1.length && !s1[i].equals("*"); i++) { if (!s1[i].equals(s2[i])) { isMatchedSeg = false; break; } } return isMatchedSeg; } /** * 是否为特定格式如:“10.10.10.1-10.10.10.99”的ip段字符串 */ public static boolean isIPSegment(String ipSeg) { return StringUtils.isNotBlank(ipSeg) && ipSeg.matches(REGX_IP_SEG); } /** * 判断ip是否在指定网段中 */ public static boolean ipIsInNetNoCheck(String iparea, String ip) { int idx = iparea.indexOf('-'); String[] sips = iparea.substring(0, idx).split("\\."); String[] sipe = iparea.substring(idx + 1).split("\\."); String[] sipt = ip.split("\\."); long ips = 0L, ipe = 0L, ipt = 0L; for (int i = 0; i < 4; ++i) { ips = ips << 8 | Integer.parseInt(sips[i]); ipe = ipe << 8 | Integer.parseInt(sipe[i]); ipt = ipt << 8 | Integer.parseInt(sipt[i]); } if (ips > ipe) { long t = ips; ips = ipe; ipe = t; } return ips <= ipt && ipt <= ipe; } /** * 校验ip是否符合过滤串规则 * * @param filter 过滤IP列表,支持后缀'*'通配,支持网段如:`10.10.10.1-10.10.10.99` * @param ip 校验IP地址 * @return boolean 结果 */ public static boolean isMatchedIp(String filter, String ip) { if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip)) { return false; } String[] ips = filter.split(";"); for (String iStr : ips) { if (isIP(iStr) && iStr.equals(ip)) { return true; } else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip)) { return true; } else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip)) { return true; } } return false; } }
281677160/openwrt-package
1,068
luci-app-homeproxy/root/etc/uci-defaults/luci-homeproxy
#!/bin/sh [ -f "/www/luci-static/resources/icons/loading.gif" ] && \ sed -i "s,/loading.svg,/loading.gif,g" "/www/luci-static/resources/view/homeproxy/status.js" uci -q batch <<-EOF >"/dev/null" delete firewall.homeproxy_pre delete firewall.homeproxy_forward set firewall.homeproxy_forward=include set firewall.homeproxy_forward.type=nftables set firewall.homeproxy_forward.path="/var/run/homeproxy/fw4_forward.nft" set firewall.homeproxy_forward.position="chain-pre" set firewall.homeproxy_forward.chain="forward" delete firewall.homeproxy_input set firewall.homeproxy_input=include set firewall.homeproxy_input.type=nftables set firewall.homeproxy_input.path="/var/run/homeproxy/fw4_input.nft" set firewall.homeproxy_input.position="chain-pre" set firewall.homeproxy_input.chain="input" delete firewall.homeproxy_post set firewall.homeproxy_post=include set firewall.homeproxy_post.type=nftables set firewall.homeproxy_post.path="/var/run/homeproxy/fw4_post.nft" set firewall.homeproxy_post.position="table-post" commit firewall EOF exit 0
2977094657/BilibiliHistoryFetcher
25,284
routers/title_pattern_discovery.py
import json import os import sqlite3 from collections import Counter, defaultdict from typing import List, Dict, Tuple, Set, Optional import jieba import numpy as np from sklearn.cluster import KMeans from sklearn.feature_extraction.text import TfidfVectorizer from snownlp import SnowNLP class PatternCache: """模式缓存管理器""" def __init__(self, cache_dir: str = None): if cache_dir is None: # 使用项目根目录下的cache文件夹 import sys import os project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) self.cache_dir = os.path.join(project_root, "cache") else: self.cache_dir = cache_dir # 确保缓存目录存在并设置正确的权限 try: print(f"尝试创建缓存目录: {self.cache_dir}") # 如果目录不存在,创建它 if not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir, mode=0o755, exist_ok=True) print(f"缓存目录已创建: {self.cache_dir}") # 确保目录权限正确 os.chmod(self.cache_dir, 0o755) print(f"缓存目录权限已设置为755") # 根据操作系统获取用户信息 if sys.platform != 'win32': import pwd import grp current_user = pwd.getpwuid(os.getuid()).pw_name current_group = grp.getgrgid(os.getgid()).gr_name print(f"当前用户: {current_user}") print(f"当前用户组: {current_group}") else: current_user = os.getlogin() if hasattr(os, 'getlogin') else 'unknown' print(f"当前用户: {current_user}") # 检查目录权限 mode = oct(os.stat(self.cache_dir).st_mode)[-3:] print(f"缓存目录权限: {mode}") # 尝试创建测试文件以验证写入权限 test_file = os.path.join(self.cache_dir, "test.txt") try: with open(test_file, 'w') as f: f.write("test") os.remove(test_file) print("缓存目录写入权限验证成功") except Exception as e: print(f"缓存目录写入权限验证失败: {str(e)}") print(f"错误类型: {type(e).__name__}") print(f"错误详情: {str(e)}") except Exception as e: print(f"创建缓存目录时出错: {str(e)}") print(f"错误类型: {type(e).__name__}") print(f"错误详情: {str(e)}") # 如果是权限问题,打印更多信息 if isinstance(e, PermissionError): print(f"当前用户: {os.getlogin() if hasattr(os, 'getlogin') else 'unknown'}") print(f"当前工作目录: {os.getcwd()}") print(f"目录是否存在: {os.path.exists(self.cache_dir)}") if os.path.exists(self.cache_dir): print(f"目录权限: {oct(os.stat(self.cache_dir).st_mode)[-3:]}") def _get_cache_path(self, table_name: str, pattern_type: str) -> str: """获取缓存文件路径""" cache_file = f"{table_name}_{pattern_type}_patterns.json" cache_path = os.path.join(self.cache_dir, cache_file) print(f"缓存文件路径: {cache_path}") return cache_path def get_cached_patterns(self, table_name: str, pattern_type: str) -> Optional[Dict]: """ 获取缓存的模式数据 Args: table_name: 数据表名 pattern_type: 模式类型('title' 或 'interaction') Returns: Dict | None: 缓存的模式数据,如果缓存不存在则返回None """ try: cache_path = self._get_cache_path(table_name, pattern_type) if not os.path.exists(cache_path): print(f"缓存文件不存在: {cache_path}") return None print(f"读取缓存文件: {cache_path}") with open(cache_path, 'r', encoding='utf-8') as f: data = json.load(f) print(f"成功读取缓存数据,包含 {len(data)} 个模式") return data except Exception as e: print(f"读取缓存时出错: {str(e)}") print(f"错误类型: {type(e).__name__}") print(f"错误详情: {str(e)}") return None def cache_patterns(self, table_name: str, pattern_type: str, patterns: Dict) -> None: """ 缓存模式数据 Args: table_name: 数据表名 pattern_type: 模式类型('title' 或 'interaction') patterns: 要缓存的模式数据 """ try: if not patterns: print("没有模式数据需要缓存") return cache_path = self._get_cache_path(table_name, pattern_type) print(f"准备写入缓存: {cache_path}") print(f"缓存数据包含 {len(patterns)} 个模式") # 确保目录存在 os.makedirs(os.path.dirname(cache_path), exist_ok=True) with open(cache_path, 'w', encoding='utf-8') as f: json.dump(patterns, f, ensure_ascii=False, indent=2) print(f"成功写入缓存: {cache_path}") except Exception as e: print(f"写入缓存时出错: {str(e)}") print(f"错误类型: {type(e).__name__}") print(f"错误详情: {str(e)}") # 如果是权限问题,打印更多信息 if isinstance(e, PermissionError): print(f"缓存目录权限: {oct(os.stat(self.cache_dir).st_mode)[-3:]}") print(f"当前用户: {os.getlogin()}") print(f"当前工作目录: {os.getcwd()}") print(f"目录是否存在: {os.path.exists(self.cache_dir)}") if os.path.exists(self.cache_dir): print(f"目录权限: {oct(os.stat(self.cache_dir).st_mode)[-3:]}") # 创建全局缓存管理器实例 pattern_cache = PatternCache() def get_stop_words() -> Set[str]: """获取停用词列表""" return { '的', '了', '是', '在', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这', '那', '啊', '呢', '吧', '吗', '啦', '呀', '哦', '哈', '嘿', '哎', '哟', '唉', '嗯', '嘛', '哼', '哇', '咦', '诶', '喂', '么', '什么', '这个', '那个', '这样', '那样', '怎么', '为什么', '如何', '哪里', '谁', '什么时候', '多少', '几', '怎样', '为何', '哪个', '哪些', '几个', '多久', '多长时间', '什么样' } def collect_title_data(cursor: sqlite3.Cursor, table_name: str) -> List[Tuple[str, float, float, str, int]]: """ 从数据库收集标题数据 Args: cursor: 数据库游标 table_name: 表名 Returns: List[Tuple]: 包含(title, duration, progress, tag_name, view_at)的元组列表 """ cursor.execute(f""" SELECT title, duration, progress, tag_name, view_at FROM {table_name} WHERE title IS NOT NULL AND title != '' """) return cursor.fetchall() def preprocess_titles(titles_data: List[Tuple[str, float, float, str, int]]) -> List[str]: """ 预处理标题文本 Args: titles_data: 原始标题数据 Returns: List[str]: 预处理后的标题列表 """ stop_words = get_stop_words() processed_titles = [] for title_data in titles_data: title = title_data[0] # 分词 words = jieba.cut(title) # 过滤停用词和单字词 filtered_words = [w for w in words if w not in stop_words and len(w) > 1] # 重新组合成句子 processed_title = ' '.join(filtered_words) processed_titles.append(processed_title) return processed_titles def extract_title_features(processed_titles: List[str], n_features: int = 1000) -> Tuple[TfidfVectorizer, np.ndarray]: """ 提取标题特征 Args: processed_titles: 预处理后的标题列表 n_features: 特征数量 Returns: Tuple: (TF-IDF向量器, 特征矩阵) """ vectorizer = TfidfVectorizer(max_features=n_features) features = vectorizer.fit_transform(processed_titles) return vectorizer, features def validate_patterns(titles_data: List[Tuple[str, float, float, str, int]], patterns: Dict) -> Dict: """ 验证和优化发现的模式 Args: titles_data: 原始标题数据 patterns: 发现的模式字典 Returns: Dict: 优化后的模式字典 """ print(f"开始验证模式,标题数量: {len(titles_data)}, 模式数量: {len(patterns)}") # 计算每个模式的覆盖率和区分度 pattern_metrics = {} total_titles = len(titles_data) if total_titles == 0: # 如果没有标题数据,直接返回原始模式 return {name: {**info, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 }} for name, info in patterns.items()} titles = [t[0] for t in titles_data] # 提取标题文本 # 计算每个模式的覆盖率和区分度 for pattern_name, pattern_info in patterns.items(): # 计算该模式覆盖的标题数量 covered_titles = sum(1 for title in titles if any(keyword in title for keyword in pattern_info['keywords'])) # 计算覆盖率 coverage = covered_titles / total_titles # 计算区分度(独特性) unique_coverage = 0 shared_coverage = 0 for title in titles: # 检查当前模式是否匹配 current_matches = any(keyword in title for keyword in pattern_info['keywords']) if current_matches: # 检查其他模式是否也匹配 other_matches = sum(1 for other_name, other_info in patterns.items() if other_name != pattern_name and any(keyword in title for keyword in other_info['keywords'])) if other_matches == 0: unique_coverage += 1 else: shared_coverage += 1 # 计算区分度,避免除零错误 total_matches = unique_coverage + shared_coverage distinctiveness = unique_coverage / total_matches if total_matches > 0 else 0 pattern_metrics[pattern_name] = { 'coverage': coverage, 'distinctiveness': distinctiveness, 'unique_matches': unique_coverage, 'shared_matches': shared_coverage } # 优化模式 optimized_patterns = {} for pattern_name, pattern_info in patterns.items(): metrics = pattern_metrics[pattern_name] # 如果模式的覆盖率太低或区分度太低,尝试优化 if metrics['coverage'] < 0.05 or metrics['distinctiveness'] < 0.3: # 获取该模式下的所有标题 pattern_titles = [title for title in titles if any(keyword in title for keyword in pattern_info['keywords'])] # 重新提取关键词,使用更严格的TF-IDF阈值 if pattern_titles: try: vectorizer = TfidfVectorizer(max_features=5) # 减少关键词数量,提高精确性 features = vectorizer.fit_transform(pattern_titles) keywords = vectorizer.get_feature_names_out() # 更新模式信息 optimized_patterns[pattern_name] = { 'keywords': list(keywords), 'sentiment': pattern_info['sentiment'], 'sample_size': len(pattern_titles), 'metrics': metrics } except Exception: # 如果TF-IDF提取失败,保持原有关键词 optimized_patterns[pattern_name] = { **pattern_info, 'metrics': metrics } else: # 如果没有匹配的标题,保持原有模式 optimized_patterns[pattern_name] = { **pattern_info, 'metrics': metrics } else: # 保持原有模式,只添加指标信息 optimized_patterns[pattern_name] = { **pattern_info, 'metrics': metrics } return optimized_patterns def discover_title_patterns(titles_data: List[Tuple[str, float, float, str, int]], n_clusters: int = 5) -> Dict: """ 发现标题模式 Args: titles_data: 原始标题数据 n_clusters: 聚类数量 Returns: Dict: 发现的模式及其关键词 """ # 数据验证 if not titles_data: return { 'default': { 'keywords': [], 'sentiment': 0.5, 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } # 预处理标题 processed_titles = preprocess_titles(titles_data) if not processed_titles: # 如果预处理后没有有效标题 return { 'default': { 'keywords': [], 'sentiment': 0.5, 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } # 调整聚类数量,确保不超过标题数量 actual_n_clusters = min(n_clusters, len(processed_titles)) if actual_n_clusters < 2: # 如果数据太少,不进行聚类 # 直接使用TF-IDF提取关键词 try: vectorizer = TfidfVectorizer(max_features=10) features = vectorizer.fit_transform(processed_titles) keywords = list(vectorizer.get_feature_names_out()) # 计算情感倾向 sentiments = [SnowNLP(title).sentiments for title in processed_titles] avg_sentiment = float(np.mean(sentiments)) patterns = { '默认模式': { 'keywords': keywords, 'sentiment': avg_sentiment, 'sample_size': len(processed_titles) } } # 验证和优化模式 optimized_patterns = validate_patterns(titles_data, patterns) return optimized_patterns except Exception as e: print(f"Error in TF-IDF processing: {str(e)}") return { 'default': { 'keywords': [], 'sentiment': 0.5, 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } try: # 提取特征 vectorizer, features = extract_title_features(processed_titles) # 聚类 kmeans = KMeans(n_clusters=actual_n_clusters, random_state=42) clusters = kmeans.fit_predict(features) # 分析每个聚类的特征词 patterns = {} for i in range(actual_n_clusters): # 获取该聚类的标题索引 cluster_indices = np.where(clusters == i)[0] if len(cluster_indices) == 0: # 如果聚类为空,跳过 continue cluster_titles = [processed_titles[idx] for idx in cluster_indices] try: # 为该聚类创建新的TF-IDF向量器 cluster_vectorizer = TfidfVectorizer(max_features=10) cluster_features = cluster_vectorizer.fit_transform(cluster_titles) # 获取特征词 feature_names = cluster_vectorizer.get_feature_names_out() # 计算该聚类的主要情感倾向 sentiments = [SnowNLP(title).sentiments for title in cluster_titles] avg_sentiment = float(np.mean(sentiments)) # 根据情感和关键词确定模式名称 if avg_sentiment > 0.6: pattern_type = '积极' elif avg_sentiment < 0.4: pattern_type = '消极' else: pattern_type = '中性' # 存储模式信息 patterns[f'模式{i+1}_{pattern_type}'] = { 'keywords': list(feature_names), 'sentiment': avg_sentiment, 'sample_size': len(cluster_titles) } except Exception as e: print(f"Error processing cluster {i}: {str(e)}") continue # 如果没有成功创建任何模式,返回默认模式 if not patterns: return { 'default': { 'keywords': [], 'sentiment': 0.5, 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } # 验证和优化模式 optimized_patterns = validate_patterns(titles_data, patterns) return optimized_patterns except Exception as e: print(f"Error in pattern discovery: {str(e)}") return { 'default': { 'keywords': [], 'sentiment': 0.5, 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } def discover_interaction_patterns(titles_data: List[Tuple[str, float, float, str, int]]) -> Dict: """ 发现互动模式 Args: titles_data: 原始标题数据 Returns: Dict: 发现的互动模式及其关键词 """ try: # 数据验证 if not titles_data: return { 'default': { 'keywords': [], 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } # 预处理标题 processed_titles = preprocess_titles(titles_data) if not processed_titles: # 如果预处理后没有有效标题 return { 'default': { 'keywords': [], 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } # 定义基本的语言模式特征 question_markers = { # 基础疑问词 '?', '?', '吗', '呢', '么', '嘛', '吧', # 特定疑问词 '什么', '为什么', '如何', '怎么', '怎样', '几时', '哪里', '谁', '多少', '哪个', '哪些', '几个', '多久', '怎么办', '怎么样', '为何', '是不是', # 疑问词组 '难道说', '究竟是', '到底是', '是否', '能否', '可否', '何必', '何不', '为何要', '怎么会', '怎么能', '如何才能', '为什么会', '是不是要', # 反问词组 '岂不是', '难道不', '怎能不', '何尝不', '谁不', # 网络流行疑问 '啥玩意', '啥情况', '咋回事', '咋办', '咋整', '啥意思', '这是啥', '这是什么', '这啥啊', '这怎么回事', '这合理吗', '这能行吗', '这靠谱吗', '这玩意儿', '搞啥呢', '闹哪样', '整啥活', '整这出' } exclamation_markers = { # 基础感叹词 '!', '!', '啊', '哇', '哦', '呀', '呐', '哎', '诶', '咦', # 程度词 '太', '真', '好', '非常', '超级', '特别', '极其', '格外', '分外', '相当', '十分', '很是', '尤其', '特', '超', '贼', '巨', # 感叹词组 '太棒了', '真棒', '好厉害', '太强了', '太牛了', '太秀了', '绝了', '震惊', '惊呆了', '厉害了', '牛逼', '卧槽', '我的天', '天呐', '要命', '要死了', '受不了', '没谁了', '绝绝子', '太可了', '太爱了', # 正面评价 '完美', '神级', '顶级', '极品', '优秀', '精彩', '精品', '经典', '必看', '值得', '推荐', '珍藏', '收藏', '赞', '好评', # 负面感叹 '可怕', '恐怖', '吓人', '要命', '糟糕', '完蛋', '惨', '惨了', '可恶', '气死', '无语', '离谱', '扯淡', '要疯了', # B站特色感叹 '草', '蚌埠住了', '绷不住了', '崩溃', '破防了', '麻了', '顶不住了', '笑死', '笑yue了', '笑死我了', '乐死我了', '乐', '孝死', '爷青回', '爷青结', '爷哭了', '泪目', '呜呜呜', '呜呜', '啊这', '这河里吗', '这不河里', '这不对劲', '这不科学', # 2023-2024热梗 '鼠鼠我啊', '答应我', '不要再', '给我狠狠', '给我使劲', '啊对对对', '好似', '开香槟咯', '大胆', '荒谬', '我说不要', '我说要要要', '不认识', '很会', '很懂', '不懂就问', '求求了', '人生建议', '建议', '速速', '狠狠', '使劲', '疯狂', '大声', '大胆', # 2024新梗 '纯纯', '典典', '润润', '狂狂', '疯疯', '笑死个人', '急急国王', '急急子', '急了急了', '慌慌子', '慌了慌了', '酸酸子', '酸了酸了', '急了蚌', '笑死蚌', '破防蚌', '麻了蚌', # 网络流行语 '太上头了', '上头', '太香了', '香疯了', '太戳了', '戳爆了', '太欧了', '太非了', '太悲伤了', '太难了', '太难蚌了', '太难绷了', '太离谱了', '太荒谬了', '太逆天了', '太致命了', '太邪门了', '太魔幻了', '太真实了', '太炸裂了', '太生草了', # 新增流行语 '真的会谢', '真的会哭', '真的会笑', '真的会玩', '狠狠地心动', '狠狠地心疼', '狠狠地感动', '狠狠地共情', '生死时速', '生死时刻', '生死时分', '生死关头', '一整个', '一整个爱了', '一整个哭了', '一整个笑了', # 夸张表达 '吊炸天', '厉害炸了', '牛炸了', '强炸了', '秀炸了', '猛炸了', '狠炸了', '吓死人', '笑死人', '气死人', '玩明白了', '玩懂了', '玩透了', '整明白了', '整懂了', '整透了', '搞明白了', '搞懂了', '搞透了' } dialogue_markers = { # 基础对话词 '来', '一起', '让我们', '跟着', '教你', '告诉你', # 邀请词组 '带你', '陪你', '和你', '跟你', '请你', '邀请你', '一块儿', '一块', '一同', '共同', '大家', '咱们', # 引导词组 '看看', '来看', '快看', '瞧瞧', '听听', '试试', '学习', '了解', '探索', '发现', '感受', '体验', # 分享词组 '分享', '推荐', '介绍', '安利', '种草', '测评', '解说', '讲解', '教程', '攻略', '指南', '技巧', # 互动词组 '互动', '交流', '讨论', '聊聊', '说说', '谈谈', '评论', '留言', '关注', '订阅', '点赞', '转发', # B站特色互动 '三连', '一键三连', '点个三连', '求三连', '给个三连', '投币', '充电', '收藏', '关注', '催更', '别走', '别急', '慢慢看', '细细品', '仔细看', '往后看', # 2023-2024新增互动 '速来', '速看', '速冲', '速进', '速食', '必看合集', '珍藏合集', '收藏合集', '经典合集', '建议收藏', '建议点赞', '建议三连', '建议关注', '记得一键三连', '记得关注', '记得收藏', '记得转发', '务必三连', '务必收藏', '务必关注', '务必转发', # 网络流行互动 '整活', '搞起来', '安排上', '冲冲冲', '搞快点', '安排', '奥利给', '搞起', '整起来', '冲它', '搞这个', '整这个', '来这个', '整一个', '搞一个', # 口语化表达 '咱整个', '咱搞个', '咱来个', '给你整个', '给你搞个', '跟你说个', '给你说个', '告诉你个', '说个事', '整点刺激的', '搞点刺激的', '来点刺激的', '整点意思', '搞点意思', # 新增口语化 '给大家整个', '给大家搞个', '给大家来个', '给你们整个', '给你们搞个', '给你们来个', '速速来个', '速速整个', '速速搞个', # 亲切称呼 '老铁', '兄弟', '姐妹', '小伙伴', '小可爱', '小宝贝', '宝', '亲', '朋友', '兄弟姐妹', '铁子', '老哥', '老姐', '老弟', '老妹', '小老弟', '小老妹', # 新增称呼 '宝贝们', '亲们', '朋友们', '兄弟们', '姐妹们', '小伙伴们', '铁子们', '老铁们', '粉丝们', '观众们' } # 统计各种模式的出现 pattern_stats = defaultdict(lambda: {'titles': [], 'keywords': Counter()}) for title, processed_title in zip([t[0] for t in titles_data], processed_titles): words = processed_title.split() try: # 检测问句模式 if any(marker in title for marker in question_markers): pattern_stats['疑问式']['titles'].append(title) pattern_stats['疑问式']['keywords'].update(words) # 检测感叹句模式 if any(marker in title for marker in exclamation_markers): pattern_stats['感叹式']['titles'].append(title) pattern_stats['感叹式']['keywords'].update(words) # 检测对话式模式 if any(marker in title for marker in dialogue_markers): pattern_stats['对话式']['titles'].append(title) pattern_stats['对话式']['keywords'].update(words) except Exception as e: print(f"Error processing title: {str(e)}") continue # 处理统计结果 interaction_patterns = {} for pattern_name, stats in pattern_stats.items(): if stats['titles']: # 如果有匹配的标题 try: interaction_patterns[pattern_name] = { 'keywords': [word for word, _ in stats['keywords'].most_common(10)], 'sample_size': len(stats['titles']) } except Exception as e: print(f"Error processing pattern {pattern_name}: {str(e)}") continue # 如果没有发现任何模式,返回默认模式 if not interaction_patterns: interaction_patterns = { 'default': { 'keywords': [], 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } } return interaction_patterns except Exception as e: print(f"Error in interaction pattern discovery: {str(e)}") return { 'default': { 'keywords': [], 'sample_size': 0, 'metrics': { 'coverage': 0, 'distinctiveness': 0, 'unique_matches': 0, 'shared_matches': 0 } } }
2977094657/BilibiliHistoryFetcher
23,931
routers/deepseek.py
""" DeepSeek API 路由 提供与DeepSeek大语言模型交互的API接口 """ import json import os import re from datetime import datetime from typing import Optional, List import aiohttp import requests import yaml from fastapi import APIRouter, HTTPException, BackgroundTasks from pydantic import BaseModel, Field # 创建API路由 router = APIRouter() # 定义请求和响应模型 class ChatMessage(BaseModel): role: str = Field(..., description="消息角色,可以是'user'、'assistant'或'system'") content: str = Field(..., description="消息内容") class ChatRequest(BaseModel): messages: List[ChatMessage] = Field(..., description="聊天消息列表") model: Optional[str] = Field(None, description="模型名称,例如'deepseek-chat'") temperature: Optional[float] = Field(None, description="温度参数,控制生成文本的随机性") max_tokens: Optional[int] = Field(None, description="最大生成的token数量") top_p: Optional[float] = Field(None, description="核采样参数") stream: Optional[bool] = Field(False, description="是否使用流式输出") json_mode: Optional[bool] = Field(False, description="是否启用JSON输出模式") class StreamResponse(BaseModel): content: str = Field(..., description="当前生成的内容片段") finish_reason: Optional[str] = Field(None, description="完成原因") class TokenDetails(BaseModel): cached_tokens: Optional[int] = Field(0, description="缓存的token数量") class UsageInfo(BaseModel): prompt_tokens: int = Field(..., description="提示tokens数量") completion_tokens: int = Field(..., description="完成tokens数量") total_tokens: int = Field(..., description="总tokens数量") prompt_tokens_details: Optional[TokenDetails] = Field(None, description="提示tokens详情") class ChatResponse(BaseModel): content: str = Field(..., description="生成的内容") model: str = Field(..., description="使用的模型") usage: UsageInfo = Field(..., description="Token使用情况") finish_reason: Optional[str] = Field(None, description="完成原因") class ModelInfo(BaseModel): id: str object: str = "model" owned_by: str = "deepseek" class ModelList(BaseModel): object: str = "list" data: List[ModelInfo] class BalanceInfo(BaseModel): currency: str = Field(..., description="货币类型,例如 CNY 或 USD") total_balance: str = Field(..., description="可用的余额,包含折扣金额和充值金额") granted_balance: str = Field(..., description="折扣金额") topped_up_balance: str = Field(..., description="充值金额") class BalanceResponse(BaseModel): is_available: bool = Field(..., description="当前账户是否有可用的余额可以使用 API 调用") balance_infos: List[BalanceInfo] = Field(..., description="余额信息列表") class ApiKeyRequest(BaseModel): api_key: str = Field(..., description="DeepSeek API密钥") class ApiKeyResponse(BaseModel): success: bool = Field(..., description="操作是否成功") message: str = Field(..., description="操作结果消息") class ApiKeyStatusResponse(BaseModel): is_set: bool = Field(..., description="API密钥是否已设置") is_valid: bool = Field(..., description="API密钥是否有效") message: str = Field(..., description="状态描述信息") # 加载YAML配置文件 def load_config(): """加载配置文件""" config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.yaml") try: with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) return config except Exception as e: print(f"加载配置文件出错: {e}") return {} # 获取配置 config = load_config() deepseek_config = config.get('deepseek', {}) # 设置API密钥(优先使用环境变量,其次使用配置文件) API_KEY = os.environ.get("DEEPSEEK_API_KEY", deepseek_config.get('api_key', '')) API_BASE = deepseek_config.get('api_base', 'https://api.deepseek.com/v1') DEFAULT_MODEL = deepseek_config.get('default_model', 'deepseek-chat') SSL_VERIFY = deepseek_config.get('ssl_verify', False) # 默认关闭SSL验证 # 辅助函数,用于记录API调用日志 async def log_api_call(model: str, prompt_tokens: int, completion_tokens: int): """记录API调用日志,可以扩展为保存到数据库或发送到监控系统""" usage_info = { "timestamp": datetime.now().isoformat(), "model": model, "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": prompt_tokens + completion_tokens } # 未来可添加写入数据库或发送到监控系统的代码 print(f"DeepSeek API调用: {usage_info}") def update_yaml_field(content: str, field_path: list, new_value: Optional[str]) -> str: """ 更新YAML文件中特定字段的值,保持其他内容不变 Args: content: YAML文件内容 field_path: 字段路径,如 ['deepseek', 'api_key'] new_value: 新的值,如果为None则删除该字段 """ lines = content.split('\n') current_level = 0 parent_found = [False] * len(field_path) parent_found[0] = True # 根级别总是存在的 # 首先检查父级字段是否存在 for i in range(len(lines)): line = lines[i] if not line.strip() or line.strip().startswith('#'): continue # 计算当前行的缩进级别 indent_count = len(line) - len(line.lstrip()) current_level = indent_count // 2 # 检查是否匹配当前级别的字段 if current_level < len(field_path) - 1: field_match = re.match(r'^\s*' + field_path[current_level] + r'\s*:', line) if field_match: parent_found[current_level + 1] = True # 如果父级字段不存在,需要创建 if not all(parent_found): # 找到需要创建的最高级别的父级字段 first_missing = parent_found.index(False) # 找到合适的位置插入 insert_pos = 0 for i in range(len(lines)): if i == len(lines) - 1 or (i < len(lines) - 1 and not lines[i+1].strip()): insert_pos = i + 1 break # 创建缺失的父级字段 for level in range(first_missing, len(field_path)): indent = ' ' * (2 * (level - 1)) if level == len(field_path) - 1: # 最后一级是要设置的字段 value_str = f'"{new_value}"' if new_value is not None else "" lines.insert(insert_pos, f"{indent}{field_path[level]}: {value_str}") else: # 中间级别 lines.insert(insert_pos, f"{indent}{field_path[level]}:") insert_pos += 1 return '\n'.join(lines) # 如果所有父级字段都存在,查找并更新目标字段 target_field = field_path[-1] target_level = len(field_path) - 1 target_indent = ' ' * (2 * target_level) field_pattern = f"^{target_indent}{target_field}:.*$" field_found = False for i, line in enumerate(lines): # 跳过空行和注释 if not line.strip() or line.strip().startswith('#'): continue # 计算当前行的缩进级别 indent_count = len(line) - len(line.lstrip()) current_level = indent_count // 2 # 检查是否是目标字段所在的父级上下文 if current_level == target_level - 1 and target_level > 0: parent_match = re.match(r'^\s*' + field_path[target_level - 1] + r'\s*:', line) if parent_match: # 在父级字段下查找目标字段 j = i + 1 while j < len(lines) and (not lines[j].strip() or lines[j].strip().startswith('#') or len(lines[j]) - len(lines[j].lstrip()) > indent_count): field_match = re.match(field_pattern, lines[j]) if field_match: # 找到目标字段,更新它 value_str = f'"{new_value}"' if new_value is not None else "" lines[j] = f"{target_indent}{target_field}: {value_str}" field_found = True break j += 1 # 如果没找到目标字段,在父级下添加 if not field_found: value_str = f'"{new_value}"' if new_value is not None else "" lines.insert(i + 1, f"{target_indent}{target_field}: {value_str}") field_found = True break # 如果是根级别字段 if target_level == 0 and re.match(field_pattern, line): value_str = f'"{new_value}"' if new_value is not None else "" lines[i] = f"{target_field}: {value_str}" field_found = True break # 如果没找到字段,在文件末尾添加 if not field_found: # 构建完整的字段路径 for level in range(len(field_path)): indent = ' ' * (2 * level) if level == len(field_path) - 1: value_str = f'"{new_value}"' if new_value is not None else "" lines.append(f"{indent}{field_path[level]}: {value_str}") else: lines.append(f"{indent}{field_path[level]}:") return '\n'.join(lines) @router.post("/chat", response_model=ChatResponse) async def chat_completion( request: ChatRequest, background_tasks: BackgroundTasks ): """ 与DeepSeek API进行聊天交互 """ if not API_KEY: raise HTTPException(status_code=500, detail="API密钥未配置,请在config/config.yaml中设置deepseek.api_key或设置DEEPSEEK_API_KEY环境变量") # 准备API调用 url = f"{API_BASE}/chat/completions" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } # 从配置中获取默认设置 default_settings = deepseek_config.get('default_settings', {}) # 请求数据 data = { "model": request.model or DEFAULT_MODEL, "messages": [{"role": msg.role, "content": msg.content} for msg in request.messages], "temperature": request.temperature if request.temperature is not None else default_settings.get("temperature", 1.0), "max_tokens": request.max_tokens if request.max_tokens is not None else default_settings.get("max_tokens", 1000), } # 添加可选参数 if request.top_p is not None: data["top_p"] = request.top_p # 如果启用JSON模式 if request.json_mode: data["response_format"] = {"type": "json_object"} # 如果启用流式输出,则抛出异常(应该使用stream端点) if request.stream: raise HTTPException(status_code=400, detail="流式输出请使用 /deepseek/stream 端点") try: # 发送请求 response = requests.post(url, headers=headers, json=data, verify=SSL_VERIFY) response.raise_for_status() # 抛出HTTP错误,如果有的话 # 获取响应 result = response.json() # 提取内容 content = result.get("choices", [{}])[0].get("message", {}).get("content", "") finish_reason = result.get("choices", [{}])[0].get("finish_reason") # 获取Token使用量 usage = result.get("usage", {}) prompt_tokens = usage.get("prompt_tokens", 0) completion_tokens = usage.get("completion_tokens", 0) total_tokens = usage.get("total_tokens", 0) prompt_tokens_details = usage.get("prompt_tokens_details", {"cached_tokens": 0}) # 添加后台任务记录API调用 background_tasks.add_task( log_api_call, request.model or DEFAULT_MODEL, prompt_tokens, completion_tokens ) return { "content": content, "model": request.model or DEFAULT_MODEL, "usage": { "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": total_tokens, "prompt_tokens_details": prompt_tokens_details }, "finish_reason": finish_reason } except requests.exceptions.RequestException as e: error_message = f"API调用出错: {str(e)}" if hasattr(e, 'response') and e.response: error_message += f"\n错误详情: {e.response.text}" raise HTTPException(status_code=500, detail=error_message) @router.post("/stream") async def stream_completion(request: ChatRequest): """ 与DeepSeek API进行流式交互 注意:此函数返回的是一个流式响应,不同于普通的JSON响应 """ # 流式输出必须为True if not request.stream: request.stream = True if not API_KEY: raise HTTPException(status_code=500, detail="API密钥未配置,请在config/config.yaml中设置deepseek.api_key或设置DEEPSEEK_API_KEY环境变量") # 准备API调用 url = f"{API_BASE}/chat/completions" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } # 从配置中获取默认设置 default_settings = deepseek_config.get('default_settings', {}) # 请求数据 data = { "model": request.model or DEFAULT_MODEL, "messages": [{"role": msg.role, "content": msg.content} for msg in request.messages], "temperature": request.temperature if request.temperature is not None else default_settings.get("temperature", 1.0), "max_tokens": request.max_tokens if request.max_tokens is not None else default_settings.get("max_tokens", 1000), "stream": True # 启用流式输出 } # 添加可选参数 if request.top_p is not None: data["top_p"] = request.top_p # 如果启用JSON模式 if request.json_mode: data["response_format"] = {"type": "json_object"} try: # 创建一个异步生成器函数处理流式响应 async def generate(): # 使用同步请求获取流式响应 with requests.post(url, headers=headers, json=data, stream=True, verify=SSL_VERIFY) as response: response.raise_for_status() # 抛出HTTP错误,如果有的话 # 返回SSE格式的流式响应 for line in response.iter_lines(): if line: line_str = line.decode('utf-8') # 处理SSE格式数据 if line_str.startswith('data: '): data_str = line_str[6:] # 跳过'data: ' if data_str == '[DONE]': yield f"data: {json.dumps({'content': '', 'finish_reason': 'stop'})}\n\n" break try: data = json.loads(data_str) delta = data.get('choices', [{}])[0].get('delta', {}) content = delta.get('content', '') finish_reason = data.get('choices', [{}])[0].get('finish_reason') yield f"data: {json.dumps({'content': content, 'finish_reason': finish_reason})}\n\n" except json.JSONDecodeError: yield f"data: {json.dumps({'content': '[解析错误]', 'finish_reason': None})}\n\n" # 返回流式响应 from fastapi.responses import StreamingResponse return StreamingResponse(generate(), media_type="text/event-stream") except requests.exceptions.RequestException as e: error_message = f"API调用出错: {str(e)}" if hasattr(e, 'response') and e.response: error_message += f"\n错误详情: {e.response.text}" raise HTTPException(status_code=500, detail=error_message) @router.get("/models", response_model=ModelList, summary="列出可用的DeepSeek模型") async def list_models(): """ 列出可用的DeepSeek模型列表,并提供相关模型的基本信息 Returns: 包含模型列表的响应对象,每个模型包含id、类型和所有者信息 """ try: api_key = config.get('deepseek', {}).get('api_key') if not api_key: raise HTTPException(status_code=401, detail="未配置DeepSeek API密钥") api_base = config.get('deepseek', {}).get('api_base', 'https://api.deepseek.com/v1') async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=SSL_VERIFY)) as session: async with session.get( f"{api_base}/models", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } ) as response: if response.status != 200: error_msg = await response.text() raise HTTPException( status_code=response.status, detail=f"DeepSeek API请求失败: {error_msg}" ) data = await response.json() return ModelList( object="list", data=[ ModelInfo( id=model["id"], object=model.get("object", "model"), owned_by=model.get("owned_by", "deepseek") ) for model in data.get("data", []) ] ) except aiohttp.ClientError as e: raise HTTPException( status_code=500, detail=f"请求DeepSeek API时发生错误: {str(e)}" ) except Exception as e: raise HTTPException( status_code=500, detail=f"获取模型列表时发生错误: {str(e)}" ) @router.get("/balance", response_model=BalanceResponse, summary="查询DeepSeek余额") async def get_user_balance(): """ 查询DeepSeek余额信息 Returns: 包含余额信息的响应对象,包括是否有可用余额、余额类型、总余额、折扣金额和充值金额 """ try: api_key = config.get('deepseek', {}).get('api_key') if not api_key: raise HTTPException(status_code=401, detail="未配置DeepSeek API密钥") api_base = config.get('deepseek', {}).get('api_base', 'https://api.deepseek.com/v1') # 构造余额查询URL balance_url = f"{api_base}/user/balance" async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=SSL_VERIFY)) as session: async with session.get( balance_url, headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } ) as response: if response.status != 200: error_msg = await response.text() raise HTTPException( status_code=response.status, detail=f"DeepSeek API请求失败: {error_msg}" ) data = await response.json() return BalanceResponse( is_available=data.get("is_available", False), balance_infos=[ BalanceInfo( currency=balance_info.get("currency", ""), total_balance=balance_info.get("total_balance", "0.00"), granted_balance=balance_info.get("granted_balance", "0.00"), topped_up_balance=balance_info.get("topped_up_balance", "0.00") ) for balance_info in data.get("balance_infos", []) ] ) except aiohttp.ClientError as e: raise HTTPException( status_code=500, detail=f"请求DeepSeek API时发生错误: {str(e)}" ) except Exception as e: raise HTTPException( status_code=500, detail=f"获取余额信息时发生错误: {str(e)}" ) @router.get("/check_api_key", response_model=ApiKeyStatusResponse, summary="检查DeepSeek API密钥是否已设置且有效") async def check_api_key(): """ 检查DeepSeek API密钥是否已设置且有效 Returns: 包含API密钥设置状态和有效性的响应对象 """ try: # 检查全局API_KEY和配置文件中的API密钥 api_key = API_KEY or config.get('deepseek', {}).get('api_key', '') if not api_key: return ApiKeyStatusResponse( is_set=False, is_valid=False, message="API密钥未设置" ) # 验证API密钥是否有效 api_base = config.get('deepseek', {}).get('api_base', 'https://api.deepseek.com/v1') test_url = f"{api_base}/models" # 使用模型列表API来测试 async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=SSL_VERIFY)) as session: async with session.get( test_url, headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } ) as response: if response.status != 200: error_msg = await response.text() try: # 解析错误信息 error_data = json.loads(error_msg) if "error" in error_data and "message" in error_data["error"]: error_msg = error_data["error"]["message"] except: # 解析错误信息失败,使用原始错误信息 pass return ApiKeyStatusResponse( is_set=True, is_valid=False, message=f"API密钥无效: {error_msg}" ) # API密钥有效 return ApiKeyStatusResponse( is_set=True, is_valid=True, message="API密钥有效" ) except aiohttp.ClientError as e: return ApiKeyStatusResponse( is_set=True, is_valid=False, message=f"验证API密钥时发生网络错误: {str(e)}" ) except Exception as e: raise HTTPException( status_code=500, detail=f"检查API密钥状态时发生错误: {str(e)}" ) @router.post("/set_api_key", response_model=ApiKeyResponse, summary="设置DeepSeek API密钥") async def set_api_key(request: ApiKeyRequest): """ 设置DeepSeek API密钥 - **api_key**: DeepSeek API密钥 Returns: 操作结果消息 """ global API_KEY, config try: # 验证API密钥是否有效 api_base = config.get('deepseek', {}).get('api_base', 'https://api.deepseek.com/v1') test_url = f"{api_base}/models" # 使用模型列表API来测试 async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=SSL_VERIFY)) as session: async with session.get( test_url, headers={ "Authorization": f"Bearer {request.api_key}", "Content-Type": "application/json" } ) as response: if response.status != 200: error_msg = await response.text() try: # 解析错误信息 error_data = json.loads(error_msg) if "error" in error_data and "message" in error_data["error"]: error_msg = error_data["error"]["message"] except: # 解析错误信息失败,使用原始错误信息 pass return ApiKeyResponse( success=False, message=f"API密钥无效: {error_msg}" ) # API密钥有效,更新全局变量 API_KEY = request.api_key # 保存到配置文件 # 获取配置文件路径 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.yaml") try: # 读取配置文件 with open(config_path, 'r', encoding='utf-8') as f: content = f.read() # 使用精确更新方法更新API密钥 updated_content = update_yaml_field(content, ['deepseek', 'api_key'], request.api_key) # 写入配置文件 with open(config_path, 'w', encoding='utf-8') as f: f.write(updated_content) # 更新全局配置 config = load_config() return ApiKeyResponse( success=True, message="API密钥已更新并保存到配置文件" ) except Exception as e: # 保存到配置文件失败,但API密钥已更新 return ApiKeyResponse( success=False, message=f"保存API密钥到配置文件失败: {str(e)}" ) except aiohttp.ClientError as e: raise HTTPException( status_code=500, detail=f"请求DeepSeek API时发生错误: {str(e)}" ) except Exception as e: raise HTTPException( status_code=500, detail=f"设置API密钥时发生错误: {str(e)}" )
2929004360/ruoyi-sign
62,094
ruoyi-common/src/main/java/com/ruoyi/common/utils/poi/ExcelUtil.java
package com.ruoyi.common.utils.poi; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.math.BigDecimal; import java.text.DecimalFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import cn.hutool.core.util.ObjectUtil; import com.alibaba.excel.EasyExcel; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFPicture; import org.apache.poi.hssf.usermodel.HSSFPictureData; import org.apache.poi.hssf.usermodel.HSSFShape; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ooxml.POIXMLDocumentPart; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.DataValidation; import org.apache.poi.ss.usermodel.DataValidationConstraint; import org.apache.poi.ss.usermodel.DataValidationHelper; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.PictureData; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDataValidation; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFPicture; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.annotation.Excel.ColumnType; import com.ruoyi.common.annotation.Excel.Type; import com.ruoyi.common.annotation.Excels; import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.text.Convert; import com.ruoyi.common.exception.UtilException; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.DictUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.file.FileTypeUtils; import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.common.utils.file.ImageUtils; import com.ruoyi.common.utils.reflect.ReflectUtils; /** * Excel相关处理 * * @author ruoyi */ public class ExcelUtil<T> { private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); public static final String FORMULA_REGEX_STR = "=|-|\\+|@"; public static final String[] FORMULA_STR = { "=", "-", "+", "@" }; /** * 用于dictType属性数据存储,避免重复查缓存 */ public Map<String, String> sysDictMap = new HashMap<String, String>(); /** * Excel sheet最大行数,默认65536 */ public static final int sheetSize = 65536; /** * 工作表名称 */ private String sheetName; /** * 导出类型(EXPORT:导出数据;IMPORT:导入模板) */ private Type type; /** * 工作薄对象 */ private Workbook wb; /** * 工作表对象 */ private Sheet sheet; /** * 样式列表 */ private Map<String, CellStyle> styles; /** * 导入导出数据列表 */ private List<T> list; /** * 注解列表 */ private List<Object[]> fields; /** * 当前行号 */ private int rownum; /** * 标题 */ private String title; /** * 最大高度 */ private short maxHeight; /** * 合并后最后行数 */ private int subMergedLastRowNum = 0; /** * 合并后开始行数 */ private int subMergedFirstRowNum = 1; /** * 对象的子列表方法 */ private Method subMethod; /** * 对象的子列表属性 */ private List<Field> subFields; /** * 统计列表 */ private Map<Integer, Double> statistics = new HashMap<Integer, Double>(); /** * 数字格式 */ private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00"); /** * 实体对象 */ public Class<T> clazz; /** * 需要显示列属性 */ public String[] includeFields; /** * 需要排除列属性 */ public String[] excludeFields; public ExcelUtil(Class<T> clazz) { this.clazz = clazz; } /** * 仅在Excel中显示列属性 * * @param fields 列属性名 示例[单个"name"/多个"id","name"] */ public void showColumn(String... fields) { this.includeFields = fields; } /** * 隐藏Excel中列属性 * * @param fields 列属性名 示例[单个"name"/多个"id","name"] */ public void hideColumn(String... fields) { this.excludeFields = fields; } public void init(List<T> list, String sheetName, String title, Type type) { if (list == null) { list = new ArrayList<T>(); } this.list = list; this.sheetName = sheetName; this.type = type; this.title = title; createExcelField(); createWorkbook(); createTitle(); createSubHead(); } /** * 创建excel第一行标题 */ public void createTitle() { if (StringUtils.isNotEmpty(title)) { int titleLastCol = this.fields.size() - 1; if (isSubList()) { titleLastCol = titleLastCol + subFields.size() - 1; } Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0); titleRow.setHeightInPoints(30); Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), 0, titleLastCol)); } } /** * 创建对象的子列表名称 */ public void createSubHead() { if (isSubList()) { Row subRow = sheet.createRow(rownum); int column = 0; int subFieldSize = subFields != null ? subFields.size() : 0; for (Object[] objects : fields) { Field field = (Field) objects[0]; Excel attr = (Excel) objects[1]; if (Collection.class.isAssignableFrom(field.getType())) { Cell cell = subRow.createCell(column); cell.setCellValue(attr.name()); cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); if (subFieldSize > 1) { CellRangeAddress cellAddress = new CellRangeAddress(rownum, rownum, column, column + subFieldSize - 1); sheet.addMergedRegion(cellAddress); } column += subFieldSize; } else { Cell cell = subRow.createCell(column++); cell.setCellValue(attr.name()); cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); } } rownum++; } } /** * 对excel表单默认第一个索引名转换成list * * @param is 输入流 * @return 转换后集合 */ public List<T> importExcel(InputStream is) { List<T> list = null; try { list = importExcel(is, 0); } catch (Exception e) { log.error("导入Excel异常{}", e.getMessage()); throw new UtilException(e.getMessage()); } finally { IOUtils.closeQuietly(is); } return list; } /** * 对excel表单默认第一个索引名转换成list * * @param is 输入流 * @param titleNum 标题占用行数 * @return 转换后集合 */ public List<T> importExcel(InputStream is, int titleNum) throws Exception { return importExcel(StringUtils.EMPTY, is, titleNum); } /** * 对excel表单指定表格索引名转换成list * * @param sheetName 表格索引名 * @param titleNum 标题占用行数 * @param is 输入流 * @return 转换后集合 */ public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception { this.type = Type.IMPORT; this.wb = WorkbookFactory.create(is); List<T> list = new ArrayList<T>(); // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0); if (sheet == null) { throw new IOException("文件sheet不存在"); } boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook); Map<String, PictureData> pictures; if (isXSSFWorkbook) { pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb); } else { pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb); } // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1 int rows = sheet.getLastRowNum(); if (rows > 0) { // 定义一个map用于存放excel列的序号和field. Map<String, Integer> cellMap = new HashMap<String, Integer>(); // 获取表头 Row heard = sheet.getRow(titleNum); for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) { Cell cell = heard.getCell(i); if (StringUtils.isNotNull(cell)) { String value = this.getCellValue(heard, i).toString(); cellMap.put(value, i); } else { cellMap.put(null, i); } } // 有数据时才处理 得到类的所有field. List<Object[]> fields = this.getFields(); Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>(); for (Object[] objects : fields) { Excel attr = (Excel) objects[1]; Integer column = cellMap.get(attr.name()); if (column != null) { fieldsMap.put(column, objects); } } for (int i = titleNum + 1; i <= rows; i++) { // 从第2行开始取数据,默认第一行是表头. Row row = sheet.getRow(i); // 判断当前行是否是空行 if (isRowEmpty(row)) { continue; } T entity = null; for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet()) { Object val = this.getCellValue(row, entry.getKey()); // 如果不存在实例则新建. entity = (entity == null ? clazz.newInstance() : entity); // 从map中得到对应列的field. Field field = (Field) entry.getValue()[0]; Excel attr = (Excel) entry.getValue()[1]; // 取得类型,并根据对象类型设置值. Class<?> fieldType = field.getType(); if (String.class == fieldType) { String s = Convert.toStr(val); if (StringUtils.endsWith(s, ".0")) { val = StringUtils.substringBefore(s, ".0"); } else { String dateFormat = field.getAnnotation(Excel.class).dateFormat(); if (StringUtils.isNotEmpty(dateFormat)) { val = parseDateToStr(dateFormat, val); } else { val = Convert.toStr(val); } } } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) { val = Convert.toInt(val); } else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val))) { val = Convert.toLong(val); } else if (Double.TYPE == fieldType || Double.class == fieldType) { val = Convert.toDouble(val); } else if (Float.TYPE == fieldType || Float.class == fieldType) { val = Convert.toFloat(val); } else if (BigDecimal.class == fieldType) { val = Convert.toBigDecimal(val); } else if (Date.class == fieldType) { if (val instanceof String) { val = DateUtils.parseDate(val); } else if (val instanceof Double) { val = DateUtil.getJavaDate((Double) val); } } else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) { val = Convert.toBool(val, false); } if (StringUtils.isNotNull(fieldType)) { String propertyName = field.getName(); if (StringUtils.isNotEmpty(attr.targetAttr())) { propertyName = field.getName() + "." + attr.targetAttr(); } if (StringUtils.isNotEmpty(attr.readConverterExp())) { val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); } else if (StringUtils.isNotEmpty(attr.dictType())) { if (!sysDictMap.containsKey(attr.dictType() + val)) { String dictValue = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); sysDictMap.put(attr.dictType() + val, dictValue); } val = sysDictMap.get(attr.dictType() + val); } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) { val = dataFormatHandlerAdapter(val, attr, null); } else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures)) { PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey()); if (image == null) { val = ""; } else { byte[] data = image.getData(); val = FileUtils.writeImportBytes(data); } } ReflectUtils.invokeSetter(entity, propertyName, val); } } list.add(entity); } } return list; } /** * 对list数据源将其里面的数据导入到excel表单 * * @param list 导出数据集合 * @param sheetName 工作表的名称 * @return 结果 */ public AjaxResult exportExcel(List<T> list, String sheetName) { return exportExcel(list, sheetName, StringUtils.EMPTY); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param list 导出数据集合 * @param sheetName 工作表的名称 * @param title 标题 * @return 结果 */ public AjaxResult exportExcel(List<T> list, String sheetName, String title) { this.init(list, sheetName, title, Type.EXPORT); return exportExcel(); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param response 返回数据 * @param list 导出数据集合 * @param sheetName 工作表的名称 * @return 结果 */ public void exportExcel(HttpServletResponse response, List<T> list, String sheetName) { exportExcel(response, list, sheetName, StringUtils.EMPTY); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param response 返回数据 * @param list 导出数据集合 * @param sheetName 工作表的名称 * @param title 标题 * @return 结果 */ public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title) { response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); this.init(list, sheetName, title, Type.EXPORT); exportExcel(response); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param sheetName 工作表的名称 * @return 结果 */ public AjaxResult importTemplateExcel(String sheetName) { return importTemplateExcel(sheetName, StringUtils.EMPTY); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param sheetName 工作表的名称 * @param title 标题 * @return 结果 */ public AjaxResult importTemplateExcel(String sheetName, String title) { this.init(null, sheetName, title, Type.IMPORT); return exportExcel(); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param sheetName 工作表的名称 * @return 结果 */ public void importTemplateExcel(HttpServletResponse response, String sheetName) { importTemplateExcel(response, sheetName, StringUtils.EMPTY); } /** * 对list数据源将其里面的数据导入到excel表单 * * @param sheetName 工作表的名称 * @param title 标题 * @return 结果 */ public void importTemplateExcel(HttpServletResponse response, String sheetName, String title) { response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); this.init(null, sheetName, title, Type.IMPORT); exportExcel(response); } /** * 对list数据源将其里面的数据导入到excel表单 * * @return 结果 */ public void exportExcel(HttpServletResponse response) { try { writeSheet(); wb.write(response.getOutputStream()); } catch (Exception e) { log.error("导出Excel异常{}", e.getMessage()); } finally { IOUtils.closeQuietly(wb); } } /** * 对list数据源将其里面的数据导入到excel表单 * * @return 结果 */ public AjaxResult exportExcel() { OutputStream out = null; try { writeSheet(); String filename = encodingFilename(sheetName); out = new FileOutputStream(getAbsoluteFile(filename)); wb.write(out); return AjaxResult.success(filename); } catch (Exception e) { log.error("导出Excel异常{}", e.getMessage()); throw new UtilException("导出Excel失败,请联系网站管理员!"); } finally { IOUtils.closeQuietly(wb); IOUtils.closeQuietly(out); } } /** * 创建写入数据到Sheet */ public void writeSheet() { // 取出一共有多少个sheet. int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize)); for (int index = 0; index < sheetNo; index++) { createSheet(sheetNo, index); // 产生一行 Row row = sheet.createRow(rownum); int column = 0; // 写入各个字段的列头名称 for (Object[] os : fields) { Field field = (Field) os[0]; Excel excel = (Excel) os[1]; if (Collection.class.isAssignableFrom(field.getType())) { for (Field subField : subFields) { Excel subExcel = subField.getAnnotation(Excel.class); this.createHeadCell(subExcel, row, column++); } } else { this.createHeadCell(excel, row, column++); } } if (Type.EXPORT.equals(type)) { fillExcelData(index, row); addStatisticsRow(); } } } /** * 填充excel数据 * * @param index 序号 * @param row 单元格行 */ @SuppressWarnings("unchecked") public void fillExcelData(int index, Row row) { int startNo = index * sheetSize; int endNo = Math.min(startNo + sheetSize, list.size()); int currentRowNum = rownum + 1; // 从标题行后开始 for (int i = startNo; i < endNo; i++) { row = sheet.createRow(currentRowNum); T vo = (T) list.get(i); int column = 0; int maxSubListSize = getCurrentMaxSubListSize(vo); for (Object[] os : fields) { Field field = (Field) os[0]; Excel excel = (Excel) os[1]; if (Collection.class.isAssignableFrom(field.getType())) { try { Collection<?> subList = (Collection<?>) getTargetValue(vo, field, excel); if (subList != null && !subList.isEmpty()) { int subIndex = 0; for (Object subVo : subList) { Row subRow = sheet.getRow(currentRowNum + subIndex); if (subRow == null) { subRow = sheet.createRow(currentRowNum + subIndex); } int subColumn = column; for (Field subField : subFields) { Excel subExcel = subField.getAnnotation(Excel.class); addCell(subExcel, subRow, (T) subVo, subField, subColumn++); } subIndex++; } column += subFields.size(); } } catch (Exception e) { log.error("填充集合数据失败", e); } } else { // 创建单元格并设置值 addCell(excel, row, vo, field, column); if (maxSubListSize > 1 && excel.needMerge()) { sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum + maxSubListSize - 1, column, column)); } column++; } } currentRowNum += maxSubListSize; } } /** * 获取子列表最大数 */ private int getCurrentMaxSubListSize(T vo) { int maxSubListSize = 1; for (Object[] os : fields) { Field field = (Field) os[0]; if (Collection.class.isAssignableFrom(field.getType())) { try { Collection<?> subList = (Collection<?>) getTargetValue(vo, field, (Excel) os[1]); if (subList != null && !subList.isEmpty()) { maxSubListSize = Math.max(maxSubListSize, subList.size()); } } catch (Exception e) { log.error("获取集合大小失败", e); } } } return maxSubListSize; } /** * 创建表格样式 * * @param wb 工作薄对象 * @return 样式列表 */ private Map<String, CellStyle> createStyles(Workbook wb) { // 写入各条记录,每条记录对应excel表中的一行 Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); CellStyle style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); Font titleFont = wb.createFont(); titleFont.setFontName("Arial"); titleFont.setFontHeightInPoints((short) 16); titleFont.setBold(true); style.setFont(titleFont); DataFormat dataFormat = wb.createDataFormat(); style.setDataFormat(dataFormat.getFormat("@")); styles.put("title", style); style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setBorderRight(BorderStyle.THIN); style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderLeft(BorderStyle.THIN); style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderTop(BorderStyle.THIN); style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderBottom(BorderStyle.THIN); style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); Font dataFont = wb.createFont(); dataFont.setFontName("Arial"); dataFont.setFontHeightInPoints((short) 10); style.setFont(dataFont); styles.put("data", style); style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); Font totalFont = wb.createFont(); totalFont.setFontName("Arial"); totalFont.setFontHeightInPoints((short) 10); style.setFont(totalFont); styles.put("total", style); styles.putAll(annotationHeaderStyles(wb, styles)); styles.putAll(annotationDataStyles(wb)); return styles; } /** * 根据Excel注解创建表格头样式 * * @param wb 工作薄对象 * @return 自定义样式列表 */ private Map<String, CellStyle> annotationHeaderStyles(Workbook wb, Map<String, CellStyle> styles) { Map<String, CellStyle> headerStyles = new HashMap<String, CellStyle>(); for (Object[] os : fields) { Excel excel = (Excel) os[1]; String key = StringUtils.format("header_{}_{}", excel.headerColor(), excel.headerBackgroundColor()); if (!headerStyles.containsKey(key)) { CellStyle style = wb.createCellStyle(); style.cloneStyleFrom(styles.get("data")); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setFillForegroundColor(excel.headerBackgroundColor().index); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); Font headerFont = wb.createFont(); headerFont.setFontName("Arial"); headerFont.setFontHeightInPoints((short) 10); headerFont.setBold(true); headerFont.setColor(excel.headerColor().index); style.setFont(headerFont); // 设置表格头单元格文本形式 DataFormat dataFormat = wb.createDataFormat(); style.setDataFormat(dataFormat.getFormat("@")); headerStyles.put(key, style); } } return headerStyles; } /** * 根据Excel注解创建表格列样式 * * @param wb 工作薄对象 * @return 自定义样式列表 */ private Map<String, CellStyle> annotationDataStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); for (Object[] os : fields) { Field field = (Field) os[0]; Excel excel = (Excel) os[1]; if (Collection.class.isAssignableFrom(field.getType())) { ParameterizedType pt = (ParameterizedType) field.getGenericType(); Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0]; List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class); for (Field subField : subFields) { Excel subExcel = subField.getAnnotation(Excel.class); annotationDataStyles(styles, subField, subExcel); } } else { annotationDataStyles(styles, field, excel); } } return styles; } /** * 根据Excel注解创建表格列样式 * * @param styles 自定义样式列表 * @param field 属性列信息 * @param excel 注解信息 */ public void annotationDataStyles(Map<String, CellStyle> styles, Field field, Excel excel) { String key = StringUtils.format("data_{}_{}_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor(), excel.cellType(), excel.wrapText()); if (!styles.containsKey(key)) { CellStyle style = wb.createCellStyle(); style.setAlignment(excel.align()); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setBorderRight(BorderStyle.THIN); style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderLeft(BorderStyle.THIN); style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderTop(BorderStyle.THIN); style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBorderBottom(BorderStyle.THIN); style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setFillForegroundColor(excel.backgroundColor().getIndex()); style.setWrapText(excel.wrapText()); Font dataFont = wb.createFont(); dataFont.setFontName("Arial"); dataFont.setFontHeightInPoints((short) 10); dataFont.setColor(excel.color().index); style.setFont(dataFont); if (ColumnType.TEXT == excel.cellType()) { DataFormat dataFormat = wb.createDataFormat(); style.setDataFormat(dataFormat.getFormat("@")); } styles.put(key, style); } } /** * 创建单元格 */ public Cell createHeadCell(Excel attr, Row row, int column) { // 创建列 Cell cell = row.createCell(column); // 写入列信息 cell.setCellValue(attr.name()); setDataValidation(attr, row, column); cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); if (isSubList()) { // 填充默认样式,防止合并单元格样式失效 sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor(), attr.cellType(), attr.wrapText()))); if (attr.needMerge()) { sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column)); } } return cell; } /** * 设置单元格信息 * * @param value 单元格值 * @param attr 注解相关 * @param cell 单元格信息 */ public void setCellVo(Object value, Excel attr, Cell cell) { if (ColumnType.STRING == attr.cellType() || ColumnType.TEXT == attr.cellType()) { String cellValue = Convert.toStr(value); // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。 if (StringUtils.startsWithAny(cellValue, FORMULA_STR)) { cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0"); } if (value instanceof Collection && StringUtils.equals("[]", cellValue)) { cellValue = StringUtils.EMPTY; } cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix()); } else if (ColumnType.NUMERIC == attr.cellType()) { if (StringUtils.isNotNull(value)) { cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); } } else if (ColumnType.IMAGE == attr.cellType()) { ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1); if(ObjectUtil.isNull(value)){ return; } String[] split = value.toString().split(","); for (String path : split) { String imagePath = Convert.toStr(path); if (StringUtils.isNotEmpty(imagePath)) { byte[] data = ImageUtils.getImage(imagePath); getDrawingPatriarch(cell.getSheet()).createPicture(anchor, cell.getSheet().getWorkbook().addPicture(data, getImageType(data))); } } } } /** * 获取画布 */ public static Drawing<?> getDrawingPatriarch(Sheet sheet) { if (sheet.getDrawingPatriarch() == null) { sheet.createDrawingPatriarch(); } return sheet.getDrawingPatriarch(); } /** * 获取图片类型,设置图片插入类型 */ public int getImageType(byte[] value) { String type = FileTypeUtils.getFileExtendName(value); if ("JPG".equalsIgnoreCase(type)) { return Workbook.PICTURE_TYPE_JPEG; } else if ("PNG".equalsIgnoreCase(type)) { return Workbook.PICTURE_TYPE_PNG; } return Workbook.PICTURE_TYPE_JPEG; } /** * 创建表格样式 */ public void setDataValidation(Excel attr, Row row, int column) { if (attr.name().indexOf("注:") >= 0) { sheet.setColumnWidth(column, 6000); } else { // 设置列宽 sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); } if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0 || attr.comboReadDict()) { String[] comboArray = attr.combo(); if (attr.comboReadDict()) { if (!sysDictMap.containsKey("combo_" + attr.dictType())) { String labels = DictUtils.getDictLabels(attr.dictType()); sysDictMap.put("combo_" + attr.dictType(), labels); } String val = sysDictMap.get("combo_" + attr.dictType()); comboArray = StringUtils.split(val, DictUtils.SEPARATOR); } if (comboArray.length > 15 || StringUtils.join(comboArray).length() > 255) { // 如果下拉数大于15或字符串长度大于255,则使用一个新sheet存储,避免生成的模板下拉值获取不到 setXSSFValidationWithHidden(sheet, comboArray, attr.prompt(), 1, 100, column, column); } else { // 提示信息或只能选择不能输入的列内容. setPromptOrValidation(sheet, comboArray, attr.prompt(), 1, 100, column, column); } } } /** * 添加单元格 */ public Cell addCell(Excel attr, Row row, T vo, Field field, int column) { Cell cell = null; try { // 设置行高 row.setHeight(maxHeight); // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列. if (attr.isExport()) { // 创建cell cell = row.createCell(column); if (isSubListValue(vo) && getListCellValue(vo).size() > 1 && attr.needMerge()) { if (subMergedLastRowNum >= subMergedFirstRowNum) { sheet.addMergedRegion(new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column)); } } cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor(), attr.cellType(), attr.wrapText()))); // 用于读取对象中的属性 Object value = getTargetValue(vo, field, attr); String dateFormat = attr.dateFormat(); String readConverterExp = attr.readConverterExp(); String separator = attr.separator(); String dictType = attr.dictType(); if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) { cell.setCellValue(parseDateToStr(dateFormat, value)); } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) { cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator)); } else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)) { if (!sysDictMap.containsKey(dictType + value)) { String lable = convertDictByExp(Convert.toStr(value), dictType, separator); sysDictMap.put(dictType + value, lable); } cell.setCellValue(sysDictMap.get(dictType + value)); } else if (value instanceof BigDecimal && -1 != attr.scale()) { cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).doubleValue()); } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) { cell.setCellValue(dataFormatHandlerAdapter(value, attr, cell)); } else { // 设置列类型 setCellVo(value, attr, cell); } addStatisticsData(column, Convert.toStr(value), attr); } } catch (Exception e) { log.error("导出Excel失败{}", e); } return cell; } /** * 设置 POI XSSFSheet 单元格提示或选择框 * * @param sheet 表单 * @param textlist 下拉框显示的内容 * @param promptContent 提示内容 * @param firstRow 开始行 * @param endRow 结束行 * @param firstCol 开始列 * @param endCol 结束列 */ public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow, int firstCol, int endCol) { DataValidationHelper helper = sheet.getDataValidationHelper(); DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1"); CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); DataValidation dataValidation = helper.createValidation(constraint, regions); if (StringUtils.isNotEmpty(promptContent)) { // 如果设置了提示信息则鼠标放上去提示 dataValidation.createPromptBox("", promptContent); dataValidation.setShowPromptBox(true); } // 处理Excel兼容性问题 if (dataValidation instanceof XSSFDataValidation) { dataValidation.setSuppressDropDownArrow(true); dataValidation.setShowErrorBox(true); } else { dataValidation.setSuppressDropDownArrow(false); } sheet.addValidationData(dataValidation); } /** * 设置某些列的值只能输入预制的数据,显示下拉框(兼容超出一定数量的下拉框). * * @param sheet 要设置的sheet. * @param textlist 下拉框显示的内容 * @param promptContent 提示内容 * @param firstRow 开始行 * @param endRow 结束行 * @param firstCol 开始列 * @param endCol 结束列 */ public void setXSSFValidationWithHidden(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow, int firstCol, int endCol) { String hideSheetName = "combo_" + firstCol + "_" + endCol; Sheet hideSheet = wb.createSheet(hideSheetName); // 用于存储 下拉菜单数据 for (int i = 0; i < textlist.length; i++) { hideSheet.createRow(i).createCell(0).setCellValue(textlist[i]); } // 创建名称,可被其他单元格引用 Name name = wb.createName(); name.setNameName(hideSheetName + "_data"); name.setRefersToFormula(hideSheetName + "!$A$1:$A$" + textlist.length); DataValidationHelper helper = sheet.getDataValidationHelper(); // 加载下拉列表内容 DataValidationConstraint constraint = helper.createFormulaListConstraint(hideSheetName + "_data"); // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列 CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); // 数据有效性对象 DataValidation dataValidation = helper.createValidation(constraint, regions); if (StringUtils.isNotEmpty(promptContent)) { // 如果设置了提示信息则鼠标放上去提示 dataValidation.createPromptBox("", promptContent); dataValidation.setShowPromptBox(true); } // 处理Excel兼容性问题 if (dataValidation instanceof XSSFDataValidation) { dataValidation.setSuppressDropDownArrow(true); dataValidation.setShowErrorBox(true); } else { dataValidation.setSuppressDropDownArrow(false); } sheet.addValidationData(dataValidation); // 设置hiddenSheet隐藏 wb.setSheetHidden(wb.getSheetIndex(hideSheet), true); } /** * 解析导出值 0=男,1=女,2=未知 * * @param propertyValue 参数值 * @param converterExp 翻译注解 * @param separator 分隔符 * @return 解析后值 */ public static String convertByExp(String propertyValue, String converterExp, String separator) { StringBuilder propertyString = new StringBuilder(); String[] convertSource = converterExp.split(","); for (String item : convertSource) { String[] itemArray = item.split("="); if (StringUtils.containsAny(propertyValue, separator)) { for (String value : propertyValue.split(separator)) { if (itemArray[0].equals(value)) { propertyString.append(itemArray[1] + separator); break; } } } else { if (itemArray[0].equals(propertyValue)) { return itemArray[1]; } } } return StringUtils.stripEnd(propertyString.toString(), separator); } /** * 反向解析值 男=0,女=1,未知=2 * * @param propertyValue 参数值 * @param converterExp 翻译注解 * @param separator 分隔符 * @return 解析后值 */ public static String reverseByExp(String propertyValue, String converterExp, String separator) { StringBuilder propertyString = new StringBuilder(); String[] convertSource = converterExp.split(","); for (String item : convertSource) { String[] itemArray = item.split("="); if (StringUtils.containsAny(propertyValue, separator)) { for (String value : propertyValue.split(separator)) { if (itemArray[1].equals(value)) { propertyString.append(itemArray[0] + separator); break; } } } else { if (itemArray[1].equals(propertyValue)) { return itemArray[0]; } } } return StringUtils.stripEnd(propertyString.toString(), separator); } /** * 解析字典值 * * @param dictValue 字典值 * @param dictType 字典类型 * @param separator 分隔符 * @return 字典标签 */ public static String convertDictByExp(String dictValue, String dictType, String separator) { return DictUtils.getDictLabel(dictType, dictValue, separator); } /** * 反向解析值字典值 * * @param dictLabel 字典标签 * @param dictType 字典类型 * @param separator 分隔符 * @return 字典值 */ public static String reverseDictByExp(String dictLabel, String dictType, String separator) { return DictUtils.getDictValue(dictType, dictLabel, separator); } /** * 数据处理器 * * @param value 数据值 * @param excel 数据注解 * @return */ public String dataFormatHandlerAdapter(Object value, Excel excel, Cell cell) { try { Object instance = excel.handler().newInstance(); Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class }); value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb); } catch (Exception e) { log.error("不能格式化数据 " + excel.handler(), e.getMessage()); } return Convert.toStr(value); } /** * 合计统计信息 */ private void addStatisticsData(Integer index, String text, Excel entity) { if (entity != null && entity.isStatistics()) { Double temp = 0D; if (!statistics.containsKey(index)) { statistics.put(index, temp); } try { temp = Double.valueOf(text); } catch (NumberFormatException e) { } statistics.put(index, statistics.get(index) + temp); } } /** * 创建统计行 */ public void addStatisticsRow() { if (statistics.size() > 0) { Row row = sheet.createRow(sheet.getLastRowNum() + 1); Set<Integer> keys = statistics.keySet(); Cell cell = row.createCell(0); cell.setCellStyle(styles.get("total")); cell.setCellValue("合计"); for (Integer key : keys) { cell = row.createCell(key); cell.setCellStyle(styles.get("total")); cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key))); } statistics.clear(); } } /** * 编码文件名 */ public String encodingFilename(String filename) { filename = UUID.randomUUID() + "_" + filename + ".xlsx"; return filename; } /** * 获取下载路径 * * @param filename 文件名称 */ public String getAbsoluteFile(String filename) { String downloadPath = RuoYiConfig.getDownloadPath() + filename; File desc = new File(downloadPath); if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } return downloadPath; } /** * 获取bean中的属性值 * * @param vo 实体对象 * @param field 字段 * @param excel 注解 * @return 最终的属性值 * @throws Exception */ private Object getTargetValue(T vo, Field field, Excel excel) throws Exception { field.setAccessible(true); Object o = field.get(vo); if (StringUtils.isNotEmpty(excel.targetAttr())) { String target = excel.targetAttr(); if (target.contains(".")) { String[] targets = target.split("[.]"); for (String name : targets) { o = getValue(o, name); } } else { o = getValue(o, target); } } return o; } /** * 以类的属性的get方法方法形式获取值 * * @param o * @param name * @return value * @throws Exception */ private Object getValue(Object o, String name) throws Exception { if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name)) { Class<?> clazz = o.getClass(); Field field = clazz.getDeclaredField(name); field.setAccessible(true); o = field.get(o); } return o; } /** * 得到所有定义字段 */ private void createExcelField() { this.fields = getFields(); this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList()); this.maxHeight = getRowHeight(); } /** * 获取字段注解信息 */ public List<Object[]> getFields() { List<Object[]> fields = new ArrayList<Object[]>(); List<Field> tempFields = new ArrayList<>(); tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); if (StringUtils.isNotEmpty(includeFields)) { for (Field field : tempFields) { if (ArrayUtils.contains(this.includeFields, field.getName()) || field.isAnnotationPresent(Excels.class)) { addField(fields, field); } } } else if (StringUtils.isNotEmpty(excludeFields)) { for (Field field : tempFields) { if (!ArrayUtils.contains(this.excludeFields, field.getName())) { addField(fields, field); } } } else { for (Field field : tempFields) { addField(fields, field); } } return fields; } /** * 添加字段信息 */ public void addField(List<Object[]> fields, Field field) { // 单注解 if (field.isAnnotationPresent(Excel.class)) { Excel attr = field.getAnnotation(Excel.class); if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) { fields.add(new Object[] { field, attr }); } if (Collection.class.isAssignableFrom(field.getType())) { subMethod = getSubMethod(field.getName(), clazz); ParameterizedType pt = (ParameterizedType) field.getGenericType(); Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0]; this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class); } } // 多注解 if (field.isAnnotationPresent(Excels.class)) { Excels attrs = field.getAnnotation(Excels.class); Excel[] excels = attrs.value(); for (Excel attr : excels) { if (StringUtils.isNotEmpty(includeFields)) { if (ArrayUtils.contains(this.includeFields, field.getName() + "." + attr.targetAttr()) && (attr != null && (attr.type() == Type.ALL || attr.type() == type))) { fields.add(new Object[] { field, attr }); } } else { if (!ArrayUtils.contains(this.excludeFields, field.getName() + "." + attr.targetAttr()) && (attr != null && (attr.type() == Type.ALL || attr.type() == type))) { fields.add(new Object[] { field, attr }); } } } } } /** * 根据注解获取最大行高 */ public short getRowHeight() { double maxHeight = 0; for (Object[] os : this.fields) { Excel excel = (Excel) os[1]; maxHeight = Math.max(maxHeight, excel.height()); } return (short) (maxHeight * 20); } /** * 创建一个工作簿 */ public void createWorkbook() { this.wb = new SXSSFWorkbook(500); this.sheet = wb.createSheet(); wb.setSheetName(0, sheetName); this.styles = createStyles(wb); } /** * 创建工作表 * * @param sheetNo sheet数量 * @param index 序号 */ public void createSheet(int sheetNo, int index) { // 设置工作表的名称. if (sheetNo > 1 && index > 0) { this.sheet = wb.createSheet(); this.createTitle(); wb.setSheetName(index, sheetName + index); } } /** * 获取单元格值 * * @param row 获取的行 * @param column 获取单元格列号 * @return 单元格值 */ public Object getCellValue(Row row, int column) { if (row == null) { return row; } Object val = ""; try { Cell cell = row.getCell(column); if (StringUtils.isNotNull(cell)) { if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) { val = cell.getNumericCellValue(); if (DateUtil.isCellDateFormatted(cell)) { val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换 } else { if ((Double) val % 1 != 0) { val = new BigDecimal(val.toString()); } else { val = new DecimalFormat("0").format(val); } } } else if (cell.getCellType() == CellType.STRING) { val = cell.getStringCellValue(); } else if (cell.getCellType() == CellType.BOOLEAN) { val = cell.getBooleanCellValue(); } else if (cell.getCellType() == CellType.ERROR) { val = cell.getErrorCellValue(); } } } catch (Exception e) { return val; } return val; } /** * 判断是否是空行 * * @param row 判断的行 * @return */ private boolean isRowEmpty(Row row) { if (row == null) { return true; } for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) { Cell cell = row.getCell(i); if (cell != null && cell.getCellType() != CellType.BLANK) { return false; } } return true; } /** * 获取Excel2003图片 * * @param sheet 当前sheet对象 * @param workbook 工作簿对象 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData */ public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook) { Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>(); List<HSSFPictureData> pictures = workbook.getAllPictures(); if (!pictures.isEmpty()) { for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) { HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor(); if (shape instanceof HSSFPicture) { HSSFPicture pic = (HSSFPicture) shape; int pictureIndex = pic.getPictureIndex() - 1; HSSFPictureData picData = pictures.get(pictureIndex); String picIndex = anchor.getRow1() + "_" + anchor.getCol1(); sheetIndexPicMap.put(picIndex, picData); } } return sheetIndexPicMap; } else { return sheetIndexPicMap; } } /** * 获取Excel2007图片 * * @param sheet 当前sheet对象 * @param workbook 工作簿对象 * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData */ public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook) { Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>(); for (POIXMLDocumentPart dr : sheet.getRelations()) { if (dr instanceof XSSFDrawing) { XSSFDrawing drawing = (XSSFDrawing) dr; List<XSSFShape> shapes = drawing.getShapes(); for (XSSFShape shape : shapes) { if (shape instanceof XSSFPicture) { XSSFPicture pic = (XSSFPicture) shape; XSSFClientAnchor anchor = pic.getPreferredSize(); CTMarker ctMarker = anchor.getFrom(); String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol(); sheetIndexPicMap.put(picIndex, pic.getPictureData()); } } } } return sheetIndexPicMap; } /** * 格式化不同类型的日期对象 * * @param dateFormat 日期格式 * @param val 被格式化的日期对象 * @return 格式化后的日期字符 */ public String parseDateToStr(String dateFormat, Object val) { if (val == null) { return ""; } String str; if (val instanceof Date) { str = DateUtils.parseDateToStr(dateFormat, (Date) val); } else if (val instanceof LocalDateTime) { str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val)); } else if (val instanceof LocalDate) { str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val)); } else { str = val.toString(); } return str; } /** * 是否有对象的子列表 */ public boolean isSubList() { return StringUtils.isNotNull(subFields) && subFields.size() > 0; } /** * 是否有对象的子列表,集合不为空 */ public boolean isSubListValue(T vo) { return StringUtils.isNotNull(subFields) && subFields.size() > 0 && StringUtils.isNotNull(getListCellValue(vo)) && getListCellValue(vo).size() > 0; } /** * 获取集合的值 */ public Collection<?> getListCellValue(Object obj) { Object value; try { value = subMethod.invoke(obj, new Object[] {}); } catch (Exception e) { return new ArrayList<Object>(); } return (Collection<?>) value; } /** * 获取对象的子列表方法 * * @param name 名称 * @param pojoClass 类对象 * @return 子列表方法 */ public Method getSubMethod(String name, Class<?> pojoClass) { StringBuffer getMethodName = new StringBuffer("get"); getMethodName.append(name.substring(0, 1).toUpperCase()); getMethodName.append(name.substring(1)); Method method = null; try { method = pojoClass.getMethod(getMethodName.toString(), new Class[] {}); } catch (Exception e) { log.error("获取对象异常{}", e.getMessage()); } return method; } /** * 对excel表单默认第一个索引名转换成list(EasyExcel) * * @param is 输入流 * @return 转换后集合 */ public List<T> importEasyExcel(InputStream is) throws Exception { return EasyExcel.read(is).head(clazz).sheet().doReadSync(); } /** * 对list数据源将其里面的数据导入到excel表单(EasyExcel) * * @param list 导出数据集合 * @param sheetName 工作表的名称 * @return 结果 */ public void exportEasyExcel(HttpServletResponse response, List<T> list, String sheetName) { try { EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(list); } catch (IOException e) { log.error("导出EasyExcel异常{}", e.getMessage()); } } }
2977094657/BilibiliHistoryFetcher
50,627
routers/favorite.py
import os import sqlite3 import time from datetime import datetime from typing import Optional, List, Dict, Any import requests from fastapi import APIRouter, Query from pydantic import BaseModel, Field from scripts.utils import load_config router = APIRouter() config = load_config() # 数据库路径 - 存储在output/database目录下 DB_PATH = os.path.join("output", "database", "bilibili_favorites.db") # 确保目录存在 os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) # 数据库表创建语句 CREATE_FAVORITES_FOLDER_TABLE = """ CREATE TABLE IF NOT EXISTS favorites_folder ( id INTEGER PRIMARY KEY, media_id INTEGER NOT NULL, fid INTEGER NOT NULL, mid INTEGER NOT NULL, title TEXT NOT NULL, cover TEXT, attr INTEGER, intro TEXT, ctime INTEGER, mtime INTEGER, state INTEGER, media_count INTEGER, fav_state INTEGER, like_state INTEGER, fetch_time INTEGER, UNIQUE(media_id) ); """ CREATE_FAVORITES_CREATOR_TABLE = """ CREATE TABLE IF NOT EXISTS favorites_creator ( mid INTEGER PRIMARY KEY, name TEXT NOT NULL, face TEXT, followed INTEGER, vip_type INTEGER, vip_status INTEGER, fetch_time INTEGER ); """ CREATE_FAVORITES_CONTENT_TABLE = """ CREATE TABLE IF NOT EXISTS favorites_content ( id INTEGER PRIMARY KEY, media_id INTEGER NOT NULL, content_id INTEGER NOT NULL, type INTEGER NOT NULL, title TEXT NOT NULL, cover TEXT, bvid TEXT, intro TEXT, page INTEGER, duration INTEGER, upper_mid INTEGER, attr INTEGER, ctime INTEGER, pubtime INTEGER, fav_time INTEGER, link TEXT, fetch_time INTEGER, creator_name TEXT, creator_face TEXT, bv_id TEXT, collect INTEGER, play INTEGER, danmaku INTEGER, vt INTEGER, play_switch INTEGER, reply INTEGER, view_text_1 TEXT, first_cid INTEGER, media_list_link TEXT, UNIQUE(media_id, content_id) ); """ CREATE_INDEXES = [ "CREATE INDEX IF NOT EXISTS idx_favorites_folder_mid ON favorites_folder (mid);", "CREATE INDEX IF NOT EXISTS idx_favorites_folder_mtime ON favorites_folder (mtime);", "CREATE INDEX IF NOT EXISTS idx_favorites_content_media_id ON favorites_content (media_id);", "CREATE INDEX IF NOT EXISTS idx_favorites_content_upper_mid ON favorites_content (upper_mid);", "CREATE INDEX IF NOT EXISTS idx_favorites_content_fav_time ON favorites_content (fav_time);" ] # 数据模型 class FolderMetadata(BaseModel): id: int fid: int mid: int attr: Optional[int] = None title: str cover: Optional[str] = None upper: Dict[str, Any] cover_type: Optional[int] = None cnt_info: Dict[str, int] type: Optional[int] = None intro: Optional[str] = None ctime: int mtime: int state: Optional[int] = None fav_state: Optional[int] = None like_state: Optional[int] = None media_count: int class FavoriteContent(BaseModel): id: int type: int title: str cover: Optional[str] = None bvid: Optional[str] = None bv_id: Optional[str] = None intro: Optional[str] = None page: Optional[int] = None duration: Optional[int] = None upper: Dict[str, Any] attr: Optional[int] = None cnt_info: Dict[str, int] link: Optional[str] = None ctime: Optional[int] = None pubtime: Optional[int] = None fav_time: Optional[int] = None season: Optional[Any] = None def get_headers(sessdata=None): """获取请求头""" # 如果未提供SESSDATA,尝试从配置中获取 if sessdata is None: current_config = load_config() sessdata = current_config.get("SESSDATA", "") headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", "Referer": "https://www.bilibili.com/", } # 构建完整Cookie字符串 cookies = [] if sessdata: cookies.append(f"SESSDATA={sessdata}") # 如果配置中有bili_jct,也添加到Cookie中 current_config = load_config() bili_jct = current_config.get("bili_jct", "") if bili_jct: cookies.append(f"bili_jct={bili_jct}") # 如果配置中有DedeUserID,也添加到Cookie中 dede_user_id = current_config.get("DedeUserID", "") if dede_user_id: cookies.append(f"DedeUserID={dede_user_id}") # 如果配置中有DedeUserID__ckMd5,也添加到Cookie中 dede_user_id_ckmd5 = current_config.get("DedeUserID__ckMd5", "") if dede_user_id_ckmd5: cookies.append(f"DedeUserID__ckMd5={dede_user_id_ckmd5}") # 将所有Cookie合并为一个字符串 if cookies: headers["Cookie"] = "; ".join(cookies) return headers async def get_current_user_info(sessdata=None): """获取当前登录用户信息""" try: headers = get_headers(sessdata) # 使用B站官方API获取用户信息 response = requests.get("https://api.bilibili.com/x/web-interface/nav", headers=headers) data = response.json() if data.get("code") == 0 and data.get("data", {}).get("isLogin"): user_data = data.get("data", {}) return { "uid": user_data.get("mid"), "uname": user_data.get("uname"), "level": user_data.get("level_info", {}).get("current_level") } return None except Exception as e: print(f"获取用户信息时出错: {str(e)}") return None def get_db_connection(): """获取数据库连接""" # 确保数据库目录存在 os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row # 创建表和索引 cursor = conn.cursor() cursor.execute(CREATE_FAVORITES_FOLDER_TABLE) cursor.execute(CREATE_FAVORITES_CREATOR_TABLE) cursor.execute(CREATE_FAVORITES_CONTENT_TABLE) for index_sql in CREATE_INDEXES: cursor.execute(index_sql) conn.commit() return conn def save_json_response(data, prefix, identifier): """不再保存JSON响应到文件,直接返回数据""" # 保留此函数是为了保持代码兼容性,但不再执行实际的保存操作 return None @router.get("/folder/created/list-all", summary="获取指定用户创建的所有收藏夹信息") async def get_created_folders( up_mid: Optional[int] = Query(None, description="目标用户mid,不提供则使用当前登录用户"), type: int = Query(0, description="目标内容属性,0=全部,2=视频稿件"), rid: Optional[int] = Query(None, description="目标内容id,视频稿件为avid"), sessdata: Optional[str] = Query(None, description="用户的 SESSDATA") ): """ 获取指定用户创建的所有收藏夹信息 需要用户登录才能查看私密收藏夹 """ try: # 如果未提供up_mid,获取当前登录用户的UID if up_mid is None: user_info = await get_current_user_info(sessdata) if user_info is None: return { "status": "error", "message": "未提供up_mid且未登录,无法获取收藏夹信息" } up_mid = user_info.get("uid") print(f"使用当前登录用户UID: {up_mid}") url = "https://api.bilibili.com/x/v3/fav/folder/created/list-all" params = {"up_mid": up_mid, "type": type} if rid is not None: params["rid"] = rid headers = get_headers(sessdata) response = requests.get(url, params=params, headers=headers) data = response.json() # 检查API响应 if data.get('code') != 0: return { "status": "error", "message": data.get('message', '未知错误'), "code": data.get('code') } folders_data = data.get('data', {}) # 保存到数据库 conn = get_db_connection() try: cursor = conn.cursor() timestamp = int(time.time()) # 遍历所有收藏夹 for folder in folders_data.get('list', []): # 保存创建者信息 upper = folder.get('upper', {}) if upper and 'mid' in upper: cursor.execute(""" INSERT OR REPLACE INTO favorites_creator (mid, name, face, followed, vip_type, vip_status, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( upper.get('mid'), upper.get('name', ''), upper.get('face', ''), 1 if upper.get('followed') else 0, upper.get('vip_type', 0), upper.get('vip_statue', 0), # API返回的字段名可能有误 timestamp )) # 保存收藏夹信息 cursor.execute(""" INSERT OR REPLACE INTO favorites_folder (media_id, fid, mid, title, cover, attr, intro, ctime, mtime, state, media_count, fav_state, like_state, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( folder.get('id'), folder.get('fid'), folder.get('mid'), folder.get('title', ''), folder.get('cover', ''), folder.get('attr'), folder.get('intro', ''), folder.get('ctime'), folder.get('mtime'), folder.get('state'), folder.get('media_count', 0), folder.get('fav_state', 0), folder.get('like_state', 0), timestamp )) conn.commit() except Exception as e: conn.rollback() print(f"保存用户收藏夹信息到数据库时出错: {str(e)}") finally: conn.close() return { "status": "success", "message": "获取用户创建的收藏夹列表成功", "data": folders_data } except Exception as e: print(f"获取用户创建的收藏夹列表时出错: {str(e)}") return { "status": "error", "message": f"获取用户创建的收藏夹列表失败: {str(e)}" } @router.get("/folder/collected/list", summary="查询用户收藏的视频收藏夹") async def get_collected_folders( up_mid: Optional[int] = Query(None, description="目标用户mid,不提供则使用当前登录用户"), pn: int = Query(1, description="页码"), ps: int = Query(40, description="每页项数"), keyword: Optional[str] = Query(None, description="搜索关键词"), sessdata: Optional[str] = Query(None, description="用户的 SESSDATA") ): """ 查询用户收藏的视频收藏夹 """ try: # 如果未提供up_mid,获取当前登录用户的UID if up_mid is None: user_info = await get_current_user_info(sessdata) if user_info is None: return { "status": "error", "message": "未提供up_mid且未登录,无法获取收藏夹信息" } up_mid = user_info.get("uid") print(f"使用当前登录用户UID: {up_mid}") url = "https://api.bilibili.com/x/v3/fav/folder/collected/list" params = {"up_mid": up_mid, "pn": pn, "ps": ps} if keyword: params["keyword"] = keyword headers = get_headers(sessdata) response = requests.get(url, params=params, headers=headers) data = response.json() # 检查API响应 if data.get('code') != 0: return { "status": "error", "message": data.get('message', '未知错误'), "code": data.get('code') } collected_data = data.get('data', {}) # 保存到数据库 conn = get_db_connection() try: cursor = conn.cursor() timestamp = int(time.time()) # 遍历所有收藏夹 for folder in collected_data.get('list', []): # 保存创建者信息 upper = folder.get('upper', {}) if upper and 'mid' in upper: cursor.execute(""" INSERT OR REPLACE INTO favorites_creator (mid, name, face, followed, vip_type, vip_status, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( upper.get('mid'), upper.get('name', ''), upper.get('face', ''), 1 if upper.get('followed') else 0, upper.get('vip_type', 0), upper.get('vip_statue', 0), # API返回的字段名可能有误 timestamp )) # 保存收藏夹信息 cursor.execute(""" INSERT OR REPLACE INTO favorites_folder (media_id, fid, mid, title, cover, attr, intro, ctime, mtime, state, media_count, fav_state, like_state, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( folder.get('id'), folder.get('fid'), folder.get('mid'), folder.get('title', ''), folder.get('cover', ''), folder.get('attr'), folder.get('intro', ''), folder.get('ctime'), folder.get('mtime'), folder.get('state'), folder.get('media_count', 0), folder.get('fav_state', 0), folder.get('like_state', 0), timestamp )) conn.commit() except Exception as e: conn.rollback() print(f"保存用户收藏的收藏夹信息到数据库时出错: {str(e)}") finally: conn.close() return { "status": "success", "message": "获取用户收藏的收藏夹列表成功", "data": collected_data } except Exception as e: print(f"获取用户收藏的收藏夹列表时出错: {str(e)}") return { "status": "error", "message": f"获取用户收藏的收藏夹列表失败: {str(e)}" } @router.get("/resource/infos", summary="批量获取指定收藏id的内容") async def get_resource_infos( resources: str = Query(..., description="资源列表,格式为id:type,id:type,如583785685:2,15664:12"), sessdata: Optional[str] = Query(None, description="用户的 SESSDATA") ): """ 批量获取指定收藏id的内容 type: 2=视频稿件,12=音频,... """ try: url = "https://api.bilibili.com/x/v3/fav/resource/infos" params = {"resources": resources} headers = get_headers(sessdata) response = requests.get(url, params=params, headers=headers) data = response.json() # 检查API响应 if data.get('code') != 0: return { "status": "error", "message": data.get('message', '未知错误'), "code": data.get('code') } resources_data = data.get('data', []) # 保存到数据库 conn = get_db_connection() try: cursor = conn.cursor() timestamp = int(time.time()) # 为每个资源创建一个虚拟的media_id,因为这个API不返回对应的media_id # 使用当前时间戳作为标识 virtual_media_id = timestamp # 遍历所有资源 for resource in resources_data: # 保存UP主信息 upper = resource.get('upper', {}) if upper and 'mid' in upper: cursor.execute(""" INSERT OR REPLACE INTO favorites_creator (mid, name, face, followed, vip_type, vip_status, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( upper.get('mid'), upper.get('name', ''), upper.get('face', ''), 0, # API不返回是否关注 0, # API不返回会员类型 0, # API不返回会员状态 timestamp )) # 保存资源信息 cursor.execute(""" INSERT OR REPLACE INTO favorites_content (media_id, content_id, type, title, cover, bvid, intro, page, duration, upper_mid, attr, ctime, pubtime, fav_time, link, fetch_time, creator_name, creator_face, bv_id, collect, play, danmaku, vt, play_switch, reply, view_text_1, first_cid, media_list_link) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( virtual_media_id, resource.get('id'), resource.get('type'), resource.get('title', ''), resource.get('cover', ''), resource.get('bvid', ''), resource.get('intro', ''), resource.get('page', 0), resource.get('duration', 0), upper.get('mid') if upper else 0, resource.get('attr', 0), resource.get('ctime', 0), resource.get('pubtime', 0), resource.get('fav_time', 0), resource.get('link', ''), timestamp, upper.get('name', '') if upper else '', upper.get('face', '') if upper else '', resource.get('bv_id', ''), resource.get('cnt_info', {}).get('collect', 0), resource.get('cnt_info', {}).get('play', 0), resource.get('cnt_info', {}).get('danmaku', 0), resource.get('cnt_info', {}).get('vt', 0), resource.get('cnt_info', {}).get('play_switch', 0), resource.get('cnt_info', {}).get('reply', 0), resource.get('cnt_info', {}).get('view_text_1', ''), resource.get('ugc', {}).get('first_cid', 0) if resource.get('ugc') else 0, resource.get('media_list_link', '') )) conn.commit() except Exception as e: conn.rollback() print(f"保存资源信息到数据库时出错: {str(e)}") finally: conn.close() return { "status": "success", "message": "获取资源信息成功", "data": resources_data } except Exception as e: print(f"获取资源信息时出错: {str(e)}") return { "status": "error", "message": f"获取资源信息失败: {str(e)}" } @router.get("/folder/resource/list", summary="获取收藏夹内容列表") async def get_folder_resource_list( media_id: int = Query(..., description="目标收藏夹id(完整id)"), pn: int = Query(1, description="页码"), ps: int = Query(40, description="每页项数"), keyword: Optional[str] = Query(None, description="搜索关键词"), order: str = Query("mtime", description="排序方式,mtime(收藏时间)或view(播放量)"), type: int = Query(0, description="筛选类型,0=全部,2=视频"), tid: int = Query(0, description="分区ID,0=全部"), platform: str = Query("web", description="平台标识"), sessdata: Optional[str] = Query(None, description="用户的 SESSDATA") ): """ 获取收藏夹内容列表 需要登录才能查看私密收藏夹 """ try: url = "https://api.bilibili.com/x/v3/fav/resource/list" params = { "media_id": media_id, "pn": pn, "ps": ps, "order": order, "type": type, "tid": tid, "platform": platform } if keyword: params["keyword"] = keyword headers = get_headers(sessdata) response = requests.get(url, params=params, headers=headers) data = response.json() # 检查API响应 if data.get('code') != 0: return { "status": "error", "message": data.get('message', '未知错误'), "code": data.get('code') } result_data = data.get('data', {}) # 保存到数据库 conn = get_db_connection() try: cursor = conn.cursor() timestamp = int(time.time()) # 保存收藏夹元数据 info = result_data.get('info', {}) if info and 'id' in info: # 保存创建者信息 upper = info.get('upper', {}) if upper and 'mid' in upper: cursor.execute(""" INSERT OR REPLACE INTO favorites_creator (mid, name, face, followed, vip_type, vip_status, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( upper.get('mid'), upper.get('name', ''), upper.get('face', ''), 1 if upper.get('followed') else 0, upper.get('vip_type', 0), upper.get('vip_statue', 0), # API返回的字段名可能有误 timestamp )) # 保存收藏夹信息 cursor.execute(""" INSERT OR REPLACE INTO favorites_folder (media_id, fid, mid, title, cover, attr, intro, ctime, mtime, state, media_count, fav_state, like_state, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( info.get('id'), info.get('fid'), info.get('mid'), info.get('title', ''), info.get('cover', ''), info.get('attr'), info.get('intro', ''), info.get('ctime'), info.get('mtime'), info.get('state'), info.get('media_count', 0), info.get('fav_state', 0), info.get('like_state', 0), timestamp )) # 保存收藏夹内容 for resource in result_data.get('medias', []): # 保存UP主信息 upper = resource.get('upper', {}) if upper and 'mid' in upper: cursor.execute(""" INSERT OR REPLACE INTO favorites_creator (mid, name, face, followed, vip_type, vip_status, fetch_time) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( upper.get('mid'), upper.get('name', ''), upper.get('face', ''), 0, # API不返回是否关注 0, # API不返回会员类型 0, # API不返回会员状态 timestamp )) # 保存资源信息 cursor.execute(""" INSERT OR REPLACE INTO favorites_content (media_id, content_id, type, title, cover, bvid, intro, page, duration, upper_mid, attr, ctime, pubtime, fav_time, link, fetch_time, creator_name, creator_face, bv_id, collect, play, danmaku, vt, play_switch, reply, view_text_1, first_cid, media_list_link) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( media_id, resource.get('id'), resource.get('type'), resource.get('title', ''), resource.get('cover', ''), resource.get('bvid', ''), resource.get('intro', ''), resource.get('page', 0), resource.get('duration', 0), upper.get('mid') if upper else 0, resource.get('attr', 0), resource.get('ctime', 0), resource.get('pubtime', 0), resource.get('fav_time', 0), resource.get('link', ''), timestamp, upper.get('name', '') if upper else '', upper.get('face', '') if upper else '', resource.get('bv_id', ''), resource.get('cnt_info', {}).get('collect', 0), resource.get('cnt_info', {}).get('play', 0), resource.get('cnt_info', {}).get('danmaku', 0), resource.get('cnt_info', {}).get('vt', 0), resource.get('cnt_info', {}).get('play_switch', 0), resource.get('cnt_info', {}).get('reply', 0), resource.get('cnt_info', {}).get('view_text_1', ''), resource.get('ugc', {}).get('first_cid', 0) if resource.get('ugc') else 0, resource.get('media_list_link', '') )) conn.commit() except Exception as e: conn.rollback() print(f"保存收藏夹内容到数据库时出错: {str(e)}") finally: conn.close() return { "status": "success", "message": "获取收藏夹内容成功", "data": result_data } except Exception as e: print(f"获取收藏夹内容时出错: {str(e)}") return { "status": "error", "message": f"获取收藏夹内容失败: {str(e)}" } @router.get("/list", summary="获取数据库中的收藏夹列表") async def get_favorites_list( mid: Optional[int] = Query(None, description="用户UID,不提供则返回所有收藏夹"), page: int = Query(1, description="页码"), size: int = Query(40, description="每页数量") ): """获取已保存到数据库中的收藏夹列表""" try: conn = get_db_connection() cursor = conn.cursor() # 构建查询条件 where_clause = "WHERE 1=1" params = [] if mid is not None: where_clause += " AND mid = ?" params.append(mid) # 计算总数 cursor.execute(f"SELECT COUNT(*) FROM favorites_folder {where_clause}", params) total = cursor.fetchone()[0] # 分页查询 offset = (page - 1) * size cursor.execute(f""" SELECT f.*, c.name as creator_name, c.face as creator_face FROM favorites_folder f LEFT JOIN favorites_creator c ON f.mid = c.mid {where_clause} ORDER BY f.mtime DESC LIMIT ? OFFSET ? """, params + [size, offset]) rows = cursor.fetchall() folders = [] for row in rows: folder = dict(row) folders.append(folder) conn.close() return { "status": "success", "message": "获取收藏夹列表成功", "data": { "list": folders, "total": total, "page": page, "size": size } } except Exception as e: print(f"获取收藏夹列表时出错: {str(e)}") return { "status": "error", "message": f"获取收藏夹列表失败: {str(e)}" } @router.get("/content/list", summary="获取数据库中的收藏内容列表") async def get_favorites_content( media_id: int = Query(..., description="收藏夹ID"), page: int = Query(1, description="页码"), size: int = Query(40, description="每页数量") ): """获取已保存到数据库中的收藏内容列表""" try: conn = get_db_connection() cursor = conn.cursor() # 计算总数 cursor.execute("SELECT COUNT(*) FROM favorites_content WHERE media_id = ?", (media_id,)) total = cursor.fetchone()[0] # 分页查询 offset = (page - 1) * size cursor.execute(""" SELECT c.*, cr.name as creator_name, cr.face as creator_face FROM favorites_content c LEFT JOIN favorites_creator cr ON c.upper_mid = cr.mid WHERE c.media_id = ? ORDER BY c.fav_time DESC LIMIT ? OFFSET ? """, (media_id, size, offset)) rows = cursor.fetchall() contents = [] for row in rows: content = dict(row) contents.append(content) conn.close() return { "status": "success", "message": "获取收藏内容列表成功", "data": { "list": contents, "total": total, "page": page, "size": size } } except Exception as e: print(f"获取收藏内容列表时出错: {str(e)}") return { "status": "error", "message": f"获取收藏内容列表失败: {str(e)}" } # 添加请求体数据模型 class FavoriteResourceRequest(BaseModel): rid: int = Field(..., description="稿件avid") add_media_ids: Optional[str] = Field(None, description="需要加入的收藏夹ID,多个用逗号分隔") del_media_ids: Optional[str] = Field(None, description="需要取消的收藏夹ID,多个用逗号分隔") sessdata: Optional[str] = Field(None, description="用户的SESSDATA") @router.post("/resource/deal", summary="收藏或取消收藏单个视频") async def favorite_resource( request: Optional[FavoriteResourceRequest] = None, rid: Optional[int] = Query(None, description="稿件avid"), add_media_ids: Optional[str] = Query(None, description="需要加入的收藏夹ID,多个用逗号分隔"), del_media_ids: Optional[str] = Query(None, description="需要取消的收藏夹ID,多个用逗号分隔"), sessdata: Optional[str] = Query(None, description="用户的SESSDATA") ): """ 收藏或取消收藏单个视频到指定收藏夹 可以通过查询参数或请求体提交参数,支持两种方式 - rid: 视频的av号(不含av前缀) - add_media_ids: 需要添加到的收藏夹ID,多个用逗号分隔 - del_media_ids: 需要从中取消的收藏夹ID,多个用逗号分隔 - sessdata: 用户的SESSDATA,不提供则从配置文件读取 需要用户登录才能操作 """ try: # 优先使用请求体中的参数 if request: rid = request.rid add_media_ids = request.add_media_ids del_media_ids = request.del_media_ids if request.sessdata: sessdata = request.sessdata # 检查必填参数 if rid is None: return { "status": "error", "message": "缺少必填参数: rid (稿件avid)" } if not add_media_ids and not del_media_ids: return { "status": "error", "message": "需要提供至少一个收藏夹ID (add_media_ids 或 del_media_ids)" } # 获取请求头和Cookie headers = get_headers(sessdata) # 从配置或Cookie中获取bili_jct (CSRF Token) current_config = load_config() bili_jct = current_config.get("bili_jct", "") if not bili_jct: return { "status": "error", "message": "缺少CSRF Token (bili_jct),请先使用QR码登录并确保已正确获取bili_jct" } # 准备请求参数 data = { "rid": rid, "type": 2, # 固定为2,表示视频稿件 "csrf": bili_jct, "platform": "web", "eab_x": 1, "ramval": 0, "ga": 1, "gaia_source": "web_normal" } if add_media_ids: data["add_media_ids"] = add_media_ids if del_media_ids: data["del_media_ids"] = del_media_ids # 发起请求 url = "https://api.bilibili.com/x/v3/fav/resource/deal" response = requests.post(url, data=data, headers=headers) result = response.json() # 检查响应 if result.get('code') != 0: return { "status": "error", "message": result.get('message', '未知错误'), "code": result.get('code') } return { "status": "success", "message": "操作成功", "data": result.get('data', {}) } except Exception as e: print(f"收藏操作失败: {str(e)}") return { "status": "error", "message": f"收藏操作失败: {str(e)}" } # 添加批量请求体数据模型 class BatchFavoriteResourceRequest(BaseModel): rids: str = Field(..., description="稿件avid列表,多个用逗号分隔") add_media_ids: Optional[str] = Field(None, description="需要加入的收藏夹ID,多个用逗号分隔") del_media_ids: Optional[str] = Field(None, description="需要取消的收藏夹ID,多个用逗号分隔") sessdata: Optional[str] = Field(None, description="用户的SESSDATA") @router.post("/resource/batch-deal", summary="批量收藏或取消收藏视频") async def batch_favorite_resource( request: Optional[BatchFavoriteResourceRequest] = None, rids: Optional[str] = Query(None, description="稿件avid列表,多个用逗号分隔"), add_media_ids: Optional[str] = Query(None, description="需要加入的收藏夹ID,多个用逗号分隔"), del_media_ids: Optional[str] = Query(None, description="需要取消的收藏夹ID,多个用逗号分隔"), sessdata: Optional[str] = Query(None, description="用户的SESSDATA") ): """ 批量收藏或取消收藏多个视频到指定收藏夹 可以通过查询参数或请求体提交参数,支持两种方式 - rids: 视频的av号列表(不含av前缀),多个用逗号分隔 - add_media_ids: 需要添加到的收藏夹ID,多个用逗号分隔 - del_media_ids: 需要从中取消的收藏夹ID,多个用逗号分隔 - sessdata: 用户的SESSDATA,不提供则从配置文件读取 需要用户登录才能操作 """ try: # 优先使用请求体中的参数 if request: rids = request.rids add_media_ids = request.add_media_ids del_media_ids = request.del_media_ids if request.sessdata: sessdata = request.sessdata # 检查必填参数 if not rids: return { "status": "error", "message": "缺少必填参数: rids (稿件avid列表)" } if not add_media_ids and not del_media_ids: return { "status": "error", "message": "需要提供至少一个收藏夹ID (add_media_ids 或 del_media_ids)" } # 处理输入参数 try: rid_list = [int(rid.strip()) for rid in rids.split(',') if rid.strip()] except ValueError: return { "status": "error", "message": "无效的rids参数格式,请使用逗号分隔的整数列表" } if not rid_list: return { "status": "error", "message": "请提供至少一个有效的视频ID" } # 获取请求头和Cookie headers = get_headers(sessdata) # 从配置或Cookie中获取bili_jct (CSRF Token) current_config = load_config() bili_jct = current_config.get("bili_jct", "") if not bili_jct: return { "status": "error", "message": "缺少CSRF Token (bili_jct),请先使用QR码登录并确保已正确获取bili_jct" } # 批量处理每个视频 results = [] for rid in rid_list: # 准备请求参数 data = { "rid": rid, "type": 2, # 固定为2,表示视频稿件 "csrf": bili_jct, "platform": "web", "eab_x": 1, "ramval": 0, "ga": 1, "gaia_source": "web_normal" } if add_media_ids: data["add_media_ids"] = add_media_ids if del_media_ids: data["del_media_ids"] = del_media_ids # 发起请求 url = "https://api.bilibili.com/x/v3/fav/resource/deal" response = requests.post(url, data=data, headers=headers) result = response.json() # 添加结果 results.append({ "rid": rid, "code": result.get('code'), "message": result.get('message'), "data": result.get('data') }) # 添加短暂延迟,防止频繁请求 time.sleep(0.5) # 检查是否全部成功 all_success = all(result["code"] == 0 for result in results) return { "status": "success" if all_success else "partial_success", "message": "所有操作成功完成" if all_success else "部分操作成功", "results": results } except Exception as e: print(f"批量收藏操作失败: {str(e)}") return { "status": "error", "message": f"批量收藏操作失败: {str(e)}" } class CheckFavoritesRequest(BaseModel): oids: List[int] = Field(..., description="视频的av号列表") sessdata: Optional[str] = Field(None, description="用户的SESSDATA") @router.post("/check/batch", summary="批量检查视频是否已被收藏", tags=["收藏夹管理"]) async def check_favorites_batch(request: CheckFavoritesRequest): """ 批量检查多个视频是否已被收藏 - oids: 视频的av号列表 - sessdata: 用户的SESSDATA,不提供则从配置文件读取 响应格式: ```json { "status": "success", "data": { "results": [ { "oid": 123456, "is_favorited": true, "favorite_folders": [ {"media_id": 1234567, "title": "收藏夹名称"} ] } ] } } ``` """ try: # 获取请求参数 oids = request.oids sessdata = request.sessdata if not oids: return { "status": "error", "message": "请提供至少一个视频av号" } # 查询B站API获取用户的收藏夹列表 user_info = await get_current_user_info(sessdata) if not user_info: return { "status": "error", "message": "无法获取用户信息,请确保已登录" } # 获取本地数据库中的相关收藏信息 conn = get_db_connection() cursor = conn.cursor() results = [] # 遍历每个视频av号 for oid in oids: # 查询本地数据库中是否收藏了该视频 cursor.execute(""" SELECT fc.media_id, ff.title FROM favorites_content fc JOIN favorites_folder ff ON fc.media_id = ff.media_id WHERE fc.content_id = ? AND fc.type = 2 """, (oid,)) rows = cursor.fetchall() is_favorited = len(rows) > 0 favorite_folders = [] if is_favorited: for row in rows: favorite_folders.append({ "media_id": row[0], "title": row[1] }) results.append({ "oid": oid, "is_favorited": is_favorited, "favorite_folders": favorite_folders }) conn.close() return { "status": "success", "data": { "results": results } } except Exception as e: print(f"批量检查收藏状态时出错: {str(e)}") return { "status": "error", "message": f"批量检查收藏状态失败: {str(e)}" } @router.get("/check", summary="检查单个视频是否已被收藏", tags=["收藏夹管理"]) async def check_favorite( oid: int = Query(..., description="视频的av号"), sessdata: Optional[str] = Query(None, description="用户的SESSDATA") ): """ 检查单个视频是否已被收藏 - oid: 视频的av号 - sessdata: 用户的SESSDATA,不提供则从配置文件读取 响应格式: ```json { "status": "success", "data": { "oid": 123456, "is_favorited": true, "favorite_folders": [ {"media_id": 1234567, "title": "收藏夹名称"} ] } } ``` """ try: # 查询本地数据库中是否收藏了该视频 conn = get_db_connection() cursor = conn.cursor() cursor.execute(""" SELECT fc.media_id, ff.title FROM favorites_content fc JOIN favorites_folder ff ON fc.media_id = ff.media_id WHERE fc.content_id = ? AND fc.type = 2 """, (oid,)) rows = cursor.fetchall() is_favorited = len(rows) > 0 favorite_folders = [] if is_favorited: for row in rows: favorite_folders.append({ "media_id": row[0], "title": row[1] }) conn.close() return { "status": "success", "data": { "oid": oid, "is_favorited": is_favorited, "favorite_folders": favorite_folders } } except Exception as e: print(f"检查收藏状态时出错: {str(e)}") return { "status": "error", "message": f"检查收藏状态失败: {str(e)}" } class BatchLocalFavoriteRequest(BaseModel): rids: str = Field(..., description="稿件avid列表,多个用逗号分隔") add_media_ids: Optional[str] = Field(None, description="需要加入的收藏夹ID,多个用逗号分隔") del_media_ids: Optional[str] = Field(None, description="需要取消的收藏夹ID,多个用逗号分隔") operation_type: str = Field("sync", description="操作类型,sync=同步到远程,local=仅本地操作") @router.post("/resource/local-batch-deal", summary="本地批量收藏或取消收藏视频") async def local_batch_favorite_resource( request: BatchLocalFavoriteRequest, sessdata: Optional[str] = Query(None, description="用户的SESSDATA") ): """ 在本地数据库中批量收藏或取消收藏多个视频 - rids: 视频的av号列表(不含av前缀),多个用逗号分隔 - add_media_ids: 需要添加到的收藏夹ID,多个用逗号分隔 - del_media_ids: 需要从中取消的收藏夹ID,多个用逗号分隔 - operation_type: 操作类型,sync=同步到远程,local=仅本地操作 此接口用于本地数据库和远程B站的收藏同步管理 """ try: # 获取请求参数 rids = request.rids add_media_ids = request.add_media_ids del_media_ids = request.del_media_ids operation_type = request.operation_type # 检查必填参数 if not rids: return { "status": "error", "message": "缺少必填参数: rids (稿件avid列表)" } if not add_media_ids and not del_media_ids: return { "status": "error", "message": "需要提供至少一个收藏夹ID (add_media_ids 或 del_media_ids)" } # 处理输入参数 try: rid_list = [int(rid.strip()) for rid in rids.split(',') if rid.strip()] except ValueError: return { "status": "error", "message": "无效的rids参数格式,请使用逗号分隔的整数列表" } if not rid_list: return { "status": "error", "message": "请提供至少一个有效的视频ID" } # 解析收藏夹ID add_folders = [] if add_media_ids: add_folders = [int(mid.strip()) for mid in add_media_ids.split(',') if mid.strip()] del_folders = [] if del_media_ids: del_folders = [int(mid.strip()) for mid in del_media_ids.split(',') if mid.strip()] # 连接数据库 conn = get_db_connection() cursor = conn.cursor() # 获取当前时间戳 timestamp = int(datetime.now().timestamp()) # 获取用户信息 user_info = await get_current_user_info(sessdata) user_mid = user_info.get("uid") if user_info else 0 results = [] # 同步到远程B站 if operation_type == "sync": # 复用现有的批量收藏接口 batch_request = BatchFavoriteResourceRequest( rids=rids, add_media_ids=add_media_ids, del_media_ids=del_media_ids, sessdata=sessdata ) remote_result = await batch_favorite_resource(request=batch_request) # 如果远程操作失败,则只返回远程结果不进行本地操作 if remote_result.get("status") != "success" and remote_result.get("status") != "partial_success": return remote_result # 遍历每个视频,处理本地数据库操作 for rid in rid_list: result_item = {"rid": rid, "code": 0, "message": "success", "data": {}} try: # 处理取消收藏 (删除记录) if del_folders: for media_id in del_folders: cursor.execute(""" DELETE FROM favorites_content WHERE content_id = ? AND media_id = ? AND type = 2 """, (rid, media_id)) if cursor.rowcount > 0: result_item["data"]["removed_folders"] = result_item.get("data", {}).get("removed_folders", 0) + 1 # 处理添加收藏 (添加记录) if add_folders: for media_id in add_folders: # 检查收藏夹是否存在 cursor.execute("SELECT * FROM favorites_folder WHERE media_id = ?", (media_id,)) folder = cursor.fetchone() if not folder: # 收藏夹不存在,跳过 result_item["data"]["folder_not_found"] = result_item.get("data", {}).get("folder_not_found", 0) + 1 continue # 检查视频是否已在收藏夹中 cursor.execute(""" SELECT * FROM favorites_content WHERE content_id = ? AND media_id = ? AND type = 2 """, (rid, media_id)) if cursor.fetchone(): # 已收藏,跳过 result_item["data"]["already_favorited"] = result_item.get("data", {}).get("already_favorited", 0) + 1 continue # 获取视频信息 (如标题等) - 尝试从数据库中其他收藏夹获取 cursor.execute(""" SELECT * FROM favorites_content WHERE content_id = ? AND type = 2 """, (rid,)) existing_content = cursor.fetchone() # 如果在数据库中找到了视频信息,使用这些信息 if existing_content: title = existing_content["title"] cover = existing_content["cover"] bvid = existing_content["bvid"] intro = existing_content["intro"] page = existing_content["page"] duration = existing_content["duration"] upper_mid = existing_content["upper_mid"] attr = existing_content["attr"] ctime = existing_content["ctime"] pubtime = existing_content["pubtime"] link = existing_content["link"] else: # 未找到视频信息,使用默认值 title = f"视频 av{rid}" cover = "" bvid = "" intro = "" page = 1 duration = 0 upper_mid = 0 attr = 0 ctime = timestamp pubtime = timestamp link = f"https://www.bilibili.com/video/av{rid}" # 添加收藏 cursor.execute(""" INSERT OR REPLACE INTO favorites_content (media_id, content_id, type, title, cover, bvid, intro, page, duration, upper_mid, attr, ctime, pubtime, fav_time, link, fetch_time, creator_name, creator_face, bv_id, collect, play, danmaku, vt, play_switch, reply, view_text_1, first_cid, media_list_link) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( media_id, rid, 2, # 固定为2,表示视频稿件 title, cover, bvid, intro, page, duration, upper_mid, attr, ctime, pubtime, timestamp, # 当前时间作为收藏时间 link, timestamp, existing_content["creator_name"] if existing_content and "creator_name" in existing_content else "", existing_content["creator_face"] if existing_content and "creator_face" in existing_content else "", existing_content["bv_id"] if existing_content and "bv_id" in existing_content else "", existing_content["collect"] if existing_content and "collect" in existing_content else 0, existing_content["play"] if existing_content and "play" in existing_content else 0, existing_content["danmaku"] if existing_content and "danmaku" in existing_content else 0, existing_content["vt"] if existing_content and "vt" in existing_content else 0, existing_content["play_switch"] if existing_content and "play_switch" in existing_content else 0, existing_content["reply"] if existing_content and "reply" in existing_content else 0, existing_content["view_text_1"] if existing_content and "view_text_1" in existing_content else "", existing_content["first_cid"] if existing_content and "first_cid" in existing_content else 0, existing_content["media_list_link"] if existing_content and "media_list_link" in existing_content else "" )) result_item["data"]["added_folders"] = result_item.get("data", {}).get("added_folders", 0) + 1 # 添加成功消息 result_item["data"]["prompt"] = True result_item["data"]["toast_msg"] = "本地收藏更新成功" results.append(result_item) except Exception as e: print(f"处理视频 {rid} 时出错: {str(e)}") result_item["code"] = -1 result_item["message"] = f"本地操作失败: {str(e)}" results.append(result_item) # 提交事务 conn.commit() conn.close() # 检查是否全部成功 all_success = all(result["code"] == 0 for result in results) return { "status": "success" if all_success else "partial_success", "message": "所有本地操作成功完成" if all_success else "部分本地操作成功", "operation_type": operation_type, "results": results } except Exception as e: print(f"本地批量收藏操作失败: {str(e)}") return { "status": "error", "message": f"本地批量收藏操作失败: {str(e)}" }
281677160/openwrt-package
2,312
luci-app-homeproxy/root/etc/config/homeproxy
config homeproxy 'infra' option __warning 'DO NOT EDIT THIS SECTION, OR YOU ARE ON YOUR OWN!' option common_port '22,53,80,143,443,465,587,853,873,993,995,5222,8080,8443,9418' option mixed_port '5330' option redirect_port '5331' option tproxy_port '5332' option dns_port '5333' option ntp_server 'time.apple.com' option sniff_override '1' option udp_timeout '' option tun_name 'singtun0' option tun_addr4 '172.19.0.1/30' option tun_addr6 'fdfe:dcba:9876::1/126' option tun_mtu '9000' option table_mark '100' option self_mark '100' option tproxy_mark '101' option tun_mark '102' config homeproxy 'migration' option crontab '1' config homeproxy 'config' option main_node 'nil' option main_udp_node 'same' option dns_server '8.8.8.8' option china_dns_server '223.5.5.5' option routing_mode 'bypass_mainland_china' option routing_port 'common' option proxy_mode 'redirect_tproxy' option ipv6_support '1' option github_token '' option log_level 'warn' config homeproxy 'control' option lan_proxy_mode 'disabled' list wan_proxy_ipv4_ips '91.105.192.0/23' list wan_proxy_ipv4_ips '91.108.4.0/22' list wan_proxy_ipv4_ips '91.108.8.0/22' list wan_proxy_ipv4_ips '91.108.16.0/22' list wan_proxy_ipv4_ips '91.108.12.0/22' list wan_proxy_ipv4_ips '91.108.20.0/22' list wan_proxy_ipv4_ips '91.108.56.0/22' list wan_proxy_ipv4_ips '149.154.160.0/20' list wan_proxy_ipv4_ips '185.76.151.0/24' list wan_proxy_ipv4_ips '203.208.50.66/32' list wan_proxy_ipv6_ips '2001:67c:4e8::/48' list wan_proxy_ipv6_ips '2001:b28:f23c::/48' list wan_proxy_ipv6_ips '2001:b28:f23d::/48' list wan_proxy_ipv6_ips '2001:b28:f23f::/48' list wan_proxy_ipv6_ips '2a0a:f280::/32' config homeproxy 'routing' option sniff_override '1' option default_outbound 'direct-out' option default_outbound_dns 'default-dns' config homeproxy 'dns' option dns_strategy 'prefer_ipv4' option default_server 'local-dns' option disable_cache '0' option disable_cache_expire '0' config homeproxy 'subscription' option auto_update '0' option allow_insecure '0' option packet_encoding 'xudp' option update_via_proxy '0' option filter_nodes 'blacklist' list filter_keywords '重置|到期|过期|剩余|套餐' list filter_keywords 'Expiration|Remaining' config homeproxy 'server' option enabled '0' option log_level 'warn'
2977094657/BilibiliHistoryFetcher
23,625
routers/scheduler.py
import asyncio import os import yaml from fastapi import APIRouter, HTTPException, Depends, Request, Query from loguru import logger from scripts.scheduler_db_enhanced import EnhancedSchedulerDB from scripts.scheduler_manager import SchedulerManager from scripts.utils import get_config_path as utils_get_config_path, setup_logger # 确保日志系统已初始化 setup_logger() router = APIRouter() # 获取调度器实例 def get_scheduler(): return SchedulerManager.get_instance() # 获取调度器数据库实例 def get_scheduler_db(): return EnhancedSchedulerDB.get_instance() def get_config_path(): """获取配置文件路径""" # 使用utils中的公共函数来保持一致性 return utils_get_config_path('scheduler_config.yaml') def save_config(config): """保存配置到文件""" config_path = get_config_path() os.makedirs(os.path.dirname(config_path), exist_ok=True) with open(config_path, 'w', encoding='utf-8') as f: yaml.dump(config, f, allow_unicode=True, sort_keys=False) return True @router.get("/tasks", summary="获取任务信息") async def get_tasks( task_id: str = None, include_subtasks: bool = True, detail_level: str = "basic", db: EnhancedSchedulerDB = Depends(get_scheduler_db) ): """ 获取任务信息 - 不指定task_id时返回所有任务 - 指定task_id时返回特定任务详情 - include_subtasks控制是否包含子任务信息 - detail_level控制返回信息详细程度 """ try: tasks = [] if task_id: if db.is_main_task(task_id): task_data = db.get_main_task_by_id(task_id) if not task_data: return {"status": "error", "message": f"任务 {task_id} 不存在"} if include_subtasks: task_data['sub_tasks'] = db.get_sub_tasks(task_id) tasks.append(_build_task_info(task_data)) else: task_data = db.get_subtask_by_id(task_id) if not task_data: return {"status": "error", "message": f"任务 {task_id} 不存在"} tasks.append(_build_task_info(task_data)) else: main_tasks = db.get_all_main_tasks() for task_data in main_tasks: if include_subtasks: task_data['sub_tasks'] = db.get_sub_tasks(task_data['task_id']) tasks.append(_build_task_info(task_data)) return { "status": "success", "message": "获取任务信息成功", "tasks": tasks } except Exception as e: logger.error(f"获取任务信息失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"获取任务信息失败: {str(e)}" } def _build_task_info(task_data): """构建任务信息""" # 从配置文件中获取调度类型 config_path = get_config_path() schedule_type = 'daily' # 默认值 if os.path.exists(config_path): try: with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) task_id = task_data.get('task_id') if task_id and 'tasks' in config and task_id in config['tasks']: schedule_type = config['tasks'][task_id].get('schedule', {}).get('type', 'daily') except Exception as e: logger.error(f"读取配置文件失败: {str(e)}") config = { "name": task_data.get('name', ''), "endpoint": task_data.get('endpoint', ''), "method": task_data.get('method', 'GET'), "params": task_data.get('params', {}), "schedule_type": task_data.get('schedule_type') or schedule_type, "schedule_time": task_data.get('schedule_time'), "schedule_delay": task_data.get('schedule_delay'), "interval_value": task_data.get('interval_value'), "interval_unit": task_data.get('interval_unit'), "enabled": bool(task_data.get('enabled', True)), "priority": task_data.get('priority', 0), "tags": task_data.get('tags') or [] } # 安全处理数值类型 avg_duration = task_data.get('avg_duration') if avg_duration is not None: try: avg_duration = float(avg_duration) except (TypeError, ValueError): avg_duration = 0.0 else: avg_duration = 0.0 execution = { "last_run": task_data.get('last_run_time'), "next_run": task_data.get('next_run_time'), "status": task_data.get('last_status') or 'pending', "success_rate": task_data.get('success_rate', 0.0), "avg_duration": avg_duration, "total_runs": int(task_data.get('total_runs') or 0), "success_runs": int(task_data.get('success_runs') or 0), "fail_runs": int(task_data.get('fail_runs') or 0), "last_error": task_data.get('last_error') } task_type = task_data.get('task_type') if not task_type: task_type = 'sub' if task_data.get('parent_id') else 'main' result = { "task_id": task_data['task_id'], "task_type": task_type, "config": config, "execution": execution, "parent_id": task_data.get('parent_id'), "sub_tasks": [_build_subtask_info(sub_task) for sub_task in task_data.get('sub_tasks', [])] if task_data.get('sub_tasks') else None, "created_at": task_data.get('created_at'), "last_modified": task_data.get('last_modified') } # 添加依赖信息 if task_data.get('depends_on'): result['depends_on'] = task_data['depends_on'] return result def _build_subtask_info(task_data): """构建子任务信息""" task_info = _build_task_info(task_data) return { "task_id": task_info["task_id"], "config": task_info["config"], "execution": task_info["execution"], "sequence_number": task_data.get('sequence_number', 0), "created_at": task_data.get('created_at'), "last_modified": task_data.get('last_modified') } @router.post("/tasks", summary="创建新任务") async def create_task( task_data: dict, db: EnhancedSchedulerDB = Depends(get_scheduler_db), scheduler: SchedulerManager = Depends(get_scheduler) ): """ 创建新任务 - 支持创建主任务和子任务 - 子任务需要指定parent_id和sequence_number """ try: task_id = task_data.get('task_id') task_type = task_data.get('task_type', 'main') if task_type == "main": success = scheduler.add_main_task(task_id, task_data.get('config', {})) else: parent_id = task_data.get('parent_id') if not parent_id: return {"status": "error", "message": "创建子任务时必须指定parent_id"} success = scheduler.add_sub_task(parent_id, task_id, task_data.get('config', {})) if success: # 重新加载调度器配置 scheduler.reload_scheduler() task_info = None if task_type == "main": task_info = _build_task_info(db.get_main_task_by_id(task_id)) else: task_info = _build_task_info(db.get_subtask_by_id(task_id)) return { "status": "success", "message": f"成功创建{task_type}任务", "task_id": task_id, "task_info": task_info } return { "status": "error", "message": "创建任务失败", "task_id": task_id } except Exception as e: logger.error(f"创建任务失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"创建任务失败: {str(e)}" } @router.put("/tasks/{task_id}", summary="更新任务配置") async def update_task( task_id: str, task_data: dict, db: EnhancedSchedulerDB = Depends(get_scheduler_db), scheduler: SchedulerManager = Depends(get_scheduler) ): """ 更新任务配置 - 支持更新主任务和子任务 - 支持更新任务配置、状态、优先级、标签等 - 支持更新子任务执行顺序 """ try: if db.is_main_task(task_id): success = db.update_main_task(task_id, task_data) else: success = db.update_subtask(task_id, task_data) if success: # 重新加载调度器配置 scheduler.reload_scheduler() task_info = None if db.is_main_task(task_id): task_info = _build_task_info(db.get_main_task_by_id(task_id)) else: task_info = _build_task_info(db.get_subtask_by_id(task_id)) return { "status": "success", "message": "任务更新成功", "task_id": task_id, "task_info": task_info } else: return { "status": "error", "message": "任务更新失败", "task_id": task_id } except Exception as e: logger.error(f"更新任务失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"更新任务失败: {str(e)}" } @router.delete("/tasks/{task_id}", summary="删除任务") async def delete_task( task_id: str, db: EnhancedSchedulerDB = Depends(get_scheduler_db) ): """ 删除任务 - 支持删除主任务和子任务 - 删除主任务时会自动删除其所有子任务 """ try: if db.is_main_task(task_id): success = db.delete_main_task(task_id) else: success = db.delete_subtask(task_id) if success: return { "status": "success", "message": "任务删除成功", "task_id": task_id } else: return { "status": "error", "message": "任务删除失败", "task_id": task_id } except Exception as e: logger.error(f"删除任务失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"删除任务失败: {str(e)}" } @router.post("/tasks/{task_id}/execute", summary="执行任务") async def execute_task( task_id: str, execute_params: dict = None, scheduler: SchedulerManager = Depends(get_scheduler) ): """ 执行任务 - 支持执行主任务和子任务 - 可控制是否执行子任务 - 可选择是否等待任务完成 """ try: wait_for_completion = execute_params.get('wait_for_completion', False) if execute_params else False if wait_for_completion: success = await scheduler.execute_task(task_id) else: asyncio.create_task(scheduler.execute_task(task_id)) success = True if success: return { "status": "success", "message": "任务执行已启动", "task_id": task_id } return { "status": "error", "message": "任务执行失败", "task_id": task_id } except Exception as e: logger.error(f"执行任务失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"执行任务失败: {str(e)}" } @router.get("/tasks/history", summary="查询任务执行历史") async def get_task_history( task_id: str = None, include_subtasks: bool = True, status: str = None, start_date: str = None, end_date: str = None, page: int = 1, page_size: int = 20, db: EnhancedSchedulerDB = Depends(get_scheduler_db) ): """ 查询任务执行历史 - 支持查询主任务和子任务历史 - 支持按时间范围和状态过滤 - 支持分页查询 """ try: conditions = { 'status': status, 'start_date': start_date, 'end_date': end_date } if task_id: # 无论是主任务还是子任务,都使用 get_task_execution_history_enhanced result = db.get_task_execution_history_enhanced( task_id, include_subtasks=include_subtasks if db.is_main_task(task_id) else False, conditions=conditions, page=page, page_size=page_size ) else: result = db.get_recent_task_executions_enhanced( include_subtasks=include_subtasks, conditions=conditions, page=page, page_size=page_size ) return { "status": "success", "message": "获取任务执行历史成功", "history": result['records'], "total_count": result['total'], "page": page, "page_size": page_size } except Exception as e: logger.error(f"获取任务执行历史失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"获取任务执行历史失败: {str(e)}" } @router.get("/available-endpoints", summary="获取可用API端点") async def get_available_endpoints(request: Request): """ 获取所有可用的API端点信息 - 返回系统中所有已注册的API端点 - 包含路径、方法、描述等信息 - 不包含系统内置的文档相关端点 """ try: # 需要过滤的内置端点路径 builtin_paths = { '/openapi.json', '/docs', '/docs/oauth2-redirect', '/redoc', '/redoc-models.js' } endpoints = [] for route in request.app.routes: if hasattr(route, 'methods'): # 跳过内置的文档相关端点 if route.path in builtin_paths: continue # 跳过HEAD方法(通常是自动生成的) methods = [m for m in route.methods if m != 'HEAD'] if not methods: continue endpoints.append({ "path": route.path, "method": methods[0], "summary": getattr(route, 'summary', None), "tags": getattr(route, 'tags', []), "operationId": route.name if hasattr(route, 'name') else None }) # 按路径排序,使输出更有序 endpoints.sort(key=lambda x: x['path']) return { "status": "success", "message": f"获取API端点列表成功,共 {len(endpoints)} 个端点", "total": len(endpoints), "endpoints": endpoints } except Exception as e: logger.error(f"获取API端点列表失败: {str(e)}", exc_info=True) return { "status": "error", "message": f"获取API端点列表失败: {str(e)}" } @router.post("/tasks/{task_id}/subtasks", summary="添加子任务") async def add_sub_task( task_id: str, sub_task_data: dict, scheduler: SchedulerManager = Depends(get_scheduler), db: EnhancedSchedulerDB = Depends(get_scheduler_db) ): """ 为主任务添加子任务 - 需要指定子任务名称、执行顺序、API端点等信息 - 自动设置子任务为启用状态 - 从配置文件读取调度类型,默认为'daily' """ try: if task_id not in scheduler.tasks: return {"status": "error", "message": f"主任务 {task_id} 不存在"} if not db.is_main_task(task_id): return {"status": "error", "message": f"任务 {task_id} 不是主任务"} # 从配置文件获取调度类型 config_path = get_config_path() schedule_type = 'daily' # 默认值 if os.path.exists(config_path): try: with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) sub_task_id = sub_task_data.get('task_id') if sub_task_id and 'tasks' in config and sub_task_id in config['tasks']: schedule_type = config['tasks'][sub_task_id].get('schedule', {}).get('type', 'daily') except Exception as e: logger.error(f"读取配置文件失败: {str(e)}") sub_task_config = { "task_id": sub_task_data.get('task_id'), "name": sub_task_data.get('name'), "sequence_number": sub_task_data.get('sequence_number'), "endpoint": sub_task_data.get('endpoint'), "method": sub_task_data.get('method', 'GET'), "params": sub_task_data.get('params'), "enabled": True, "task_type": "sub", "schedule_type": sub_task_data.get('schedule_type') or schedule_type, "depends_on": sub_task_data.get('depends_on') # 添加依赖关系 } # 获取子任务ID sub_task_id = sub_task_data.get('task_id') if not sub_task_id: return {"status": "error", "message": "子任务ID不能为空"} result = scheduler.add_sub_task(task_id, sub_task_id, sub_task_config) if not result: return {"status": "error", "message": "添加子任务失败"} # 重新加载调度器配置 scheduler.reload_scheduler() return { "status": "success", "message": f"成功为主任务 {task_id} 添加子任务", "task_id": task_id } except Exception as e: logger.error(f"添加子任务失败: {str(e)}") return {"status": "error", "message": f"添加子任务失败: {str(e)}"} @router.get("/tasks/{task_id}/subtasks", summary="获取子任务列表") async def get_sub_tasks( task_id: str, db: EnhancedSchedulerDB = Depends(get_scheduler_db), scheduler: SchedulerManager = Depends(get_scheduler) ): """ 获取主任务的所有子任务 - 返回子任务的详细信息,包括调度类型 - 包含执行状态、成功率等统计数据 - 按执行顺序排序 """ try: # 检查主任务是否存在 if task_id not in scheduler.tasks: raise HTTPException(status_code=404, detail=f"主任务 {task_id} 不存在") # 检查是否为主任务 if not db.is_main_task(task_id): raise HTTPException(status_code=400, detail=f"任务 {task_id} 不是主任务") # 获取子任务列表 sub_tasks = db.get_sub_tasks(task_id) # 处理每个子任务的状态 processed_sub_tasks = [] for sub_task in sub_tasks: sub_task_id = sub_task['task_id'] # 获取子任务状态 status = '未执行' if sub_task.get('last_run_time'): status = '成功' if sub_task.get('last_status') == 'success' else '失败' # 计算成功率 total_runs = sub_task.get('total_runs', 0) success_runs = sub_task.get('success_runs', 0) success_rate = round(success_runs / total_runs * 100, 2) if total_runs > 0 else None processed_sub_task = { 'task_id': sub_task_id, 'name': sub_task.get('name', sub_task_id), 'sequence_number': sub_task.get('sequence_number', 0), 'endpoint': sub_task.get('endpoint'), 'method': sub_task.get('method', 'GET'), 'params': sub_task.get('params'), 'status': status, 'enabled': bool(sub_task.get('enabled', True)), 'success_rate': success_rate, 'total_runs': total_runs, 'success_runs': success_runs, 'fail_runs': sub_task.get('fail_runs', 0), 'last_error': sub_task.get('last_error'), 'tags': sub_task.get('tags', []), 'task_type': 'sub', 'schedule_type': sub_task.get('schedule_type', 'daily') } processed_sub_tasks.append(processed_sub_task) # 按序号排序 processed_sub_tasks.sort(key=lambda x: x['sequence_number']) return { "status": "success", "message": f"成功获取主任务 {task_id} 的子任务列表", "sub_tasks": processed_sub_tasks } except HTTPException: raise except Exception as e: logger.error(f"获取子任务列表失败: {str(e)}") raise HTTPException(status_code=500, detail=f"获取子任务列表失败: {str(e)}") @router.delete("/tasks/{task_id}/subtasks/{sub_task_id}", summary="删除子任务") async def delete_sub_task( task_id: str, sub_task_id: str, db: EnhancedSchedulerDB = Depends(get_scheduler_db), scheduler: SchedulerManager = Depends(get_scheduler) ): """ 删除子任务 - 从主任务中移除指定的子任务 - 同时删除子任务的执行历史记录 """ try: # 检查主任务是否存在 if task_id not in scheduler.tasks: raise HTTPException(status_code=404, detail=f"主任务 {task_id} 不存在") # 检查是否为主任务 if not db.is_main_task(task_id): raise HTTPException(status_code=400, detail=f"任务 {task_id} 不是主任务") # 检查子任务是否存在 sub_task = db.get_sub_task(task_id, sub_task_id) if not sub_task: raise HTTPException(status_code=404, detail=f"子任务 {sub_task_id} 不存在") # 删除子任务 result = db.delete_sub_task(task_id, sub_task_id) if not result: raise HTTPException(status_code=500, detail="删除子任务失败") return { "status": "success", "message": f"成功删除子任务 {sub_task_id}", "task_id": task_id, "sub_task_id": sub_task_id } except HTTPException: raise except Exception as e: logger.error(f"删除子任务失败: {str(e)}") raise HTTPException(status_code=500, detail=f"删除子任务失败: {str(e)}") @router.put("/tasks/{task_id}/subtasks/{sub_task_id}/sequence", summary="更新子任务顺序") async def update_sub_task_sequence( task_id: str, sub_task_id: str, sequence: int = Query(..., description="新的执行顺序"), db: EnhancedSchedulerDB = Depends(get_scheduler_db), scheduler: SchedulerManager = Depends(get_scheduler) ): """ 更新子任务的执行顺序 - 修改子任务在主任务中的执行顺序 - 自动调整其他子任务的顺序 """ try: # 检查主任务是否存在 if task_id not in scheduler.tasks: raise HTTPException(status_code=404, detail=f"主任务 {task_id} 不存在") # 检查是否为主任务 if not db.is_main_task(task_id): raise HTTPException(status_code=400, detail=f"任务 {task_id} 不是主任务") # 检查子任务是否存在 sub_task = db.get_sub_task(task_id, sub_task_id) if not sub_task: raise HTTPException(status_code=404, detail=f"子任务 {sub_task_id} 不存在") # 更新执行顺序 result = db.update_sub_task_sequence(task_id, sub_task_id, sequence) if not result: raise HTTPException(status_code=500, detail="更新子任务执行顺序失败") return { "status": "success", "message": f"成功更新子任务 {sub_task_id} 的执行顺序为 {sequence}", "task_id": task_id, "sub_task_id": sub_task_id, "sequence": sequence } except HTTPException: raise except Exception as e: logger.error(f"更新子任务执行顺序失败: {str(e)}") raise HTTPException(status_code=500, detail=f"更新子任务执行顺序失败: {str(e)}") @router.post("/tasks/{task_id}/enable", summary="启用/禁用任务") async def enable_task( task_id: str, request: dict, db: EnhancedSchedulerDB = Depends(get_scheduler_db), scheduler: SchedulerManager = Depends(get_scheduler) ): """ 启用或禁用任务 - 支持启用/禁用主任务和子任务 - 禁用主任务时会自动禁用其所有子任务 - 启用主任务不会自动启用子任务 - 子任务的启用/禁用不影响其他任务 """ try: # 检查任务是否存在 is_main = db.is_main_task(task_id) task = None if is_main: task = db.get_main_task_by_id(task_id) else: task = db.get_subtask_by_id(task_id) if not task: raise HTTPException(status_code=404, detail=f"任务 {task_id} 不存在") enabled = request.get('enabled', True) if is_main: # 更新主任务状态 result = db.update_main_task(task_id, {'enabled': enabled}) if enabled is False: # 如果是禁用主任务,同时禁用所有子任务 sub_tasks = db.get_sub_tasks(task_id) for sub_task in sub_tasks: db.update_subtask(sub_task['task_id'], {'enabled': False}) success_message = f"已禁用主任务 {task_id} 及其所有子任务" else: success_message = f"已启用主任务 {task_id}" else: # 更新子任务状态 result = db.update_subtask(task_id, {'enabled': enabled}) success_message = f"已{'启用' if enabled else '禁用'}子任务 {task_id}" if not result: raise HTTPException(status_code=500, detail=f"更新任务状态失败") return { "status": "success", "message": success_message, "task_id": task_id, "enabled": enabled } except HTTPException: raise except Exception as e: logger.error(f"更新任务状态失败: {str(e)}") raise HTTPException(status_code=500, detail=f"更新任务状态失败: {str(e)}")
2977094657/BilibiliHistoryFetcher
22,445
routers/title_analytics.py
import sqlite3 from collections import Counter from collections import defaultdict from datetime import datetime from typing import Dict, List, Tuple, Optional import jieba import numpy as np from fastapi import APIRouter, HTTPException, Query from snownlp import SnowNLP from scripts.utils import load_config, get_output_path from .title_pattern_discovery import discover_interaction_patterns router = APIRouter() config = load_config() def get_db(): """获取数据库连接""" db_path = get_output_path(config['db_file']) return sqlite3.connect(db_path) def analyze_keywords(titles_data: List[tuple]) -> List[Tuple[str, int]]: """ 从标题数据中提取关键词及其频率 Args: titles_data: 包含(title, duration, progress, tag_name, view_at)的元组列表 Returns: List[Tuple[str, int]]: 关键词和频率的列表 """ # 停用词列表(可以根据需要扩展) stop_words = {'的', '了', '是', '在', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'} # 所有标题分词后的结果 all_words = [] for title_data in titles_data: title = title_data[0] # 标题在元组的第一个位置 if not title: # 跳过空标题 continue words = jieba.cut(title) # 过滤停用词和单字词(通常单字词不能很好地表达含义) words = [w for w in words if w not in stop_words and len(w) > 1] all_words.extend(words) # 统计词频 word_freq = Counter(all_words) # 返回前20个最常见的词 return word_freq.most_common(20) def analyze_completion_rates(titles_data: List[tuple]) -> Dict: """ 分析标题特征与完成率的关系 Args: titles_data: 包含(title, duration, progress, tag_name, view_at)的元组列表 Returns: Dict: 完成率分析结果 """ # 计算每个视频的完成率 completion_rates = [] titles = [] for title_data in titles_data: title = title_data[0] duration = float(title_data[1]) if title_data[1] is not None else 0 progress = float(title_data[2]) if title_data[2] is not None else 0 if duration and duration > 0: # 确保duration有效且大于0 if progress == -1.0: # progress为-1表示看完了 completion_rate = 1.0 elif progress > 0: completion_rate = min(progress / duration, 1.0) # 限制最大值为1 else: completion_rate = 0.0 completion_rates.append(completion_rate) titles.append(title) # 提取关键词 keywords = analyze_keywords([(title,) for title in titles]) # 分析包含每个关键词的视频的平均完成率 keyword_completion_rates = {} for keyword, _ in keywords: rates = [] for title, rate in zip(titles, completion_rates): if keyword in title: rates.append(rate) if rates: # 如果有包含该关键词的视频 avg_rate = sum(rates) / len(rates) keyword_completion_rates[keyword] = { 'average_completion_rate': avg_rate, 'video_count': len(rates) } return keyword_completion_rates def generate_insights(keywords: List[Tuple[str, int]], completion_rates: Dict) -> List[str]: """ 根据关键词和完成率生成洞察 Args: keywords: 关键词和频率的列表 completion_rates: 完成率分析结果 Returns: List[str]: 洞察列表 """ insights = [] # 1. 关键词频率洞察 top_keywords = [(word, count) for word, count in keywords[:5]] if top_keywords: insights.append(f"在您观看的视频中,最常出现的关键词是:{', '.join([f'{word}({count}次)' for word, count in top_keywords])}") # 2. 完成率洞察 if completion_rates: # 按完成率排序 sorted_rates = sorted( [(k, v['average_completion_rate'], v['video_count']) for k, v in completion_rates.items()], key=lambda x: x[1], reverse=True ) # 高完成率关键词(前3个) high_completion = sorted_rates[:3] if high_completion: insights.append(f"包含关键词 {', '.join([f'{k}({rate:.1%})' for k, rate, count in high_completion])} 的视频往往会被您看完。") # 低完成率关键词(后3个) low_completion = sorted_rates[-3:] low_completion.reverse() # 从低到高显示 if low_completion: insights.append(f"而包含关键词 {', '.join([f'{k}({rate:.1%})' for k, rate, count in low_completion])} 的视频较少被看完。") return insights def analyze_title_length(cursor, table_name: str) -> dict: """分析标题长度与观看行为的关系""" cursor.execute(f""" SELECT title, duration, progress FROM {table_name} WHERE duration > 0 AND title IS NOT NULL AND strftime('%Y', datetime(view_at, 'unixepoch')) = ? """, (table_name.split('_')[-1],)) length_stats = defaultdict(lambda: {'count': 0, 'completion_rates': []}) for title, duration, progress in cursor.fetchall(): length = len(title) completion_rate = progress / duration if duration > 0 else 0 length_group = (length // 5) * 5 # 按5个字符分组 length_stats[length_group]['count'] += 1 length_stats[length_group]['completion_rates'].append(completion_rate) # 计算每个长度组的平均完成率 results = {} for length_group, stats in length_stats.items(): avg_completion = np.mean(stats['completion_rates']) results[f"{length_group}-{length_group+4}字"] = { 'count': stats['count'], 'avg_completion_rate': avg_completion } # 找出最佳长度范围 best_length = max(results.items(), key=lambda x: x[1]['avg_completion_rate']) most_common = max(results.items(), key=lambda x: x[1]['count']) return { 'length_stats': results, 'best_length': best_length[0], 'most_common_length': most_common[0], 'insights': [ f"标题长度在{best_length[0]}的视频最容易被你看完,平均完成率为{best_length[1]['avg_completion_rate']:.1%}", f"你观看的视频中,标题长度最常见的是{most_common[0]},共有{most_common[1]['count']}个视频" ] } def analyze_title_sentiment(cursor, table_name: str) -> dict: """分析标题情感与观看行为的关系""" cursor.execute(f""" SELECT title, duration, progress FROM {table_name} WHERE duration > 0 AND title IS NOT NULL AND strftime('%Y', datetime(view_at, 'unixepoch')) = ? """, (table_name.split('_')[-1],)) sentiment_stats = { '积极': {'count': 0, 'completion_rates': []}, '中性': {'count': 0, 'completion_rates': []}, '消极': {'count': 0, 'completion_rates': []} } for title, duration, progress in cursor.fetchall(): sentiment = SnowNLP(title).sentiments completion_rate = progress / duration if duration > 0 else 0 # 情感分类 if sentiment > 0.6: category = '积极' elif sentiment < 0.4: category = '消极' else: category = '中性' sentiment_stats[category]['count'] += 1 sentiment_stats[category]['completion_rates'].append(completion_rate) # 计算每种情感的平均完成率 results = {} for sentiment, stats in sentiment_stats.items(): if stats['count'] > 0: results[sentiment] = { 'count': stats['count'], 'avg_completion_rate': np.mean(stats['completion_rates']) } # 找出最受欢迎的情感类型 best_sentiment = max(results.items(), key=lambda x: x[1]['avg_completion_rate']) most_common = max(results.items(), key=lambda x: x[1]['count']) return { 'sentiment_stats': results, 'best_sentiment': best_sentiment[0], 'most_common_sentiment': most_common[0], 'insights': [ f"{best_sentiment[0]}情感的视频最容易引起你的兴趣,平均完成率为{best_sentiment[1]['avg_completion_rate']:.1%}", f"在你观看的视频中,{most_common[0]}情感的内容最多,共有{most_common[1]['count']}个视频" ] } def analyze_title_trends(cursor, table_name: str) -> dict: """分析标题趋势与观看行为的关系""" cursor.execute(f""" SELECT title, duration, progress, view_at FROM {table_name} WHERE duration > 0 AND title IS NOT NULL AND strftime('%Y', datetime(view_at, 'unixepoch')) = ? ORDER BY view_at ASC """, (table_name.split('_')[-1],)) # 按月分组的关键词统计和视频计数 monthly_keywords = defaultdict(lambda: defaultdict(int)) monthly_video_count = defaultdict(int) # 新增:每月视频计数 for title, duration, progress, view_at in cursor.fetchall(): month = datetime.fromtimestamp(view_at).strftime('%Y-%m') monthly_video_count[month] += 1 # 新增:增加月度视频计数 words = jieba.cut(title) for word in words: if len(word) > 1: # 排除单字词 monthly_keywords[month][word] += 1 # 分析每个月的热门关键词 trending_keywords = {} for month, keywords in monthly_keywords.items(): # 获取当月TOP5关键词 top_keywords = sorted(keywords.items(), key=lambda x: x[1], reverse=True)[:5] trending_keywords[month] = { 'top_keywords': top_keywords, 'total_videos': monthly_video_count[month] # 修改:使用实际的月度视频数量 } # 识别关键词趋势 all_months = sorted(trending_keywords.keys()) if len(all_months) >= 2: first_month = all_months[0] last_month = all_months[-1] # 计算关键词增长率 first_keywords = set(k for k, _ in trending_keywords[first_month]['top_keywords']) last_keywords = set(k for k, _ in trending_keywords[last_month]['top_keywords']) new_trending = last_keywords - first_keywords fading = first_keywords - last_keywords consistent = first_keywords & last_keywords trend_insights = [] if new_trending: trend_insights.append(f"新兴关键词: {', '.join(new_trending)}") if consistent: trend_insights.append(f"持续热门: {', '.join(consistent)}") if fading: trend_insights.append(f"减少关注: {', '.join(fading)}") else: trend_insights = ["数据量不足以分析趋势"] return { 'monthly_trends': trending_keywords, 'insights': trend_insights } def analyze_title_interaction(cursor, table_name: str) -> dict: """分析标题与用户互动的关系""" cursor.execute(f""" SELECT title, duration, progress, tag_name, view_at FROM {table_name} WHERE duration > 0 AND title IS NOT NULL AND strftime('%Y', datetime(view_at, 'unixepoch')) = ? """, (table_name.split('_')[-1],)) titles_data = cursor.fetchall() # 使用互动模式发现功能,不再传递table_name参数 discovered_patterns = discover_interaction_patterns(titles_data) interaction_stats = defaultdict(lambda: {'count': 0, 'completion_rates': []}) for title, duration, progress, *_ in titles_data: completion_rate = progress / duration if duration > 0 else 0 found_pattern = False for pattern_type, pattern_info in discovered_patterns.items(): if any(keyword in title for keyword in pattern_info['keywords']): interaction_stats[pattern_type]['count'] += 1 interaction_stats[pattern_type]['completion_rates'].append(completion_rate) found_pattern = True if not found_pattern: interaction_stats['其他']['count'] += 1 interaction_stats['其他']['completion_rates'].append(completion_rate) results = {} for pattern, stats in interaction_stats.items(): if stats['count'] > 0: results[pattern] = { 'count': stats['count'], 'avg_completion_rate': np.mean(stats['completion_rates']), 'keywords': discovered_patterns[pattern]['keywords'] if pattern in discovered_patterns else [] } best_pattern = max(results.items(), key=lambda x: x[1]['avg_completion_rate']) most_common = max(results.items(), key=lambda x: x[1]['count']) return { 'interaction_stats': results, 'best_pattern': best_pattern[0], 'most_common_pattern': most_common[0], 'insights': [ f"{best_pattern[0]}互动方式的标题最容易引起互动,平均完成率为{best_pattern[1]['avg_completion_rate']:.1%}", f"在你观看的视频中,{most_common[0]}互动方式最常见,共有{most_common[1]['count']}个视频" ] } def validate_year_and_get_table(year: Optional[int]) -> tuple: """验证年份并返回表名和可用年份列表 Args: year: 要验证的年份,None表示使用最新年份 Returns: tuple: (table_name, target_year, available_years) 或 (None, None, error_response) """ # 导入已有的函数,避免重复代码 from .viewing_analytics import get_available_years # 获取可用年份列表 available_years = get_available_years() if not available_years: error_response = { "status": "error", "message": "未找到任何历史记录数据" } return None, None, error_response # 如果未指定年份,使用最新的年份 target_year = year if year is not None else available_years[0] # 检查指定的年份是否可用 if year is not None and year not in available_years: error_response = { "status": "error", "message": f"未找到 {year} 年的历史记录数据。可用的年份有:{', '.join(map(str, available_years))}" } return None, None, error_response table_name = f"bilibili_history_{target_year}" return table_name, target_year, available_years @router.get("/keyword-analysis", summary="获取标题关键词分析") async def get_keyword_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取标题关键词分析数据 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含关键词分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'keyword_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的关键词分析数据") return cached_response print(f"开始分析 {target_year} 年的标题关键词数据") # 获取所有标题数据 cursor.execute(f""" SELECT title, duration, progress FROM {table_name} WHERE title IS NOT NULL AND title != '' """) titles_data = cursor.fetchall() if not titles_data: return { "status": "error", "message": "未找到任何有效的标题数据" } # 分词和关键词提取 keywords = analyze_keywords(titles_data) # 分析完成率 completion_analysis = analyze_completion_rates(titles_data) # 生成洞察 insights = generate_insights(keywords, completion_analysis) # 构建响应 response = { "status": "success", "data": { "keyword_analysis": { "top_keywords": [{"word": word, "count": count} for word, count in keywords], "completion_rates": completion_analysis }, "insights": insights, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的关键词分析数据缓存") pattern_cache.cache_patterns(table_name, 'keyword_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/length-analysis", summary="获取标题长度分析") async def get_length_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取标题长度分析数据 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含标题长度分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'length_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的标题长度分析数据") return cached_response print(f"开始分析 {target_year} 年的标题长度数据") # 获取标题长度分析 length_analysis = analyze_title_length(cursor, table_name) # 构建响应 response = { "status": "success", "data": { "length_analysis": length_analysis, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的标题长度分析数据缓存") pattern_cache.cache_patterns(table_name, 'length_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/sentiment-analysis", summary="获取标题情感分析") async def get_sentiment_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取标题情感分析数据 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含标题情感分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'sentiment_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的标题情感分析数据") return cached_response print(f"开始分析 {target_year} 年的标题情感数据") # 获取标题情感分析 sentiment_analysis = analyze_title_sentiment(cursor, table_name) # 构建响应 response = { "status": "success", "data": { "sentiment_analysis": sentiment_analysis, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的标题情感分析数据缓存") pattern_cache.cache_patterns(table_name, 'sentiment_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/trend-analysis", summary="获取标题趋势分析") async def get_trend_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取标题趋势分析数据 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含标题趋势分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'trend_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的标题趋势分析数据") return cached_response print(f"开始分析 {target_year} 年的标题趋势数据") # 获取标题趋势分析 trend_analysis = analyze_title_trends(cursor, table_name) # 构建响应 response = { "status": "success", "data": { "trend_analysis": trend_analysis, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的标题趋势分析数据缓存") pattern_cache.cache_patterns(table_name, 'trend_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close() @router.get("/interaction-analysis", summary="获取标题互动分析") async def get_interaction_analysis( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份"), use_cache: bool = Query(True, description="是否使用缓存,默认为True。如果为False则重新分析数据") ): """获取标题互动分析数据 Args: year: 要分析的年份,不传则使用当前年份 use_cache: 是否使用缓存,默认为True。如果为False则重新分析数据 Returns: dict: 包含标题互动分析的数据 """ # 验证年份并获取表名 table_name, target_year, available_years = validate_year_and_get_table(year) if table_name is None: return available_years # 这里是错误响应 conn = get_db() try: cursor = conn.cursor() # 如果启用缓存,尝试从缓存获取 if use_cache: from .title_pattern_discovery import pattern_cache cached_response = pattern_cache.get_cached_patterns(table_name, 'interaction_analysis') if cached_response: print(f"从缓存获取 {target_year} 年的标题互动分析数据") return cached_response print(f"开始分析 {target_year} 年的标题互动数据") # 获取标题互动分析 interaction_analysis = analyze_title_interaction(cursor, table_name) # 构建响应 response = { "status": "success", "data": { "interaction_analysis": interaction_analysis, "year": target_year, "available_years": available_years } } # 更新缓存 from .title_pattern_discovery import pattern_cache print(f"更新 {target_year} 年的标题互动分析数据缓存") pattern_cache.cache_patterns(table_name, 'interaction_analysis', response) return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if conn: conn.close()
2929004360/ruoyi-sign
3,792
ruoyi-flowable/src/main/resources/mapper/flowable/WfRoamHistoricalMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfRoamHistoricalMapper"> <resultMap type="WfRoamHistorical" id="WfRoamHistoricalResult"> <result property="roamHistoricalId" column="roam_historical_id" /> <result property="businessId" column="business_id" /> <result property="processId" column="process_id" /> <result property="businessProcessType" column="business_process_type" /> <result property="data" column="data" /> </resultMap> <sql id="selectWfRoamHistoricalVo"> select roam_historical_id, business_id, process_id, business_process_type, data from wf_roam_historical </sql> <select id="selectWfRoamHistoricalList" parameterType="WfRoamHistorical" resultMap="WfRoamHistoricalResult"> <include refid="selectWfRoamHistoricalVo"/> <where> <if test="roamHistoricalId != null and roamHistoricalId != ''"> and roam_historical_id = #{roamHistoricalId}</if> <if test="businessId != null and businessId != ''"> and business_id = #{businessId}</if> <if test="processId != null and processId != ''"> and process_id = #{processId}</if> <if test="businessProcessType != null and businessProcessType != ''"> and business_process_type = #{businessProcessType}</if> </where> </select> <select id="selectWfRoamHistoricalByRoamHistoricalId" parameterType="String" resultMap="WfRoamHistoricalResult"> <include refid="selectWfRoamHistoricalVo"/> where roam_historical_id = #{roamHistoricalId} </select> <insert id="insertWfRoamHistorical" parameterType="WfRoamHistorical"> insert into wf_roam_historical <trim prefix="(" suffix=")" suffixOverrides=","> <if test="roamHistoricalId != null and roamHistoricalId != ''">roam_historical_id,</if> <if test="businessId != null">business_id,</if> <if test="processId != null">process_id,</if> <if test="businessProcessType != null">business_process_type,</if> <if test="data != null">data,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="roamHistoricalId != null and roamHistoricalId != ''">#{roamHistoricalId},</if> <if test="businessId != null">#{businessId},</if> <if test="processId != null">#{processId},</if> <if test="businessProcessType != null">#{businessProcessType},</if> <if test="data != null">#{data},</if> </trim> </insert> <update id="updateWfRoamHistorical" parameterType="WfRoamHistorical"> update wf_roam_historical <trim prefix="SET" suffixOverrides=","> <if test="businessId != null">business_id = #{businessId},</if> <if test="processId != null">process_id = #{processId},</if> <if test="businessProcessType != null">business_process_type = #{businessProcessType},</if> <if test="data != null">data = #{data},</if> </trim> where roam_historical_id = #{roamHistoricalId} </update> <delete id="deleteWfRoamHistoricalByRoamHistoricalId" parameterType="String"> delete from wf_roam_historical where roam_historical_id = #{roamHistoricalId} </delete> <delete id="deleteWfRoamHistoricalByRoamHistoricalIds" parameterType="String"> delete from wf_roam_historical where roam_historical_id in <foreach item="roamHistoricalId" collection="array" open="(" separator="," close=")"> #{roamHistoricalId} </foreach> </delete> </mapper>
2929004360/ruoyi-sign
1,509
ruoyi-flowable/src/main/resources/mapper/flowable/WfCategoryMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfCategoryMapper"> <resultMap type="WfCategory" id="CategoryResult"> <result property="categoryId" column="category_id"/> <result property="categoryName" column="category_name"/> <result property="code" column="code"/> <result property="createBy" column="create_by"/> <result property="createTime" column="create_time"/> <result property="updateBy" column="update_by"/> <result property="updateTime" column="update_time"/> <result property="remark" column="remark"/> <result property="delFlag" column="del_flag"/> </resultMap> <sql id="selectCategoryVo"> select category_id, category_name, code, remark, create_by, create_time, update_by, update_time, del_flag from wf_category </sql> <select id="selectWfCategoryPage" resultMap="CategoryResult"> <include refid="selectCategoryVo"/> <where> <if test="categoryName != null and categoryName != ''">and category_name = #{categoryName}</if> <if test="code != null and code != ''">and code like concat('%', #{code}, '%')</if> </where> ORDER BY create_time DESC </select> </mapper>
2929004360/ruoyi-sign
6,711
ruoyi-flowable/src/main/resources/mapper/flowable/WfModelTemplateMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfModelTemplateMapper"> <resultMap type="WfModelTemplate" id="WfModelTemplateResult"> <result property="modelTemplateId" column="model_template_id"/> <result property="deptId" column="dept_id"/> <result property="name" column="name"/> <result property="deptName" column="dept_name"/> <result property="type" column="type"/> <result property="formType" column="form_type"/> <result property="bpmnXml" column="bpmnXml"/> <result property="createTime" column="create_time"/> <result property="updateTime" column="update_time"/> </resultMap> <sql id="selectWfModelTemplateVo"> select model_template_id, dept_id, name, dept_name, type, form_type, bpmnXml, create_time, update_time from wf_model_template </sql> <sql id="selectWfModelTemplateSql"> model_template_id, dept_id, `name`, dept_name, `type`, `form_type`, bpmnXml, create_time, update_time </sql> <select id="selectWfModelTemplateList" parameterType="WfModelTemplate" resultMap="WfModelTemplateResult"> <include refid="selectWfModelTemplateVo"/> <where> <if test="deptId != null and deptId != ''">and dept_id = #{deptId}</if> <if test="name != null and name != ''">and name like concat('%', #{name}, '%')</if> <if test="deptName != null and deptName != ''">and dept_name like concat('%', #{deptName}, '%')</if> <if test="type != null and type != ''">and type = #{type}</if> <if test="formType != null and formType != ''">and form_type = #{formType}</if> <if test="params.beginCreateTime != null and params.beginCreateTime != '' and params.endCreateTime != null and params.endCreateTime != ''"> and create_time between #{params.beginCreateTime} and #{params.endCreateTime} </if> <if test="params.beginUpdateTime != null and params.beginUpdateTime != '' and params.endUpdateTime != null and params.endUpdateTime != ''"> and update_time between #{params.beginUpdateTime} and #{params.endUpdateTime} </if> </where> </select> <select id="selectWfModelTemplateByModelTemplateId" parameterType="String" resultMap="WfModelTemplateResult"> <include refid="selectWfModelTemplateVo"/> where model_template_id = #{modelTemplateId} </select> <select id="selectWfModelTemplateListVo" resultMap="WfModelTemplateResult"> select DISTINCT <include refid="selectWfModelTemplateSql"/> FROM ( select <include refid="selectWfModelTemplateSql"/> FROM wf_model_template where dept_id in <foreach item="deptId" collection="deptIdList" open="(" separator="," close=")"> #{deptId} </foreach> UNION ALL select <include refid="selectWfModelTemplateSql"/> FROM wf_model_template where dept_id = #{wfModelTemplate.deptId} and type = '1' UNION ALL select <include refid="selectWfModelTemplateSql"/> FROM wf_model_template where dept_id in <foreach item="deptId" collection="ancestorsList" open="(" separator="," close=")"> #{deptId} </foreach> and type = '2' ) f <where> <if test="wfModelTemplate.name != null and wfModelTemplate.name != ''">and `name` = #{wfModelTemplate.name} </if> <if test="wfModelTemplate.formType != null and wfModelTemplate.formType != ''">and form_type = #{wfModelTemplate.formType}</if> </where> </select> <insert id="insertWfModelTemplate" parameterType="WfModelTemplate"> insert into wf_model_template <trim prefix="(" suffix=")" suffixOverrides=","> <if test="modelTemplateId != null">model_template_id,</if> <if test="deptId != null">dept_id,</if> <if test="name != null">name,</if> <if test="deptName != null and deptName != ''">dept_name,</if> <if test="type != null">type,</if> <if test="formType != null">form_type,</if> <if test="bpmnXml != null">bpmnXml,</if> <if test="createTime != null">create_time,</if> <if test="updateTime != null">update_time,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="modelTemplateId != null">#{modelTemplateId},</if> <if test="deptId != null">#{deptId},</if> <if test="name != null">#{name},</if> <if test="deptName != null and deptName != ''">#{deptName},</if> <if test="type != null">#{type},</if> <if test="formType != null">#{formType},</if> <if test="bpmnXml != null">#{bpmnXml},</if> <if test="createTime != null">#{createTime},</if> <if test="updateTime != null">#{updateTime},</if> </trim> </insert> <update id="updateWfModelTemplate" parameterType="WfModelTemplate"> update wf_model_template <trim prefix="SET" suffixOverrides=","> <if test="deptId != null">dept_id = #{deptId},</if> <if test="name != null">name = #{name},</if> <if test="deptName != null and deptName != ''">dept_name = #{deptName},</if> <if test="type != null">type = #{type},</if> <if test="formType != null">form_type = #{formType},</if> <if test="bpmnXml != null">bpmnXml = #{bpmnXml},</if> <if test="createTime != null">create_time = #{createTime},</if> <if test="updateTime != null">update_time = #{updateTime},</if> </trim> where model_template_id = #{modelTemplateId} </update> <delete id="deleteWfModelTemplateByModelTemplateId" parameterType="String"> delete from wf_model_template where model_template_id = #{modelTemplateId} </delete> <delete id="deleteWfModelTemplateByModelTemplateIds" parameterType="String"> delete from wf_model_template where model_template_id in <foreach item="modelTemplateId" collection="array" open="(" separator="," close=")"> #{modelTemplateId} </foreach> </delete> </mapper>
2929004360/ruoyi-sign
2,335
ruoyi-flowable/src/main/resources/mapper/flowable/FlowTaskMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.FlowTaskMapper"> <select id="queryActivityInstance" resultType="org.flowable.engine.impl.persistence.entity.ActivityInstanceEntityImpl"> select t.* from ACT_RU_ACTINST t <where> <if test="processInstanceId !=null and processInstanceId != ''" > t.PROC_INST_ID_=#{processInstanceId} and ACT_TYPE_ = 'userTask' and END_TIME_ is not null </if> </where> order by t.END_TIME_ ASC </select> <delete id="deleteRunActinstsByIds" parameterType="java.util.List"> delete from ACT_RU_ACTINST where ID_ in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </delete> <delete id="deleteHisActinstsByIds" parameterType="java.util.List"> delete from ACT_HI_ACTINST where ID_ in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </delete> <delete id="deleteAllHisAndRun" parameterType="String"> delete from ACT_RU_ACTINST where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_RU_IDENTITYLINK where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_RU_TASK where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_RU_VARIABLE where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_RU_EXECUTION where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_HI_ACTINST where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_HI_COMMENT where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_HI_IDENTITYLINK where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_HI_PROCINST where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_HI_TASKINST where PROC_INST_ID_ = #{processInstanceId}; delete from ACT_HI_VARINST where PROC_INST_ID_ = #{processInstanceId}; </delete> <select id="querySubTaskByParentTaskId" resultType="Integer"> select count(1) from ACT_RU_TASK where PARENT_TASK_ID_=#{parentTaskId} </select> </mapper>
2977094657/BilibiliHistoryFetcher
52,471
routers/dynamic.py
import os import shutil import asyncio from typing import Optional, Dict, Any, List from fastapi import APIRouter, HTTPException, Query, Response from fastapi.responses import StreamingResponse from loguru import logger import aiohttp import aiofiles from scripts.utils import load_config, setup_logger, get_output_path from scripts.dynamic_db import ( get_connection, save_normalized_dynamic_item, list_hosts_with_stats, list_dynamics_for_host, dynamic_core_exists, purge_host, ) from scripts.dynamic_media import collect_image_urls, download_images, predict_image_path, collect_live_media_urls, download_live_media, collect_emoji_urls, download_emojis # 确保日志系统已初始化 setup_logger() router = APIRouter() # 任务管理:按 host_mid 管理抓取任务、停止信号与进度 _tasks = {} _stop_events = {} _progress = {} def _get_or_create_event(host_mid: int) -> asyncio.Event: if host_mid not in _stop_events: _stop_events[host_mid] = asyncio.Event() return _stop_events[host_mid] def _clear_event(host_mid: int) -> None: """清除停止事件""" if host_mid in _stop_events: try: _stop_events[host_mid].clear() logger.info(f"[DEBUG] 已清除停止事件 host_mid={host_mid}") except Exception as e: logger.warning(f"[DEBUG] 清除停止事件失败: {e}") else: logger.info(f"[DEBUG] 停止事件不存在于缓存中 host_mid={host_mid}") def _set_progress(host_mid: int, page: int, total_items: int, last_offset: str, message: str) -> None: _progress[host_mid] = { "page": page, "total_items": total_items, "last_offset": last_offset or "", "message": message, } def _get_progress(host_mid: int) -> Dict[str, Any]: return _progress.get(host_mid, {"page": 0, "total_items": 0, "last_offset": "", "message": "空闲状态,未开始抓取"}) @router.get("/space/auto/{host_mid}/progress", summary="SSE 实时获取自动抓取进度") async def auto_fetch_progress(host_mid: int): """ 以 SSE 流方式每秒推送一次当前抓取进度。 数据格式为 text/event-stream,data 为 JSON 字符串。 """ async def event_generator(): while True: progress = _get_progress(host_mid) # 构造 SSE 包 import json payload = json.dumps({ "host_mid": host_mid, "page": progress.get("page", 0), "total_items": progress.get("total_items", 0), "last_offset": progress.get("last_offset", ""), "message": progress.get("message", "idle"), }, ensure_ascii=False) yield f"event: progress\ndata: {payload}\n\n" await asyncio.sleep(1) return StreamingResponse(event_generator(), media_type="text/event-stream") @router.post("/space/auto/{host_mid}/stop", summary="停止当前自动抓取(页级停止)") async def stop_auto_fetch(host_mid: int): """ 发送停止信号,当前页完成后停止抓取,并记录 offset 以便下次继续。 注意:下次开始抓取时会自动清除停止信号。 """ ev = _get_or_create_event(host_mid) ev.set() logger.info(f"[DEBUG] 发送停止信号 host_mid={host_mid}, 事件状态: is_set={ev.is_set()}") return {"status": "ok", "message": "stop signal sent", "event_is_set": ev.is_set()} @router.get("/db/hosts", summary="列出数据库中已有动态的UP列表") async def list_db_hosts( limit: int = Query(50, ge=1, le=200, description="每页数量"), offset: int = Query(0, ge=0, description="偏移量"), ): try: conn = get_connection() except Exception as e: logger.error(f"打开动态数据库失败: {e}") raise HTTPException(status_code=500, detail=f"打开动态数据库失败: {str(e)}") try: data = list_hosts_with_stats(conn, limit=limit, offset=offset) # 基础输出根目录(用于拼接相对路径) base_output_dir = os.path.dirname(get_output_path("__base__")) # 为每个 host_mid 增补 up_name 与 face_path(若存在则返回相对路径) cursor = conn.cursor() for rec in data: host_mid = rec.get("host_mid") up_name = None face_rel = None try: # 查询最近一条记录的作者名 row = cursor.execute( """ SELECT author_name FROM dynamic_core WHERE host_mid = ? AND author_name IS NOT NULL AND author_name <> '' ORDER BY (publish_ts IS NULL) ASC, publish_ts DESC, fetch_time DESC LIMIT 1 """, (str(host_mid),), ).fetchone() if row and row[0]: up_name = row[0] except Exception as e: logger.warning(f"查询作者名失败(忽略) host_mid={host_mid}: {e}") # 头像:output/dynamic/{mid}/face.* try: host_dir = os.path.dirname(get_output_path("dynamic", str(host_mid), "__host_meta.json")) if os.path.isdir(host_dir): for name in os.listdir(host_dir): if os.path.isfile(os.path.join(host_dir, name)) and name.lower().startswith("face."): face_rel = os.path.relpath(os.path.join(host_dir, name), base_output_dir) break except Exception as e: logger.warning(f"定位头像失败(忽略) host_mid={host_mid}: {e}") # 写回扩展字段 rec["up_name"] = up_name rec["face_path"] = face_rel return {"data": data, "limit": limit, "offset": offset} finally: try: conn.close() except Exception: pass @router.get("/db/space/{host_mid}", summary="列出指定UP的动态(来自数据库)") async def list_db_space( host_mid: int, limit: int = Query(20, ge=1, le=200, description="每页数量"), offset: int = Query(0, ge=0, description="偏移量"), ): try: conn = get_connection() except Exception as e: logger.error(f"打开动态数据库失败: {e}") raise HTTPException(status_code=500, detail=f"打开动态数据库失败: {str(e)}") try: result = list_dynamics_for_host(conn, host_mid=host_mid, limit=limit, offset=offset) # 将 media_locals 和 live_media_locals 从逗号分隔字符串转换为数组,便于前端使用 try: items = result.get("items", []) if isinstance(result, dict) else [] for item in items: # 处理普通媒体 ml = item.get("media_locals") if isinstance(ml, str): ml_str = ml.strip() if ml_str: item["media_locals"] = [p for p in (s.strip() for s in ml_str.split(",")) if p] else: item["media_locals"] = [] elif ml is None: item["media_locals"] = [] # 处理实况媒体 lml = item.get("live_media_locals") if isinstance(lml, str): lml_str = lml.strip() if lml_str: item["live_media_locals"] = [p for p in (s.strip() for s in lml_str.split(",")) if p] else: item["live_media_locals"] = [] elif lml is None: item["live_media_locals"] = [] except Exception as e: logger.warning(f"媒体路径转换失败(忽略) host_mid={host_mid}: {e}") return {"host_mid": str(host_mid), **result, "limit": limit, "offset": offset} finally: try: conn.close() except Exception: pass def get_headers() -> Dict[str, str]: """获取请求头""" config = load_config() sessdata = config.get("SESSDATA", "") headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36', 'Referer': 'https://www.bilibili.com/', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', } if sessdata: headers['Cookie'] = f'SESSDATA={sessdata}' return headers async def fetch_dynamic_data(api_url: str, params: Dict[str, Any]) -> Dict[str, Any]: """获取动态数据的通用函数""" headers = get_headers() async with aiohttp.ClientSession() as session: try: async with session.get(api_url, headers=headers, params=params) as response: if response.status == 200: # 内容类型保护:仅当返回为 JSON 时才解析为 JSON content_type = response.headers.get("Content-Type", "") if "application/json" in content_type or "text/json" in content_type or "application/vnd" in content_type: data = await response.json() else: # 非JSON返回,读取少量文本用于错误提示(不抛出二次异常) try: snippet = (await response.text())[:256] except Exception: snippet = "<non-text response>" logger.error(f"请求返回非JSON,Content-Type={content_type} url={api_url} params={params} snippet={snippet}") raise HTTPException(status_code=500, detail="非JSON响应,无法解析") logger.info(f"成功获取动态数据,状态码: {response.status}") return data else: logger.error(f"请求失败,状态码: {response.status}") raise HTTPException(status_code=response.status, detail=f"请求失败: {response.status}") except aiohttp.ClientError as e: logger.error(f"网络请求错误: {e}") raise HTTPException(status_code=500, detail=f"网络请求错误: {str(e)}") @router.get("/space/auto/{host_mid}", summary="自动从前到后抓取直至完成") async def auto_fetch_all( host_mid: int, need_top: bool = Query(False, description="是否需要置顶动态"), save_to_db: bool = Query(True, description="是否保存到数据库"), save_media: bool = Query(True, description="是否保存图片等多媒体"), ): """ 自动连续抓取用户空间动态: - 从上次记录的offset继续;若存在 fully_fetched=true 则从头开始 - 每页3-5秒随机延迟 - 当 offset 为空时终止,写 fully_fetched=true - 若从头开始抓取遇到连续10条已存在的动态ID则停止,并不保存这10条 """ import json, time, random api_url = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space" params = { "host_mid": host_mid, "need_top": 1 if need_top else 0, "features": "itemOpusStyle,listOnlyfans,opusBigCover,onlyfansVote,forwardListHidden,decorationCard,commentsNewVersion,onlyfansAssetsV2,ugcDelete,onlyfansQaCard" } # 读取 host 元数据 host_dir = os.path.dirname(get_output_path("dynamic", str(host_mid), "__host_meta.json")) os.makedirs(host_dir, exist_ok=True) meta_path = os.path.join(host_dir, "__host_meta.json") meta = {"host_mid": str(host_mid), "last_fetch_time": 0, "last_offset": {"offset": "", "update_baseline": "", "update_num": 0}, "fully_fetched": False} if os.path.exists(meta_path): try: with open(meta_path, "r", encoding="utf-8") as rf: old = json.load(rf) if isinstance(old, dict): meta.update(old) except Exception: pass # 确定起点 start_from_head = bool(meta.get("fully_fetched", False)) next_offset = None if start_from_head else (meta.get("last_offset", {}) or {}).get("offset") or None # 调试信息:打印offset使用情况 logger.info(f"[DEBUG] 抓取开始 host_mid={host_mid}") logger.info(f"[DEBUG] 元数据内容: {meta}") logger.info(f"[DEBUG] fully_fetched={meta.get('fully_fetched')}, start_from_head={start_from_head}") logger.info(f"[DEBUG] last_offset对象: {meta.get('last_offset', {})}") logger.info(f"[DEBUG] 将使用的next_offset: {next_offset}") if start_from_head: logger.info(f"[DEBUG] 模式: 从头开始抓取 (因为fully_fetched=True)") elif next_offset: logger.info(f"[DEBUG] 模式: 从offset继续抓取 (offset={next_offset})") else: logger.info(f"[DEBUG] 模式: 从头开始抓取 (无有效offset)") # DB 连接 if save_to_db: try: conn = get_connection() except Exception as e: logger.error(f"打开动态数据库失败: {e}") raise HTTPException(status_code=500, detail=f"打开动态数据库失败: {str(e)}") else: conn = None all_items = [] consecutive_duplicates = 0 # 页计数 current_page = 0 # 自动重置停止信号:每次开始抓取前都清除之前的停止状态 logger.info(f"[DEBUG] 自动重置停止信号 host_mid={host_mid}") _clear_event(host_mid) # 确保清除任何遗留的停止信号 stop_event = _get_or_create_event(host_mid) # 创建新的事件对象 # 验证重置结果 logger.info(f"[DEBUG] 重置后停止事件状态: is_set={stop_event.is_set()}") _set_progress(host_mid, current_page, 0, next_offset or "", "准备开始抓取动态") try: while True: # 调试信息:打印每页请求的参数 logger.info(f"[DEBUG] === 第 {current_page + 1} 页请求 ===") logger.info(f"[DEBUG] 当前next_offset: {next_offset}") if next_offset: params["offset"] = next_offset logger.info(f"[DEBUG] 设置offset参数: {next_offset}") elif "offset" in params: params.pop("offset", None) logger.info(f"[DEBUG] 移除offset参数(从头开始)") logger.info(f"[DEBUG] 最终请求参数: {params}") # 更新进度:准备抓取下一页 if current_page > 0: _set_progress(host_mid, current_page, len(all_items), next_offset or "", f"准备抓取第 {current_page + 1} 页...") # 随机延迟3-5秒 await asyncio.sleep(random.uniform(3, 5)) data = await fetch_dynamic_data(api_url, params) # 调试信息:打印API响应中的offset信息 logger.info(f"[DEBUG] API响应结构检查:") logger.info(f"[DEBUG] - response.code: {data.get('code')}") logger.info(f"[DEBUG] - response.data存在: {bool(data.get('data'))}") # 兼容B站原始结构:从data.data中获取items和offset data_section = data.get("data", {}) if isinstance(data, dict) else {} items = data_section.get("items", []) if isinstance(data_section, dict) else [] # offset 既可能是字符串,也可能在对象中 off = data_section.get("offset") if isinstance(data_section, dict) else None logger.info(f"[DEBUG] - data_section.offset原始值: {off} (类型: {type(off)})") if isinstance(off, dict): next_offset = off.get("offset") logger.info(f"[DEBUG] - 从offset对象提取: {next_offset}") else: next_offset = off logger.info(f"[DEBUG] - 直接使用offset: {next_offset}") logger.info(f"[DEBUG] - 本页获取items数量: {len(items)}") logger.info(f"[DEBUG] - 下一页的offset: {next_offset}") # 若从头开始,并且出现连续10条都已存在,则停止 if start_from_head and conn is not None: for item in items: id_str = item.get("id_str") or item.get("basic", {}).get("id_str") or str(item.get("id")) if id_str and dynamic_core_exists(conn, host_mid, str(id_str)): consecutive_duplicates += 1 if consecutive_duplicates >= 10: next_offset = None # 触发终止 items = [] # 不保存这10条 break else: consecutive_duplicates = 0 all_items.extend(items) current_page += 1 _set_progress(host_mid, current_page, len(all_items), next_offset or "", f"第 {current_page} 页抓取完成,本页获取 {len(items)} 条动态,累计 {len(all_items)} 条") # 保存页面数据(去掉item.json保存,只有包含多媒体文件时才创建文件夹) if save_to_db and items: base_output_dir = os.path.dirname(get_output_path("__base__")) # 头像保存:仅保存一次到 output/dynamic/{host_mid}/face.(ext) try: # 尝试从items提取用户头像 face_url = None for item in items: modules_raw = item.get("modules") if isinstance(modules_raw, dict): face_url = modules_raw.get("module_author", {}).get("face") elif isinstance(modules_raw, list): for mod in modules_raw: if isinstance(mod, dict) and mod.get("module_type") == "MODULE_TYPE_AUTHOR": face_url = mod.get("module_author", {}).get("user", {}).get("face") or mod.get("module_author", {}).get("face") if face_url: break if not face_url: face_url = item.get("user", {}).get("face") if face_url: break if face_url: # 若已存在头像文件则跳过 host_dir = os.path.dirname(get_output_path("dynamic", str(host_mid), "__host_meta.json")) os.makedirs(host_dir, exist_ok=True) # 检查是否已有任何文件以 face.* 命名 exists = any( name.lower().startswith("face.") for name in os.listdir(host_dir) if os.path.isfile(os.path.join(host_dir, name)) ) if not exists: # 下载头像一次 results = await download_images([face_url], host_dir) # 将下载的哈希文件重命名为 face.扩展名 for url, local_path, ok in results: if ok: _, ext = os.path.splitext(local_path) new_path = os.path.join(host_dir, f"face{ext}") try: if os.path.exists(new_path): os.remove(new_path) except Exception: pass try: os.replace(local_path, new_path) except Exception: pass break except Exception as e: logger.warning(f"保存头像失败(忽略):{e}") for item in items: try: id_str = ( item.get("id_str") or item.get("basic", {}).get("id_str") or str(item.get("id")) ) if not id_str: continue # 检查是否有多媒体文件需要下载 has_media = False predicted_locals = [] live_predicted_locals = [] if save_media: # 处理普通图片 image_urls = collect_image_urls(item) if image_urls: has_media = True # 只有当包含多媒体文件时才创建文件夹 item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) # 预测本地路径 for u in image_urls: predicted_locals.append(os.path.relpath(predict_image_path(u, item_dir), base_output_dir)) results = await download_images(image_urls, item_dir) media_records = [] for media_url, local_path, ok in results: if ok: rel_path = os.path.relpath(local_path, base_output_dir) media_records.append((media_url, rel_path, "image")) # 处理实况媒体(live图片+视频) live_media_pairs = collect_live_media_urls(item) if live_media_pairs: has_media = True # 创建文件夹(如果还未创建) if not image_urls: item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) live_results = await download_live_media(live_media_pairs, item_dir) for image_url, video_url, image_path, video_path, ok in live_results: if ok: # 将实况媒体路径分别记录 image_rel = os.path.relpath(image_path, base_output_dir) video_rel = os.path.relpath(video_path, base_output_dir) live_predicted_locals.extend([image_rel, video_rel]) # 处理表情 emoji_pairs = collect_emoji_urls(item) if emoji_pairs: has_media = True # 创建文件夹(如果还未创建) if not image_urls and not live_media_pairs: item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) emoji_results = await download_emojis(emoji_pairs, item_dir) for emoji_url, emoji_path, ok in emoji_results: if ok: # 将表情路径记录到普通媒体中 emoji_rel = os.path.relpath(emoji_path, base_output_dir) predicted_locals.append(emoji_rel) # 规范化保存到数据库 logger.info(f"normalize.core.call begin host_mid={host_mid} id_str={id_str}") try: save_normalized_dynamic_item(conn, host_mid, item) logger.info(f"normalize.core.call done host_mid={host_mid} id_str={id_str}") # 回写本地路径逗号串(只有当有多媒体文件时) if predicted_locals or live_predicted_locals: cursor = conn.cursor() cursor.execute( """ UPDATE dynamic_core SET media_locals = CASE WHEN media_locals IS NULL OR media_locals = '' THEN ? ELSE media_locals END, live_media_locals = CASE WHEN live_media_locals IS NULL OR live_media_locals = '' THEN ? ELSE live_media_locals END, live_media_count = ? WHERE host_mid = ? AND id_str = ? """, ( ",".join(predicted_locals) if predicted_locals else "", ",".join(live_predicted_locals) if live_predicted_locals else "", len(live_predicted_locals), str(host_mid), str(id_str), ), ) conn.commit() except Exception as norm_err: logger.warning(f"规范化保存失败(忽略): {norm_err}") except Exception as perr: logger.warning(f"保存页面数据失败: {perr}") # 更新 meta meta["last_fetch_time"] = int(time.time()) meta["last_offset"] = {"offset": next_offset or "", "update_baseline": "", "update_num": 0} meta["fully_fetched"] = not bool(next_offset) # 调试信息:保存状态 logger.info(f"[DEBUG] 保存元数据:") logger.info(f"[DEBUG] - last_offset.offset: {next_offset or ''}") logger.info(f"[DEBUG] - fully_fetched: {meta['fully_fetched']}") try: async with aiofiles.open(meta_path, "w", encoding="utf-8") as wf: await wf.write(json.dumps(meta, ensure_ascii=False, indent=2)) logger.info(f"[DEBUG] 元数据已保存到: {meta_path}") except Exception as e: logger.error(f"[DEBUG] 保存元数据失败: {e}") # 终止条件:offset 为空 logger.info(f"[DEBUG] 检查终止条件: next_offset={next_offset}, 是否为空: {not bool(next_offset)}") if not next_offset: _set_progress(host_mid, current_page, len(all_items), next_offset or "", f"[全部抓取完毕] 抓取完成!共获取 {len(all_items)} 条动态,总计 {current_page} 页") break # 页级停止:如收到停止信号,则抓取完本页后停止并记录 offset logger.info(f"[DEBUG] 检查停止信号: is_set={stop_event.is_set()}") if stop_event.is_set(): logger.warning(f"[DEBUG] 🛑 收到停止信号,停止抓取") _set_progress(host_mid, current_page, len(all_items), next_offset or "", f"用户停止抓取,已完成 {current_page} 页,共获取 {len(all_items)} 条动态") break # 返回B站原始结构,合并所有items return { "code": 0, "message": "0", "ttl": 1, "data": { "has_more": bool(next_offset), "items": all_items, "offset": next_offset or "", "update_baseline": "", "update_num": 0, "fully_fetched": meta.get("fully_fetched", False), } } finally: if conn is not None: try: conn.close() except Exception: pass # 关闭后保持最后一次进度 @router.get("/space/{host_mid}", summary="获取用户空间动态") async def get_space_dynamic( host_mid: int, pages: int = Query(1, description="获取页数,0 表示获取全部"), need_top: bool = Query(False, description="是否需要置顶动态"), save_to_db: bool = Query(True, description="是否保存到数据库"), save_media: bool = Query(True, description="是否保存图片等多媒体") ): """ 获取指定用户空间的动态列表 Args: host_mid: 目标用户的UID offset: 分页偏移量 need_top: 是否获取置顶动态 """ try: api_url = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space" params = { "host_mid": host_mid, "need_top": 1 if need_top else 0, "features": "itemOpusStyle,listOnlyfans,opusBigCover,onlyfansVote,forwardListHidden,decorationCard,commentsNewVersion,onlyfansAssetsV2,ugcDelete,onlyfansQaCard" } logger.info(f"请求用户 {host_mid} 的空间动态,参数: {params}, pages={pages}") # 多页抓取:至多 pages 页;若 pages=0 则直到 offset 为空 all_items = [] next_offset: Optional[str] = None current_page = 0 while True: # 注入偏移 if next_offset: params["offset"] = next_offset data = await fetch_dynamic_data(api_url, params) # 兼容B站原始结构:从data.data中获取items和offset data_section = data.get("data", {}) if isinstance(data, dict) else {} items = data_section.get("items", []) if isinstance(data_section, dict) else [] off = data_section.get("offset") if isinstance(data_section, dict) else None if isinstance(off, dict): next_offset = off.get("offset") else: next_offset = off all_items.extend(items) current_page += 1 # 终止条件 if pages == 0: if not next_offset: break else: if current_page >= max(1, pages): break if not next_offset: break # 可选保存 if save_to_db: try: conn = get_connection() except Exception as e: logger.error(f"打开动态数据库失败: {e}") raise HTTPException(status_code=500, detail=f"打开动态数据库失败: {str(e)}") items: List[Dict[str, Any]] = all_items base_output_dir = os.path.dirname(get_output_path("__base__")) # 头像保存:仅保存一次到 output/dynamic/{host_mid}/face.(ext) try: # 尝试从items提取用户头像 face_url = None for item in items: modules_raw = item.get("modules") if isinstance(modules_raw, dict): face_url = modules_raw.get("module_author", {}).get("face") elif isinstance(modules_raw, list): for mod in modules_raw: if isinstance(mod, dict) and mod.get("module_type") == "MODULE_TYPE_AUTHOR": face_url = mod.get("module_author", {}).get("user", {}).get("face") or mod.get("module_author", {}).get("face") if face_url: break if not face_url: face_url = item.get("user", {}).get("face") if face_url: break if face_url: # 若已存在头像文件则跳过 host_dir = os.path.dirname(get_output_path("dynamic", str(host_mid), "__host_meta.json")) os.makedirs(host_dir, exist_ok=True) # 检查是否已有任何文件以 face.* 命名 exists = any( name.lower().startswith("face.") for name in os.listdir(host_dir) if os.path.isfile(os.path.join(host_dir, name)) ) if not exists: # 下载头像一次 results = await download_images([face_url], host_dir) # 将下载的哈希文件重命名为 face.扩展名 for url, local_path, ok in results: if ok: _, ext = os.path.splitext(local_path) new_path = os.path.join(host_dir, f"face{ext}") try: if os.path.exists(new_path): os.remove(new_path) except Exception: pass try: os.replace(local_path, new_path) except Exception: pass break except Exception as e: logger.warning(f"保存头像失败(忽略):{e}") # 写 host_mid 元数据:最后一次获取的时间与offset try: import json, time host_dir = os.path.dirname(get_output_path("dynamic", str(host_mid), "__host_meta.json")) meta_path = os.path.join(host_dir, "__host_meta.json") last_offset_obj = {"offset": next_offset or "", "update_baseline": "", "update_num": 0} meta = { "host_mid": str(host_mid), "last_fetch_time": int(time.time()), "last_offset": last_offset_obj, "fully_fetched": False, } # 合并旧值(保留 fully_fetched 等状态) if os.path.exists(meta_path): try: with open(meta_path, "r", encoding="utf-8") as rf: old = json.load(rf) if isinstance(old, dict): meta.update({k: old.get(k, meta.get(k)) for k in ("fully_fetched",)}) except Exception: pass async with aiofiles.open(meta_path, "w", encoding="utf-8") as wf: await wf.write(json.dumps(meta, ensure_ascii=False, indent=2)) except Exception as e: logger.warning(f"写入 host_mid 元数据失败(忽略):{e}") for item in items: try: id_str = ( item.get("id_str") or item.get("basic", {}).get("id_str") or str(item.get("id")) ) if not id_str: # 跳过无法定位ID的记录 continue # 检查是否有多媒体文件需要下载 has_media = False predicted_locals = [] live_predicted_locals = [] if save_media: # 处理普通图片 image_urls = collect_image_urls(item) if image_urls: has_media = True # 只有当包含多媒体文件时才创建文件夹 item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) # 预测本地路径 for u in image_urls: predicted_locals.append(os.path.relpath(predict_image_path(u, item_dir), base_output_dir)) # 下载多媒体文件 results = await download_images(image_urls, item_dir) media_records = [] for media_url, local_path, ok in results: if ok: rel_path = os.path.relpath(local_path, base_output_dir) media_records.append((media_url, rel_path, "image")) # 处理实况媒体(live图片+视频) live_media_pairs = collect_live_media_urls(item) if live_media_pairs: has_media = True # 创建文件夹(如果还未创建) if not image_urls: item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) live_results = await download_live_media(live_media_pairs, item_dir) for image_url, video_url, image_path, video_path, ok in live_results: if ok: # 将实况媒体路径分别记录 image_rel = os.path.relpath(image_path, base_output_dir) video_rel = os.path.relpath(video_path, base_output_dir) live_predicted_locals.extend([image_rel, video_rel]) # 处理表情 emoji_pairs = collect_emoji_urls(item) if emoji_pairs: has_media = True # 创建文件夹(如果还未创建) if not image_urls and not live_media_pairs: item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) emoji_results = await download_emojis(emoji_pairs, item_dir) for emoji_url, emoji_path, ok in emoji_results: if ok: # 将表情路径记录到普通媒体中 emoji_rel = os.path.relpath(emoji_path, base_output_dir) predicted_locals.append(emoji_rel) # 规范化保存到数据库 logger.info(f"normalize.core.call begin host_mid={host_mid} id_str={id_str}") try: save_normalized_dynamic_item(conn, host_mid, item) logger.info(f"normalize.core.call done host_mid={host_mid} id_str={id_str}") # 回写本地路径逗号串(只有当有多媒体文件时) if predicted_locals or live_predicted_locals: cursor = conn.cursor() cursor.execute( """ UPDATE dynamic_core SET media_locals = CASE WHEN media_locals IS NULL OR media_locals = '' THEN ? ELSE media_locals END, live_media_locals = CASE WHEN live_media_locals IS NULL OR live_media_locals = '' THEN ? ELSE live_media_locals END, live_media_count = ? WHERE host_mid = ? AND id_str = ? """, ( ",".join(predicted_locals) if predicted_locals else "", ",".join(live_predicted_locals) if live_predicted_locals else "", len(live_predicted_locals), str(host_mid), str(id_str), ), ) conn.commit() except Exception as norm_err: logger.warning(f"规范化保存失败(忽略): {norm_err}") except Exception as perr: logger.error(f"保存动态项失败 id_str={item.get('id_str')}: {perr}") try: conn.close() except Exception: pass # 返回B站原始结构,合并所有items return { "code": 0, "message": "0", "ttl": 1, "data": { "has_more": bool(next_offset), "items": all_items, "offset": next_offset or "", "update_baseline": "", "update_num": 0 } } except HTTPException: raise except Exception as e: logger.error(f"获取用户空间动态失败: {e}") raise HTTPException(status_code=500, detail=f"获取用户空间动态失败: {str(e)}") @router.get("/detail/{dynamic_id}", summary="获取动态详情") async def get_dynamic_detail( dynamic_id: str, save_to_db: bool = Query(True, description="是否保存到数据库"), save_media: bool = Query(True, description="是否保存图片等多媒体") ): """ 获取单条动态的详细信息 Args: dynamic_id: 动态ID """ try: api_url = "https://api.bilibili.com/x/polymer/web-dynamic/v1/detail" params = { "id": dynamic_id } logger.info(f"请求动态详情,ID: {dynamic_id}") data = await fetch_dynamic_data(api_url, params) if save_to_db: try: conn = get_connection() except Exception as e: logger.error(f"打开动态数据库失败: {e}") raise HTTPException(status_code=500, detail=f"打开动态数据库失败: {str(e)}") # detail 接口通常返回一个 item data_section = data.get("data", {}) if isinstance(data, dict) else {} item = data_section.get("item") or data_section.get("card") or data_section if isinstance(item, dict): try: id_str = ( item.get("id_str") or item.get("basic", {}).get("id_str") or str(item.get("id") or dynamic_id) ) # 尝试从作者信息解析 host_mid,失败则用 0 host_mid_val = ( item.get("modules", {}) .get("module_author", {}) .get("mid") ) try: host_mid_int = int(host_mid_val) if host_mid_val is not None else 0 except Exception: host_mid_int = 0 # 检查是否有多媒体文件需要下载 base_output_dir = os.path.dirname(get_output_path("__base__")) has_media = False predicted_locals = [] live_predicted_locals = [] if save_media: # 处理普通图片 image_urls = collect_image_urls(item) if image_urls: has_media = True # 只有当包含多媒体文件时才创建文件夹 item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid_int), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) # 预测本地路径 for u in image_urls: predicted_locals.append(os.path.relpath(predict_image_path(u, item_dir), base_output_dir)) # 下载多媒体文件 results = await download_images(image_urls, item_dir) media_records = [] for media_url, local_path, ok in results: if ok: rel_path = os.path.relpath(local_path, base_output_dir) media_records.append((media_url, rel_path, "image")) # 处理实况媒体(live图片+视频) live_media_pairs = collect_live_media_urls(item) if live_media_pairs: has_media = True # 创建文件夹(如果还未创建) if not image_urls: item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid_int), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) live_results = await download_live_media(live_media_pairs, item_dir) for image_url, video_url, image_path, video_path, ok in live_results: if ok: # 将实况媒体路径分别记录 image_rel = os.path.relpath(image_path, base_output_dir) video_rel = os.path.relpath(video_path, base_output_dir) live_predicted_locals.extend([image_rel, video_rel]) # 处理表情 emoji_pairs = collect_emoji_urls(item) if emoji_pairs: has_media = True # 创建文件夹(如果还未创建) if not image_urls and not live_media_pairs: item_dir = os.path.dirname( get_output_path("dynamic", str(host_mid_int), str(id_str), "media") ) os.makedirs(item_dir, exist_ok=True) emoji_results = await download_emojis(emoji_pairs, item_dir) for emoji_url, emoji_path, ok in emoji_results: if ok: # 将表情路径记录到普通媒体中 emoji_rel = os.path.relpath(emoji_path, base_output_dir) predicted_locals.append(emoji_rel) # 保存头像一次(若存在) try: face_url = None modules_raw = item.get("modules") if isinstance(modules_raw, dict): face_url = modules_raw.get("module_author", {}).get("face") elif isinstance(modules_raw, list): for mod in modules_raw: if isinstance(mod, dict) and mod.get("module_type") == "MODULE_TYPE_AUTHOR": face_url = mod.get("module_author", {}).get("user", {}).get("face") or mod.get("module_author", {}).get("face") if face_url: break if not face_url: face_url = item.get("user", {}).get("face") if face_url and host_mid_int: host_dir = os.path.dirname(get_output_path("dynamic", str(host_mid_int), "__host_meta.json")) os.makedirs(host_dir, exist_ok=True) exists = any( name.lower().startswith("face.") for name in os.listdir(host_dir) if os.path.isfile(os.path.join(host_dir, name)) ) if not exists: results = await download_images([face_url], host_dir) for media_url, local_path, ok in results: if ok: _, ext = os.path.splitext(local_path) new_path = os.path.join(host_dir, f"face{ext}") try: if os.path.exists(new_path): os.remove(new_path) except Exception: pass try: os.replace(local_path, new_path) except Exception: pass break except Exception as e: logger.warning(f"保存头像失败(忽略):{e}") # 规范化保存 + 回写预测路径(逗号分隔) try: save_normalized_dynamic_item(conn, host_mid_int, item) if predicted_locals or live_predicted_locals: cursor = conn.cursor() cursor.execute( """ UPDATE dynamic_core SET media_locals = CASE WHEN media_locals IS NULL OR media_locals = '' THEN ? ELSE media_locals END, live_media_locals = CASE WHEN live_media_locals IS NULL OR live_media_locals = '' THEN ? ELSE live_media_locals END, live_media_count = ? WHERE host_mid = ? AND id_str = ? """, ( ",".join(predicted_locals) if predicted_locals else "", ",".join(live_predicted_locals) if live_predicted_locals else "", len(live_predicted_locals), str(host_mid_int), str(id_str), ), ) conn.commit() except Exception as norm_err: logger.warning(f"规范化保存失败(忽略): {norm_err}") except Exception as perr: logger.error(f"保存动态详情失败 dynamic_id={dynamic_id}: {perr}") try: conn.close() except Exception: pass # 直接返回B站API的原始响应数据 return data except HTTPException: raise except Exception as e: logger.error(f"获取动态详情失败: {e}") raise HTTPException(status_code=500, detail=f"获取动态详情失败: {str(e)}") @router.get("/types", summary="获取动态类型说明") async def get_dynamic_types(): """ 获取动态类型的说明信息 """ dynamic_types = { "DYNAMIC_TYPE_NONE": "无类型", "DYNAMIC_TYPE_FORWARD": "转发动态", "DYNAMIC_TYPE_AV": "视频动态", "DYNAMIC_TYPE_PGC": "番剧/影视动态", "DYNAMIC_TYPE_COURSES": "课程动态", "DYNAMIC_TYPE_WORD": "文字动态", "DYNAMIC_TYPE_DRAW": "图片动态", "DYNAMIC_TYPE_ARTICLE": "文章动态", "DYNAMIC_TYPE_MUSIC": "音频动态", "DYNAMIC_TYPE_COMMON_SQUARE": "普通方形动态", "DYNAMIC_TYPE_COMMON_VERTICAL": "普通竖版动态", "DYNAMIC_TYPE_LIVE": "直播动态", "DYNAMIC_TYPE_MEDIALIST": "收藏夹动态", "DYNAMIC_TYPE_COURSES_SEASON": "课程合集动态", "DYNAMIC_TYPE_COURSES_BATCH": "课程批次动态", "DYNAMIC_TYPE_AD": "广告动态", "DYNAMIC_TYPE_APPLET": "小程序动态", "DYNAMIC_TYPE_SUBSCRIPTION": "订阅动态", "DYNAMIC_TYPE_LIVE_RCMD": "直播推荐动态", "DYNAMIC_TYPE_BANNER": "横幅动态", "DYNAMIC_TYPE_UGC_SEASON": "合集动态", "DYNAMIC_TYPE_SUBSCRIPTION_NEW": "新订阅动态" } return {"types": dynamic_types} @router.delete("/space/{host_mid}", summary="删除指定UP的动态数据(文件+数据库)") async def delete_space_data(host_mid: int) -> Dict[str, Any]: """ 删除指定 host_mid 的本地动态数据目录以及数据库中所有关联记录。 - 文件夹: output/dynamic/{host_mid} - 数据库表: dynamic_core / dynamic_author / dynamic_stat / dynamic_topic / major_opus_pics / major_archive_jump_urls """ # 发送停止信号(若存在正在抓取的任务,页级停止) try: ev = _get_or_create_event(host_mid) ev.set() except Exception as e: logger.warning(f"[purge] 发送停止信号失败(忽略) host_mid={host_mid}: {e}") # 定位并删除文件夹 dir_path: Optional[str] = None dir_existed = False dir_deleted = False try: dir_path = os.path.dirname(get_output_path("dynamic", str(host_mid), "__host_meta.json")) dir_existed = os.path.isdir(dir_path) if dir_existed: shutil.rmtree(dir_path, ignore_errors=True) dir_deleted = not os.path.exists(dir_path) except Exception as e: logger.error(f"[purge] 删除目录失败 host_mid={host_mid}: {e}") # 删除数据库记录 try: conn = get_connection() except Exception as e: logger.error(f"[purge] 打开动态数据库失败: {e}") raise HTTPException(status_code=500, detail=f"打开动态数据库失败: {str(e)}") try: db_stats = purge_host(conn, host_mid) finally: try: conn.close() except Exception: pass return { "host_mid": str(host_mid), "dir": { "path": dir_path, "existed": dir_existed, "deleted": dir_deleted, }, "db_deleted": db_stats, }
281677160/openwrt-package
1,523
luci-app-homeproxy/root/etc/homeproxy/scripts/firewall_pre.uc
#!/usr/bin/ucode 'use strict'; import { writefile } from 'fs'; import { cursor } from 'uci'; import { isEmpty, RUN_DIR } from 'homeproxy'; const cfgname = 'homeproxy'; const uci = cursor(); uci.load(cfgname); const routing_mode = uci.get(cfgname, 'config', 'routing_mode') || 'bypass_mainland_china', proxy_mode = uci.get(cfgname, 'config', 'proxy_mode') || 'redirect_tproxy'; let outbound_node, tun_name; if (match(proxy_mode, /tun/)) { if (routing_mode === 'custom') outbound_node = uci.get(cfgname, 'routing', 'default_outbound') || 'nil'; else outbound_node = uci.get(cfgname, 'config', 'main_node') || 'nil'; if (outbound_node !== 'nil') tun_name = uci.get(cfgname, 'infra', 'tun_name') || 'singtun0'; } const server_enabled = uci.get(cfgname, 'server', 'enabled'); let forward = [], input = []; if (tun_name) { push(forward, `oifname ${tun_name} counter accept comment "!${cfgname}: accept tun forward"`); push(input ,`iifname ${tun_name} counter accept comment "!${cfgname}: accept tun input"`); } if (server_enabled === '1') { uci.foreach(cfgname, 'server', (s) => { if (s.enabled !== '1' || s.firewall !== '1') return; let proto = s.network || '{ tcp, udp }'; push(input, `meta l4proto ${proto} th dport ${s.port} counter accept comment "!${cfgname}: accept server ${s['.name']}"`); }); } if (!isEmpty(forward)) writefile(RUN_DIR + '/fw4_forward.nft', join('\n', forward) + '\n'); if (!isEmpty(input)) writefile(RUN_DIR + '/fw4_input.nft', join('\n', input) + '\n');
2977094657/BilibiliHistoryFetcher
6,101
routers/bilibili_history_delete.py
""" B站历史记录删除API 实现B站历史记录的删除功能,支持单条和批量删除 """ from typing import List import requests from fastapi import APIRouter, Query from pydantic import BaseModel, Field from scripts.utils import load_config router = APIRouter() class DeleteHistoryItem(BaseModel): """删除历史记录项目模型""" kid: str = Field(..., description="删除的目标记录,格式为{业务类型}_{目标id}") sync_to_bilibili: bool = Field(True, description="是否同步删除B站服务器上的记录") class BatchDeleteRequest(BaseModel): """批量删除请求模型""" items: List[DeleteHistoryItem] = Field(..., description="要删除的历史记录列表") def get_headers(): """获取请求头""" # 动态读取配置文件,获取最新的SESSDATA current_config = load_config() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer': 'https://www.bilibili.com/', 'Origin': 'https://www.bilibili.com', 'Content-Type': 'application/x-www-form-urlencoded', } # 添加Cookie cookies = [] if 'SESSDATA' in current_config: cookies.append(f"SESSDATA={current_config['SESSDATA']}") if 'bili_jct' in current_config: cookies.append(f"bili_jct={current_config['bili_jct']}") if 'DedeUserID' in current_config: cookies.append(f"DedeUserID={current_config['DedeUserID']}") if cookies: headers['Cookie'] = '; '.join(cookies) return headers @router.delete("/single", summary="删除单条历史记录") async def delete_single_history( kid: str = Query(..., description="删除的目标记录,格式为{业务类型}_{目标id}"), sync_to_bilibili: bool = Query(True, description="是否同步删除B站服务器上的记录") ): """ 删除单条历史记录 - **kid**: 删除的目标记录,格式为{业务类型}_{目标id} - 视频:archive_{稿件bvid} - 直播:live_{直播间id} - 专栏:article_{专栏cvid} - 剧集:pgc_{剧集ssid} - 文集:article-list_{文集rlid} - **sync_to_bilibili**: 是否同步删除B站服务器上的记录 """ try: # 如果需要同步删除B站服务器上的记录 if sync_to_bilibili: # 获取配置 current_config = load_config() bili_jct = current_config.get("bili_jct", "") if not bili_jct: return { "status": "error", "message": "缺少CSRF Token (bili_jct),请先使用QR码登录并确保已正确获取bili_jct" } # 准备请求参数 data = { "kid": kid, "csrf": bili_jct } # 发送请求 headers = get_headers() response = requests.post( "https://api.bilibili.com/x/v2/history/delete", data=data, # 使用form-urlencoded格式 headers=headers ) # 解析响应 result = response.json() if result.get("code") != 0: return { "status": "error", "message": f"删除B站历史记录失败: {result.get('message', '未知错误')}", "code": result.get("code"), "data": result } # 返回成功结果 return { "status": "success", "message": "历史记录删除成功", "data": { "kid": kid, "sync_to_bilibili": sync_to_bilibili } } except Exception as e: return { "status": "error", "message": f"删除历史记录失败: {str(e)}" } @router.delete("/batch", summary="批量删除历史记录") async def batch_delete_history(request: BatchDeleteRequest): """ 批量删除历史记录 - **items**: 要删除的历史记录列表,每个记录包含kid和是否同步删除B站服务器上的记录的标志 """ try: # 获取配置 current_config = load_config() bili_jct = current_config.get("bili_jct", "") if not bili_jct: return { "status": "error", "message": "缺少CSRF Token (bili_jct),请先使用QR码登录并确保已正确获取bili_jct" } # 处理结果 results = [] success_count = 0 error_count = 0 # 需要同步删除B站服务器上的记录的项目 sync_items = [item for item in request.items if item.sync_to_bilibili] # 如果有需要同步删除的记录 if sync_items: # 准备请求参数 - 支持批量删除,用逗号分隔多个kid kids = ",".join([item.kid for item in sync_items]) data = { "kid": kids, "csrf": bili_jct } # 发送请求 headers = get_headers() response = requests.post( "https://api.bilibili.com/x/v2/history/delete", data=data, # 使用form-urlencoded格式 headers=headers ) # 解析响应 result = response.json() if result.get("code") == 0: success_count += len(sync_items) for item in sync_items: results.append({ "kid": item.kid, "sync_to_bilibili": True, "status": "success" }) else: error_count += len(sync_items) error_message = result.get('message', '未知错误') for item in sync_items: results.append({ "kid": item.kid, "sync_to_bilibili": True, "status": "error", "message": error_message }) # 处理不需要同步删除的记录 for item in request.items: if not item.sync_to_bilibili: success_count += 1 results.append({ "kid": item.kid, "sync_to_bilibili": False, "status": "success" }) # 返回结果 return { "status": "success" if error_count == 0 else "partial_success", "message": f"成功删除 {success_count} 条历史记录,失败 {error_count} 条", "data": { "success_count": success_count, "error_count": error_count, "results": results } } except Exception as e: return { "status": "error", "message": f"批量删除历史记录失败: {str(e)}" }
2929004360/ruoyi-sign
2,719
ruoyi-flowable/src/main/resources/mapper/flowable/WfModelMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfModelMapper"> <resultMap type="ActReModel" id="ActReModelResult"> <result property="id" column="ID_"/> <result property="rev" column="REV_"/> <result property="name" column="NAME_"/> <result property="key" column="KEY_"/> <result property="category" column="CATEGORY_"/> <result property="createTime" column="CREATE_TIME_"/> <result property="lastUpdateTime" column="LAST_UPDATE_TIME_"/> <result property="version" column="VERSION_"/> <result property="metaInfo" column="META_INFO_"/> <result property="deploymentId" column="DEPLOYMENT_ID_"/> <result property="editorSourceValueId" column="EDITOR_SOURCE_VALUE_ID_"/> <result property="editorSourceExtraValueId" column="EDITOR_SOURCE_EXTRA_VALUE_ID_"/> <result property="tenantId" column="TENANT_ID_"/> </resultMap> <select id="selectListVo" resultMap="ActReModelResult"> SELECT RES.* from ACT_RE_MODEL RES WHERE RES.VERSION_ = (select max(VERSION_) from ACT_RE_MODEL where KEY_ = RES.KEY_) and ID_ in ( SELECT DISTINCT model_id FROM ( SELECT model_id FROM wf_model_permission WHERE type = '1' AND permission_id in <foreach item="userId" collection="userIdList" open="(" separator="," close=")"> #{userId} </foreach> UNION ALL SELECT model_id FROM wf_model_permission WHERE type = '2' AND permission_id in <foreach item="deptId" collection="deptIdList" open="(" separator="," close=")"> #{deptId} </foreach> ) m ) <if test="modelBo.modelName != null and modelBo.modelName != ''">and NAME_ = #{modelBo.modelName}</if> <if test="modelBo.modelKey != null and modelBo.modelKey != ''">and KEY_ = #{modelBo.modelKey}</if> <if test="modelBo.category != null and modelBo.category != ''">and CATEGORY_ = #{modelBo.category}</if> ORDER BY CREATE_TIME_ DESC </select> <select id="selectList" resultMap="ActReModelResult"> SELECT RES.* from ACT_RE_MODEL RES WHERE RES.VERSION_ = (select max(VERSION_) from ACT_RE_MODEL where KEY_ = RES.KEY_) <if test="modelName != null and modelName != ''">and NAME_ = #{modelName}</if> <if test="modelKey != null and modelKey != ''">and KEY_ = #{modelKey}</if> <if test="category != null and category != ''">and CATEGORY_ = #{category}</if> order by RES.CREATE_TIME_ desc </select> </mapper>
2929004360/ruoyi-sign
3,576
ruoyi-flowable/src/main/resources/mapper/flowable/WfBusinessProcessMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfBusinessProcessMapper"> <resultMap type="WfBusinessProcess" id="WfBusinessProcessResult"> <result property="businessId" column="business_id"/> <result property="processId" column="process_id"/> <result property="businessProcessType" column="business_process_type"/> </resultMap> <sql id="selectWfBusinessProcessVo"> select business_id, process_id, business_process_type from wf_business_process </sql> <select id="selectWfBusinessProcessList" parameterType="WfBusinessProcess" resultMap="WfBusinessProcessResult"> <include refid="selectWfBusinessProcessVo"/> <where> <if test="processId != null and processId != ''">and process_id = #{processId}</if> <if test="businessProcessType != null and businessProcessType != ''">and business_process_type = #{businessProcessType} </if> </where> </select> <select id="selectWfBusinessProcessByBusinessId" parameterType="String" resultMap="WfBusinessProcessResult"> <include refid="selectWfBusinessProcessVo"/> where business_id = #{businessId} </select> <select id="selectWfBusinessProcessByProcessId" parameterType="String" resultMap="WfBusinessProcessResult"> <include refid="selectWfBusinessProcessVo"/> where process_id = #{processId} </select> <select id="selectWfBusinessProcessListByProcessId" resultMap="WfBusinessProcessResult"> <include refid="selectWfBusinessProcessVo"/> where process_id in <foreach item="id" collection="ids" open="(" separator="," close=")"> #{id} </foreach> </select> <insert id="insertWfBusinessProcess" parameterType="WfBusinessProcess"> insert into wf_business_process <trim prefix="(" suffix=")" suffixOverrides=","> <if test="businessId != null">business_id,</if> <if test="processId != null and processId != ''">process_id,</if> <if test="businessProcessType != null">business_process_type,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="businessId != null">#{businessId},</if> <if test="processId != null and processId != ''">#{processId},</if> <if test="businessProcessType != null">#{businessProcessType},</if> </trim> </insert> <update id="updateWfBusinessProcess" parameterType="WfBusinessProcess"> update wf_business_process <trim prefix="SET" suffixOverrides=","> <if test="processId != null and processId != ''">process_id = #{processId},</if> <if test="businessProcessType != null">business_process_type = #{businessProcessType},</if> </trim> where business_id = #{businessId} </update> <delete id="deleteWfBusinessProcessByBusinessId" parameterType="String"> delete from wf_business_process where business_id = #{businessId} and business_process_type = #{type} </delete> <delete id="deleteWfBusinessProcessByBusinessIds" parameterType="String"> delete from wf_business_process where business_id in <foreach item="businessId" collection="array" open="(" separator="," close=")"> #{businessId} </foreach> </delete> </mapper>
2977094657/BilibiliHistoryFetcher
19,736
routers/login.py
import os import time import json import qrcode import requests from fastapi import APIRouter, HTTPException from fastapi.responses import JSONResponse, FileResponse from loguru import logger from scripts.utils import load_config, get_output_path, setup_logger from datetime import datetime from scripts.send_log_email import send_email # 确保日志系统已初始化 setup_logger() router = APIRouter() def get_current_config(): """获取当前配置""" return load_config() def save_cookies(cookies): """保存cookies到配置文件""" try: # 使用绝对路径 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config', 'config.yaml') logger.info(f"配置文件路径: {config_path}") if not os.path.exists(config_path): logger.error(f"配置文件不存在: {config_path}") raise HTTPException( status_code=500, detail="配置文件不存在" ) # 读取现有配置 with open(config_path, 'r', encoding='utf-8') as f: config_data = f.read() logger.info("成功读取配置文件") # 要更新的Cookie字段列表 cookie_fields = ['SESSDATA', 'bili_jct', 'DedeUserID', 'DedeUserID__ckMd5'] lines = config_data.split('\n') updated_fields = set() # 更新已存在的字段 for i, line in enumerate(lines): for field in cookie_fields: if line.strip().startswith(f'{field}:'): if field in cookies: lines[i] = f'{field}: {cookies[field]}' updated_fields.add(field) print(f"更新配置 {field}: {cookies[field]}") break # 添加不存在的字段 for field in cookie_fields: if field in cookies and field not in updated_fields: lines.append(f'{field}: {cookies[field]}') print(f"添加配置 {field}: {cookies[field]}") # 保存更新后的配置 config_data = '\n'.join(lines) with open(config_path, 'w', encoding='utf-8') as f: f.write(config_data) print("配置文件已更新") except Exception as e: print(f"保存cookies时发生错误: {str(e)}") raise HTTPException( status_code=500, detail=f"保存cookies失败: {str(e)}" ) @router.get("/qrcode/generate", summary="生成B站登录二维码") async def generate_qrcode(): """生成二维码登录的URL和密钥""" try: logger.info("开始生成二维码...") # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } # 调用B站API获取二维码URL response = requests.get( 'https://passport.bilibili.com/x/passport-login/web/qrcode/generate', headers=headers, timeout=10 # 添加超时设置 ) logger.info(f"API响应状态码: {response.status_code}") logger.debug(f"API响应内容: {response.text}") # 检查响应状态码 if response.status_code != 200: raise HTTPException( status_code=response.status_code, detail=f"B站API请求失败: {response.text}" ) # 尝试解析JSON响应 try: data = response.json() except json.JSONDecodeError as e: print(f"JSON解析错误: {str(e)}") print(f"响应内容: {response.text}") raise HTTPException( status_code=500, detail=f"解析B站API响应失败: {str(e)}" ) if data.get('code') != 0: raise HTTPException( status_code=400, detail=f"B站API返回错误: {data.get('message', '未知错误')}" ) # 确保返回的数据包含必要的字段 if 'data' not in data or 'url' not in data['data'] or 'qrcode_key' not in data['data']: raise HTTPException( status_code=500, detail="B站API返回的数据格式不正确" ) print("成功获取二维码URL和密钥") # 生成二维码图片 qr = qrcode.QRCode(version=1, box_size=10, border=5) qr.add_data(data['data']['url']) qr.make(fit=True) # 保存二维码图片 img = qr.make_image(fill_color="black", back_color="white") qr_path = get_output_path('temp/qrcode.png') os.makedirs(os.path.dirname(qr_path), exist_ok=True) img.save(qr_path) print("二维码图片已生成") return { "status": "success", "data": { "qrcode_key": data['data']['qrcode_key'], "url": data['data']['url'] } } except requests.RequestException as e: print(f"网络请求错误: {str(e)}") raise HTTPException( status_code=500, detail=f"网络请求失败: {str(e)}" ) except Exception as e: print(f"发生未知错误: {str(e)}") raise HTTPException( status_code=500, detail=f"生成二维码失败: {str(e)}" ) @router.get("/qrcode/image", summary="获取登录二维码图片") async def get_qrcode_image(): """获取生成的二维码图片""" try: print("尝试获取二维码图片...") qr_path = get_output_path('temp/qrcode.png') if not os.path.exists(qr_path): print(f"二维码图片不存在: {qr_path}") raise HTTPException( status_code=404, detail="二维码图片不存在,请先调用 /login/qrcode/generate 接口生成二维码" ) print(f"成功找到二维码图片: {qr_path}") return FileResponse( qr_path, media_type="image/png", filename="qrcode.png" ) except Exception as e: print(f"获取二维码图片时发生错误: {str(e)}") if isinstance(e, HTTPException): raise e raise HTTPException( status_code=500, detail=f"获取二维码图片失败: {str(e)}" ) @router.get("/qrcode/poll", summary="轮询二维码扫描状态") async def poll_scan_status(qrcode_key: str): """轮询扫码状态""" try: print(f"开始轮询扫码状态,qrcode_key: {qrcode_key}") if not qrcode_key: raise HTTPException( status_code=400, detail="缺少必要的qrcode_key参数" ) # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } # 调用B站API检查扫码状态 try: response = requests.get( 'https://passport.bilibili.com/x/passport-login/web/qrcode/poll', params={'qrcode_key': qrcode_key}, headers=headers, timeout=10 ) print(f"API响应状态码: {response.status_code}") print(f"API响应内容: {response.text}") print(f"响应头: {response.headers}") print(f"响应Cookies: {response.cookies}") # 检查响应状态码 if response.status_code != 200: raise HTTPException( status_code=response.status_code, detail=f"B站API请求失败: {response.text}" ) # 尝试解析JSON响应 try: data = response.json() except json.JSONDecodeError as e: print(f"JSON解析错误: {str(e)}") print(f"响应内容: {response.text}") raise HTTPException( status_code=500, detail=f"解析B站API响应失败: {str(e)}" ) # 检查API返回的code if data.get('code') != 0: error_message = data.get('message', '未知错误') print(f"B站API返回错误: {error_message}") return { "status": "error", "data": { "code": data.get('code'), "message": error_message, "timestamp": int(time.time()) } } scan_data = data.get('data', {}) print(f"扫码状态数据: {scan_data}") # 如果登录成功,保存cookies if scan_data.get('code') == 0: print("登录成功,保存cookies...") # 从set-cookie头和响应cookies中提取信息 cookies = {} # 从响应cookie中获取 for cookie in response.cookies: cookies[cookie.name] = cookie.value print(f"从响应cookies获取到: {cookie.name}={cookie.value}") # 从响应头中获取(有些Cookie可能在响应头的set-cookie中,但不在cookies中) if 'set-cookie' in response.headers: # 修复: 使用正确的方法获取set-cookie头 # CaseInsensitiveDict不支持getlist方法 set_cookie_header = response.headers.get('set-cookie', '') print(f"从响应头获取到set-cookie: {set_cookie_header}") # 如果是单个cookie if set_cookie_header: parts = set_cookie_header.split(';')[0].split('=', 1) if len(parts) == 2: name, value = parts cookies[name.strip()] = value.strip() print(f"解析出cookie: {name.strip()}={value.strip()}") # 可能多个cookie在不同的Set-Cookie头中 # 遍历所有响应头来查找所有的Set-Cookie for key, value in response.headers.items(): if key.lower() == 'set-cookie': cookie_parts = value.split(';')[0].split('=', 1) if len(cookie_parts) == 2: cookie_name, cookie_value = cookie_parts cookies[cookie_name.strip()] = cookie_value.strip() print(f"从头部遍历解析出cookie: {cookie_name.strip()}={cookie_value.strip()}") # 如果响应数据中包含cookie_info字段(TV端QR登录模式),从中提取cookies if 'cookie_info' in scan_data: cookie_info = scan_data.get('cookie_info', {}) for cookie in cookie_info.get('cookies', []): if 'name' in cookie and 'value' in cookie: cookies[cookie['name']] = cookie['value'] print(f"从cookie_info获取到: {cookie['name']}={cookie['value']}") # 如果必要的cookie不在响应中,从url中解析 if 'url' in scan_data and scan_data['url'] and ('SESSDATA' not in cookies or 'bili_jct' not in cookies): url = scan_data['url'] print(f"从url中解析cookie: {url}") if '?' in url: query = url.split('?', 1)[1] for param in query.split('&'): if '=' in param: name, value = param.split('=', 1) if name in ['DedeUserID', 'DedeUserID__ckMd5', 'SESSDATA', 'bili_jct']: cookies[name] = value print(f"从URL解析出cookie: {name}={value}") # 记录找到的所有cookie print(f"找到的所有cookies: {cookies}") # 检查是否有必要的鉴权字段 if 'SESSDATA' not in cookies: print("警告: 未获取到SESSDATA") if 'bili_jct' not in cookies: print("警告: 未获取到bili_jct (CSRF Token)") # 保存cookies save_cookies(cookies) print("cookies已保存") # 记录获取到的鉴权信息 auth_info = { "SESSDATA": cookies.get("SESSDATA", "未获取"), "bili_jct": cookies.get("bili_jct", "未获取"), "DedeUserID": cookies.get("DedeUserID", "未获取"), "DedeUserID__ckMd5": cookies.get("DedeUserID__ckMd5", "未获取") } print(f"鉴权信息摘要: {auth_info}") return { "status": "success", "data": { "code": scan_data.get('code', 86101), # 默认未扫码 "message": scan_data.get('message', '等待扫码'), "timestamp": int(time.time()) } } except requests.RequestException as e: print(f"请求B站API时发生错误: {str(e)}") raise HTTPException( status_code=500, detail=f"网络请求失败: {str(e)}" ) except Exception as e: print(f"发生未知错误: {str(e)}") if isinstance(e, HTTPException): raise e raise HTTPException( status_code=500, detail=f"轮询扫码状态失败: {str(e)}" ) @router.post("/logout", summary="退出登录") async def logout(): """退出登录,清空SESSDATA""" try: logger.info("开始退出登录...") # 使用绝对路径 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'config', 'config.yaml') logger.info(f"配置文件路径: {config_path}") if not os.path.exists(config_path): logger.error(f"配置文件不存在: {config_path}") raise HTTPException( status_code=500, detail="配置文件不存在" ) # 读取现有配置 with open(config_path, 'r', encoding='utf-8') as f: config_data = f.read() logger.info("成功读取配置文件") # 清空SESSDATA lines = config_data.split('\n') new_lines = [] for line in lines: if line.strip().startswith('SESSDATA:'): new_lines.append('SESSDATA: ""') else: new_lines.append(line) new_config = '\n'.join(new_lines) # 保存更新后的配置 with open(config_path, 'w', encoding='utf-8') as f: f.write(new_config) print("SESSDATA已清空") return { "status": "success", "message": "已成功退出登录" } except Exception as e: print(f"退出登录时发生错误: {str(e)}") raise HTTPException( status_code=500, detail=f"退出登录失败: {str(e)}" ) @router.get("/check", summary="检查登录状态") async def check_login_status(): """检查当前登录状态""" try: print("检查登录状态...") # 每次检查时重新加载配置 current_config = get_current_config() # 从配置文件中获取SESSDATA if not current_config.get('SESSDATA'): return JSONResponse( status_code=200, content={ "code": -101, "message": "未登录", "ttl": 1, "data": None } ) # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Cookie': f'SESSDATA={current_config["SESSDATA"]}' } # 调用B站API验证登录状态 response = requests.get( 'https://api.bilibili.com/x/web-interface/nav', headers=headers, timeout=10 ) print(f"API响应状态码: {response.status_code}") # 直接返回B站API的原始响应数据 return JSONResponse( status_code=200, content=response.json() ) except Exception as e: print(f"检查登录状态时发生错误: {str(e)}") raise HTTPException( status_code=500, detail=f"检查登录状态失败: {str(e)}" ) @router.get("/check-and-notify", summary="检查SESSDATA并在失效时发送邮件") async def check_and_notify(): """检查SESSDATA有效性;若失效则发送邮件告警(状态变为失效时仅告警一次)""" try: print("检查SESSDATA并发送告警(如失效)...") # 获取配置与SESSDATA current_config = get_current_config() sessdata = current_config.get('SESSDATA', '') headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Cookie': f'SESSDATA={sessdata}' } valid = False detail = {} error_message = None if not sessdata: error_message = "SESSDATA 未配置或为空" else: try: resp = requests.get( 'https://api.bilibili.com/x/web-interface/nav', headers=headers, timeout=10 ) status_code = resp.status_code print(f"API响应状态码: {status_code}") try: data = resp.json() if status_code == 200 else {} except Exception: data = {} detail = data # code == 0 表示已登录有效 if status_code == 200 and isinstance(data, dict) and data.get('code') == 0: valid = True else: err_msg = "" if isinstance(data, dict): err_msg = data.get('message', '') or (data.get('data', {}) or {}).get('message', '') if not err_msg: err_msg = f"HTTP {status_code}" error_message = f"登录失效或异常: {err_msg}" except Exception as e: error_message = f"请求验证接口失败: {str(e)}" # 状态文件(用于去重,仅在状态从有效->失效时告警一次) state_path = get_output_path('state/sessdata_monitor.json') last_alert_ts = 0 last_status = "unknown" try: if os.path.exists(state_path): with open(state_path, 'r', encoding='utf-8') as f: st = json.load(f) last_alert_ts = st.get('last_alert_ts', 0) last_status = st.get('last_status', 'unknown') except Exception: pass now_ts = int(time.time()) notified = False if valid: # 更新状态为有效 try: os.makedirs(os.path.dirname(state_path), exist_ok=True) with open(state_path, 'w', encoding='utf-8') as f: json.dump({ 'last_status': 'valid', 'last_valid_ts': now_ts }, f, ensure_ascii=False, indent=2) except Exception as e: print(f"写入状态文件失败: {e}") return { "status": "success", "message": "SESSDATA 有效", "data": {"valid": True, "detail": detail} } # 若失效则发送邮件(仅当上次状态不是 invalid 时触发) if last_status != 'invalid': subject = "B站登录状态失效,请尽快重新登录" body = "\n".join([ f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", f"原因: {error_message or '未知'}", f"原始返回: {json.dumps(detail, ensure_ascii=False) if isinstance(detail, dict) else str(detail)}" ]) try: send_res = await send_email(subject=subject, content=body) print(f"告警邮件发送结果: {send_res}") notified = (send_res or {}).get("status") == "success" except Exception as e: print(f"发送告警邮件失败: {e}") # 更新为失效状态 try: os.makedirs(os.path.dirname(state_path), exist_ok=True) with open(state_path, 'w', encoding='utf-8') as f: json.dump({ 'last_status': 'invalid', 'last_alert_ts': now_ts, 'last_error': error_message }, f, ensure_ascii=False, indent=2) except Exception as e: print(f"写入状态文件失败: {e}") else: print("状态已为失效,跳过重复告警") return { "status": "success", "message": "SESSDATA 已失效" + ("(已发送邮件)" if notified else "(未重复发送)"), "data": {"valid": False, "notified": notified, "detail": detail} } except Exception as e: print(f"检查与告警流程失败: {str(e)}") raise HTTPException( status_code=500, detail=f"检查与告警流程失败: {str(e)}" )
2977094657/BilibiliHistoryFetcher
1,811
routers/comment.py
from fastapi import APIRouter, HTTPException, Query from typing import Optional from scripts.comment_fetcher import fetch_and_save_comments, get_user_comments from enum import Enum router = APIRouter() class CommentType(str, Enum): ALL = "all" ROOT = "root" REPLY = "reply" @router.post("/fetch/{uid}", summary="获取用户评论") async def fetch_user_comments(uid: str): """ 获取并保存用户的评论数据 Args: uid: 用户ID Returns: dict: 包含操作结果、评论总数和最新评论时间的字典 """ try: result = fetch_and_save_comments(uid) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @router.get("/query/{uid}", summary="查询用户评论") async def query_user_comments( uid: str, page: int = Query(1, description="页码,从1开始"), page_size: int = Query(20, description="每页数量"), comment_type: CommentType = Query(CommentType.ALL, description="评论类型:all-全部, root-一级评论, reply-二级评论"), keyword: Optional[str] = Query(None, description="关键词,用于模糊匹配评论内容"), type_filter: Optional[int] = Query(None, description="评论类型筛选,例如:1(视频评论),17(动态评论)等") ): """ 查询用户的评论数据,如果数据库中没有该用户的数据会自动获取 Args: uid: 用户ID page: 页码,从1开始 page_size: 每页数量 comment_type: 评论类型,可选值:all(全部), root(一级评论), reply(二级评论) keyword: 关键词,用于模糊匹配评论内容 type_filter: 评论类型筛选,例如:1(视频评论),17(动态评论)等 Returns: dict: 包含评论列表和分页信息的字典 """ try: result = get_user_comments( uid=uid, page=page, page_size=page_size, comment_type=comment_type, keyword=keyword or "", comment_type_filter=type_filter ) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
2929004360/ruoyi-sign
3,083
ruoyi-flowable/src/main/resources/mapper/flowable/WfModelAssociationTemplateMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfModelAssociationTemplateMapper"> <resultMap type="WfModelAssociationTemplate" id="WfModelAssociationTemplateResult"> <result property="modelTemplateId" column="model_template_id" /> <result property="modelId" column="model_id" /> </resultMap> <sql id="selectWfModelAssociationTemplateVo"> select model_template_id, model_id from wf_model_association_template </sql> <select id="selectWfModelAssociationTemplateList" parameterType="WfModelAssociationTemplate" resultMap="WfModelAssociationTemplateResult"> <include refid="selectWfModelAssociationTemplateVo"/> <where> <if test="modelTemplateId != null and modelTemplateId != ''"> and model_template_id = #{modelTemplateId}</if> <if test="modelId != null and modelId != ''"> and model_id = #{modelId}</if> </where> </select> <select id="selectWfModelAssociationTemplateByModelTemplateId" parameterType="String" resultMap="WfModelAssociationTemplateResult"> <include refid="selectWfModelAssociationTemplateVo"/> where model_template_id = #{modelTemplateId} </select> <insert id="insertWfModelAssociationTemplate" parameterType="WfModelAssociationTemplate"> insert into wf_model_association_template <trim prefix="(" suffix=")" suffixOverrides=","> <if test="modelTemplateId != null and modelTemplateId != ''">model_template_id,</if> <if test="modelId != null and modelId != ''">model_id,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="modelTemplateId != null and modelTemplateId != ''">#{modelTemplateId},</if> <if test="modelId != null and modelId != ''">#{modelId},</if> </trim> </insert> <update id="updateWfModelAssociationTemplate" parameterType="WfModelAssociationTemplate"> update wf_model_association_template <trim prefix="SET" suffixOverrides=","> <if test="modelId != null and modelId != ''">model_id = #{modelId},</if> </trim> where model_template_id = #{modelTemplateId} </update> <delete id="deleteWfModelAssociationTemplateByModelTemplateId" parameterType="String"> delete from wf_model_association_template where model_template_id = #{modelTemplateId} </delete> <delete id="deleteWfModelAssociationTemplateByModelTemplateIds" parameterType="String"> delete from wf_model_association_template where model_template_id in <foreach item="modelTemplateId" collection="array" open="(" separator="," close=")"> #{modelTemplateId} </foreach> </delete> <delete id="deleteWfModelAssociationTemplate"> delete from wf_model_association_template where model_template_id = #{modelTemplateId} and model_id = #{modelId} </delete> </mapper>
2929004360/ruoyi-sign
3,966
ruoyi-flowable/src/main/resources/mapper/flowable/WfFlowMenuMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfFlowMenuMapper"> <resultMap type="WfFlowMenu" id="WfFlowMenuResult"> <result property="flowMenuId" column="flow_menu_id" /> <result property="menuId" column="menu_id" /> <result property="name" column="name" /> <result property="create" column="create" /> <result property="view" column="view" /> <result property="createTime" column="create_time" /> <result property="updateTime" column="update_time" /> </resultMap> <sql id="selectWfFlowMenuVo"> select flow_menu_id, menu_id, name, `create`, `view`, create_time, update_time from wf_flow_menu </sql> <select id="selectWfFlowMenuList" parameterType="WfFlowMenu" resultMap="WfFlowMenuResult"> <include refid="selectWfFlowMenuVo"/> <where> <if test="menuId != null and menuId != ''"> and menu_id = #{menuId}</if> <if test="name != null and name != ''"> and name like concat('%', #{name}, '%')</if> <if test="create != null and create != ''"> and `create` = #{create}</if> <if test="view != null and view != ''"> and `view` = #{view}</if> </where> </select> <select id="selectWfFlowMenuByFlowMenuId" parameterType="String" resultMap="WfFlowMenuResult"> <include refid="selectWfFlowMenuVo"/> where flow_menu_id = #{flowMenuId} </select> <select id="getWfFlowMenuInfo" resultMap="WfFlowMenuResult"> <include refid="selectWfFlowMenuVo"/> where menu_id = #{menuId} </select> <insert id="insertWfFlowMenu" parameterType="WfFlowMenu"> insert into wf_flow_menu <trim prefix="(" suffix=")" suffixOverrides=","> <if test="flowMenuId != null">flow_menu_id,</if> <if test="menuId != null and menuId != ''">menu_id,</if> <if test="name != null">`name`,</if> <if test="create != null and create != ''">`create`,</if> <if test="view != null">`view`,</if> <if test="createTime != null">create_time,</if> <if test="updateTime != null">update_time,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="flowMenuId != null">#{flowMenuId},</if> <if test="menuId != null and menuId != ''">#{menuId},</if> <if test="name != null">#{name},</if> <if test="create != null and create != ''">#{create},</if> <if test="view != null">#{view},</if> <if test="createTime != null">#{createTime},</if> <if test="updateTime != null">#{updateTime},</if> </trim> </insert> <update id="updateWfFlowMenu" parameterType="WfFlowMenu"> update wf_flow_menu <trim prefix="SET" suffixOverrides=","> <if test="menuId != null and menuId != ''">menu_id = #{menuId},</if> <if test="name != null">`name` = #{name},</if> <if test="create != null and create != ''">`create` = #{create},</if> <if test="view != null">`view` = #{view},</if> <if test="createTime != null">create_time = #{createTime},</if> <if test="updateTime != null">update_time = #{updateTime},</if> </trim> where flow_menu_id = #{flowMenuId} </update> <delete id="deleteWfFlowMenuByFlowMenuId" parameterType="String"> delete from wf_flow_menu where flow_menu_id = #{flowMenuId} </delete> <delete id="deleteWfFlowMenuByFlowMenuIds" parameterType="String"> delete from wf_flow_menu where flow_menu_id in <foreach item="flowMenuId" collection="array" open="(" separator="," close=")"> #{flowMenuId} </foreach> </delete> </mapper>
281677160/openwrt-package
4,960
luci-app-homeproxy/root/etc/homeproxy/scripts/homeproxy.uc
/* * SPDX-License-Identifier: GPL-2.0-only * * Copyright (C) 2023 ImmortalWrt.org */ import { mkstemp } from 'fs'; import { urldecode_params } from 'luci.http'; /* Global variables start */ export const HP_DIR = '/etc/homeproxy'; export const RUN_DIR = '/var/run/homeproxy'; /* Global variables end */ /* Utilities start */ /* Kanged from luci-app-commands */ export function shellQuote(s) { return `'${replace(s, "'", "'\\''")}'`; }; export function isBinary(str) { for (let off = 0, byte = ord(str); off < length(str); byte = ord(str, ++off)) if (byte <= 8 || (byte >= 14 && byte <= 31)) return true; return false; }; export function executeCommand(...args) { let outfd = mkstemp(); let errfd = mkstemp(); const exitcode = system(`${join(' ', args)} >&${outfd.fileno()} 2>&${errfd.fileno()}`); outfd.seek(0); errfd.seek(0); const stdout = outfd.read(1024 * 512) ?? ''; const stderr = errfd.read(1024 * 512) ?? ''; outfd.close(); errfd.close(); const binary = isBinary(stdout); return { command: join(' ', args), stdout: binary ? null : stdout, stderr, exitcode, binary }; }; export function getTime(epoch) { const local_time = localtime(epoch); return replace(replace(sprintf( '%d-%2d-%2d@%2d:%2d:%2d', local_time.year, local_time.mon, local_time.mday, local_time.hour, local_time.min, local_time.sec ), ' ', '0'), '@', ' '); }; export function wGET(url, ua) { if (!url || type(url) !== 'string') return null; if (!ua) ua = 'Wget/1.21 (HomeProxy, like v2rayN)'; const output = executeCommand(`/usr/bin/wget -qO- --user-agent ${shellQuote(ua)} --timeout=10 ${shellQuote(url)}`) || {}; return trim(output.stdout); }; /* Utilities end */ /* String helper start */ export function isEmpty(res) { return !res || res === 'nil' || (type(res) in ['array', 'object'] && length(res) === 0); }; export function strToBool(str) { return (str === '1') || null; }; export function strToInt(str) { return !isEmpty(str) ? (int(str) || null) : null; }; export function strToTime(str) { return !isEmpty(str) ? (str + 's') : null; }; export function removeBlankAttrs(res) { let content; if (type(res) === 'object') { content = {}; map(keys(res), (k) => { if (type(res[k]) in ['array', 'object']) content[k] = removeBlankAttrs(res[k]); else if (res[k] !== null && res[k] !== '') content[k] = res[k]; }); } else if (type(res) === 'array') { content = []; map(res, (k, i) => { if (type(k) in ['array', 'object']) push(content, removeBlankAttrs(k)); else if (k !== null && k !== '') push(content, k); }); } else return res; return content; }; export function validateHostname(hostname) { return (match(hostname, /^[a-zA-Z0-9_]+$/) != null || (match(hostname, /^[a-zA-Z0-9_][a-zA-Z0-9_%-.]*[a-zA-Z0-9]$/) && match(hostname, /[^0-9.]/))); }; export function validation(datatype, data) { if (!datatype || !data) return null; const ret = system(`/sbin/validate_data ${shellQuote(datatype)} ${shellQuote(data)} 2>/dev/null`); return (ret === 0); }; /* String helper end */ /* String parser start */ export function decodeBase64Str(str) { if (isEmpty(str)) return null; str = trim(str); str = replace(str, '_', '/'); str = replace(str, '-', '+'); const padding = length(str) % 4; if (padding) str = str + substr('====', padding); return b64dec(str); }; export function parseURL(url) { if (type(url) !== 'string') return null; const services = { http: '80', https: '443' }; const objurl = {}; objurl.href = url; url = replace(url, /#(.+)$/, (_, val) => { objurl.hash = val; return ''; }); url = replace(url, /^(\w[A-Za-z0-9\+\-\.]+):/, (_, val) => { objurl.protocol = val; return ''; }); url = replace(url, /\?(.+)/, (_, val) => { objurl.search = val; objurl.searchParams = urldecode_params(val); return ''; }); url = replace(url, /^\/\/([^\/]+)/, (_, val) => { val = replace(val, /^([^@]+)@/, (_, val) => { objurl.userinfo = val; return ''; }); val = replace(val, /:(\d+)$/, (_, val) => { objurl.port = val; return ''; }); if (validation('ip4addr', val) || validation('ip6addr', replace(val, /\[|\]/g, '')) || validation('hostname', val)) objurl.hostname = val; return ''; }); objurl.pathname = url || '/'; if (!objurl.protocol || !objurl.hostname) return null; if (objurl.userinfo) { objurl.userinfo = replace(objurl.userinfo, /:(.+)$/, (_, val) => { objurl.password = val; return ''; }); if (match(objurl.userinfo, /^[A-Za-z0-9\+\-\_\.]+$/)) { objurl.username = objurl.userinfo; delete objurl.userinfo; } else { delete objurl.userinfo; delete objurl.password; } }; if (!objurl.port) objurl.port = services[objurl.protocol]; objurl.host = objurl.hostname + (objurl.port ? `:${objurl.port}` : ''); objurl.origin = `${objurl.protocol}://${objurl.host}`; return objurl; }; /* String parser end */
2929004360/ruoyi-sign
2,491
ruoyi-flowable/src/main/resources/mapper/flowable/WfDeployMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfDeployMapper"> <resultMap type="Deploy" id="DeployResultVo"> <result property="id" column="ID_"/> <result property="rev" column="REV_"/> <result property="category" column="CATEGORY_"/> <result property="name" column="NAME_"/> <result property="key" column="KEY_"/> <result property="version" column="VERSION_"/> <result property="deploymentId" column="DEPLOYMENT_ID_"/> <result property="resourceName" column="RESOURCE_NAME_"/> <result property="dgrmResourceName" column="DGRM_RESOURCE_NAME_"/> <result property="description" column="DESCRIPTION_"/> <result property="hasStartFormKey" column="HAS_START_FORM_KEY_"/> <result property="hasGraphicalNotation" column="HAS_GRAPHICAL_NOTATIO"/> <result property="suspensionState" column="SUSPENSION_STATE_"/> <result property="tenantId" column="TENANT_ID_"/> <result property="engineVersion" column="ENGINE_VERSION_"/> <result property="derivedFrom" column="DERIVED_FROM_"/> <result property="derivedFromRoot" column="DERIVED_FROM_ROOT_"/> <result property="derivedVersion" column="DERIVED_VERSION_"/> </resultMap> <select id="selectWfDeployList" resultMap="DeployResultVo"> SELECT RES.* from ACT_RE_PROCDEF RES WHERE RES.VERSION_ = ( select max(VERSION_) from ACT_RE_PROCDEF where KEY_ = RES.KEY_ and ( (TENANT_ID_ IS NOT NULL and TENANT_ID_ = RES.TENANT_ID_) or (TENANT_ID_ IS NULL and RES.TENANT_ID_ IS NULL) ) ) <if test="procdefIdList != null and procdefIdList.size() > 0"> AND DEPLOYMENT_ID_ IN <foreach item="procdefId" collection="procdefIdList" open="(" separator="," close=")"> #{procdefId} </foreach> </if> <if test="processQuery.processName != null and processQuery.processName != ''">and NAME_ = #{processQuery.processName}</if> <if test="processQuery.category != null and processQuery.category != ''">and CATEGORY_ = #{processQuery.category}</if> <if test="processQuery.state != null and processQuery.state != ''">and SUSPENSION_STATE_ = #{processQuery.state}</if> order by RES.KEY_ asc </select> </mapper>
2929004360/ruoyi-sign
5,067
ruoyi-flowable/src/main/resources/mapper/flowable/WfModelPermissionMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfModelPermissionMapper"> <resultMap type="WfModelPermission" id="WfModelPermissionResult"> <result property="modelPermissionId" column="model_permission_id"/> <result property="modelId" column="model_id"/> <result property="permissionId" column="permission_id"/> <result property="name" column="name"/> <result property="type" column="type"/> <result property="createTime" column="create_time"/> <result property="updateTime" column="update_time"/> </resultMap> <sql id="selectWfModelPermissionVo"> select model_permission_id, model_id, permission_id, name, type, create_time, update_time from wf_model_permission </sql> <select id="selectWfModelPermissionList" resultMap="WfModelPermissionResult"> <include refid="selectWfModelPermissionVo"/> <where> <if test="wfModelPermission.modelId != null and wfModelPermission.modelId != ''">and model_id = #{wfModelPermission.modelId}</if> <if test="wfModelPermission.name != null and wfModelPermission.name != ''">and `name` like concat('%', #{wfModelPermission.name}, '%')</if> <if test="wfModelPermission.type != null and wfModelPermission.type != ''">and `type` = #{wfModelPermission.type}</if> <if test="permissionIdList != null and permissionIdList.size() > 0"> and permission_id in <foreach item="permissionId" collection="permissionIdList" open="(" separator="," close=")"> #{permissionId} </foreach> </if> </where> </select> <select id="selectWfModelPermissionByModelPermissionId" parameterType="String" resultMap="WfModelPermissionResult"> <include refid="selectWfModelPermissionVo"/> where model_permission_id = #{modelPermissionId} </select> <insert id="insertWfModelPermission" parameterType="WfModelPermission"> insert into wf_model_permission <trim prefix="(" suffix=")" suffixOverrides=","> <if test="modelPermissionId != null">model_permission_id,</if> <if test="modelId != null and modelId != ''">model_id,</if> <if test="permissionId != null">permission_id,</if> <if test="name != null">name,</if> <if test="type != null">type,</if> <if test="createTime != null">create_time,</if> <if test="updateTime != null">update_time,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="modelPermissionId != null">#{modelPermissionId},</if> <if test="modelId != null and modelId != ''">#{modelId},</if> <if test="permissionId != null">#{permissionId},</if> <if test="name != null">#{name},</if> <if test="type != null">#{type},</if> <if test="createTime != null">#{createTime},</if> <if test="updateTime != null">#{updateTime},</if> </trim> </insert> <insert id="insertWfModelPermissionList"> INSERT INTO wf_model_permission ( model_permission_id, model_id, permission_id, name, type, create_time, update_time ) VALUES <foreach collection="list" separator="," item="item"> (#{item.modelPermissionId},#{item.modelId},#{item.permissionId},#{item.name},#{item.type},#{item.createTime},#{item.updateTime}) </foreach> </insert> <update id="updateWfModelPermission" parameterType="WfModelPermission"> update wf_model_permission <trim prefix="SET" suffixOverrides=","> <if test="modelId != null and modelId != ''">model_id = #{modelId},</if> <if test="permissionId != null">permission_id = #{permissionId},</if> <if test="name != null">name = #{name},</if> <if test="type != null">type = #{type},</if> <if test="createTime != null">create_time = #{createTime},</if> <if test="updateTime != null">update_time = #{updateTime},</if> </trim> where model_permission_id = #{modelPermissionId} </update> <delete id="deleteWfModelPermissionByModelPermissionId" parameterType="String"> delete from wf_model_permission where model_permission_id = #{modelPermissionId} </delete> <delete id="deleteWfModelPermissionByModelPermissionIds" parameterType="String"> delete from wf_model_permission where model_permission_id in <foreach item="modelPermissionId" collection="array" open="(" separator="," close=")"> #{modelPermissionId} </foreach> </delete> <delete id="deleteWfModelPermissionByModelId"> delete from wf_model_permission where model_id = #{modelId} </delete> </mapper>
2977094657/BilibiliHistoryFetcher
4,722
routers/categories.py
import sqlite3 from fastapi import APIRouter from scripts.init_categories import init_categories from scripts.utils import get_output_path, load_config router = APIRouter() def get_db(): """获取数据库连接""" config = load_config() db_path = get_output_path(config['db_file']) return sqlite3.connect(db_path) def ensure_table_exists(): """确保分类表存在,如果不存在则初始化""" try: conn = get_db() cursor = conn.cursor() # 检查表是否存在 cursor.execute(''' SELECT name FROM sqlite_master WHERE type='table' AND name='video_categories' ''') if not cursor.fetchone(): print("分类表不存在,正在初始化...") init_categories() print("分类表初始化完成") except sqlite3.Error as e: print(f"检查表存在时发生错误: {e}") finally: if conn: conn.close() @router.post("/init", summary="初始化视频分类数据") async def initialize_categories(): """初始化视频分类数据""" try: init_categories() return { "status": "success", "message": "视频分类表初始化成功" } except Exception as e: return { "status": "error", "message": f"初始化失败: {str(e)}" } @router.get("/categories", summary="获取所有分类信息") async def get_categories(): """获取所有分类信息""" try: # 确保表存在 ensure_table_exists() conn = get_db() cursor = conn.cursor() # 查询所有分类 cursor.execute(''' SELECT main_category, sub_category, alias, tid, image FROM video_categories ORDER BY main_category, sub_category ''') # 构建分类树 categories = {} for row in cursor.fetchall(): main_cat, sub_cat, alias, tid, image = row if main_cat not in categories: categories[main_cat] = { "name": main_cat, "image": image, "sub_categories": [] } # 只有当子分类名称不等于主分类名称时才添加 if sub_cat != main_cat: categories[main_cat]["sub_categories"].append({ "name": sub_cat, "alias": alias, "tid": tid }) # 打印结果 print("\n=== 分类数据 ===") print(f"主分类数量: {len(categories)}") for main_cat, data in categories.items(): print(f"{main_cat}: {len(data['sub_categories'])} 个子分类") print("===============\n") return { "status": "success", "data": list(categories.values()) } except sqlite3.Error as e: error_msg = f"数据库错误: {str(e)}" print(f"=== 错误 ===\n{error_msg}\n===========") return {"status": "error", "message": error_msg} finally: if conn: conn.close() @router.get("/main-categories", summary="获取所有主分类") async def get_main_categories(): """获取所有主分类""" try: # 确保表存在 ensure_table_exists() conn = get_db() cursor = conn.cursor() cursor.execute(''' SELECT DISTINCT main_category, image FROM video_categories ORDER BY main_category ''') categories = [] for row in cursor.fetchall(): categories.append({ "name": row[0], "image": row[1] }) return { "status": "success", "data": categories } except sqlite3.Error as e: return {"status": "error", "message": f"数据库错误: {str(e)}"} finally: if conn: conn.close() @router.get("/sub-categories/{main_category}", summary="获取指定主分类下的所有子分类") async def get_sub_categories(main_category: str): """获取指定主分类下的所有子分类""" try: # 确保表存在 ensure_table_exists() conn = get_db() cursor = conn.cursor() cursor.execute(''' SELECT sub_category, alias, tid FROM video_categories WHERE main_category = ? AND sub_category != main_category ORDER BY sub_category ''', (main_category,)) categories = [] for row in cursor.fetchall(): categories.append({ "name": row[0], "alias": row[1], "tid": row[2] }) return { "status": "success", "data": categories } except sqlite3.Error as e: return {"status": "error", "message": f"数据库错误: {str(e)}"} finally: if conn: conn.close()
2977094657/BilibiliHistoryFetcher
1,157
routers/send_log.py
from datetime import datetime from typing import Optional from fastapi import APIRouter, Body from scripts.send_log_email import send_email, get_task_execution_logs router = APIRouter() @router.post("/send-email", summary="发送日志邮件") async def send_log_email( subject: str = Body(..., description="邮件主题"), content: Optional[str] = Body(None, description="邮件内容,如果为None则发送当前任务执行的日志内容"), to_email: Optional[str] = Body(None, description="收件人邮箱,不填则使用配置文件中的默认收件人") ): """发送日志邮件""" try: # 如果没有提供内容,则获取任务执行期间的日志 if content is None: content = get_task_execution_logs() if not content or content == "未找到任务执行记录": content = "当前没有任务执行记录" # 格式化内容,添加时间戳 formatted_content = f""" 时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} === 执行日志 === {content} ============= """ result = await send_email( subject=subject, content=formatted_content, to_email=to_email ) return {"status": "success", "message": "邮件发送成功"} except Exception as e: return {"status": "error", "message": f"邮件发送失败: {str(e)}"}
2929004360/ruoyi-sign
2,683
ruoyi-flowable/src/main/resources/mapper/flowable/WfProcessMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfProcessMapper"> <resultMap type="Deploy" id="DeployResultVo"> <result property="id" column="ID_"/> <result property="rev" column="REV_"/> <result property="category" column="CATEGORY_"/> <result property="name" column="NAME_"/> <result property="key" column="KEY_"/> <result property="version" column="VERSION_"/> <result property="deploymentId" column="DEPLOYMENT_ID_"/> <result property="resourceName" column="RESOURCE_NAME_"/> <result property="dgrmResourceName" column="DGRM_RESOURCE_NAME_"/> <result property="description" column="DESCRIPTION_"/> <result property="hasStartFormKey" column="HAS_START_FORM_KEY_"/> <result property="hasGraphicalNotation" column="HAS_GRAPHICAL_NOTATIO"/> <result property="suspensionState" column="SUSPENSION_STATE_"/> <result property="tenantId" column="TENANT_ID_"/> <result property="engineVersion" column="ENGINE_VERSION_"/> <result property="derivedFrom" column="DERIVED_FROM_"/> <result property="derivedFromRoot" column="DERIVED_FROM_ROOT_"/> <result property="derivedVersion" column="DERIVED_VERSION_"/> <result property="formType" column="form_type"/> <result property="formCreatePath" column="form_create_path"/> </resultMap> <select id="selectProcessList" resultMap="DeployResultVo"> SELECT RES.*, m.form_type, m.form_create_path from ACT_RE_PROCDEF RES INNER JOIN wf_model_procdef m ON RES.DEPLOYMENT_ID_ = m.procdef_id WHERE RES.VERSION_ = (select max(VERSION_) from ACT_RE_PROCDEF where KEY_ = RES.KEY_ and ((TENANT_ID_ IS NOT NULL and TENANT_ID_ = RES.TENANT_ID_) or (TENANT_ID_ IS NULL and RES.TENANT_ID_ IS NULL))) and (RES.SUSPENSION_STATE_ = 1) <if test="procdefIdList != null and procdefIdList.size() > 0"> AND DEPLOYMENT_ID_ IN <foreach item="procdefId" collection="procdefIdList" open="(" separator="," close=")"> #{procdefId} </foreach> </if> <if test="processQuery.processName != null and processQuery.processName != ''">and NAME_ = #{processQuery.processName}</if> <if test="processQuery.category != null and processQuery.category != ''">and CATEGORY_ = #{processQuery.category}</if> order by RES.KEY_ asc </select> </mapper>
2929004360/ruoyi-sign
2,282
ruoyi-flowable/src/main/resources/mapper/flowable/WfFormMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfFormMapper"> <resultMap type="WfForm" id="WfFormResult"> <result property="formId" column="form_id"/> <result property="deptId" column="dept_id"/> <result property="formName" column="form_name"/> <result property="content" column="content"/> <result property="createTime" column="create_time"/> <result property="updateTime" column="update_time"/> <result property="createBy" column="create_by"/> <result property="updateBy" column="update_by"/> <result property="remark" column="remark"/> </resultMap> <sql id="selectWfFormVo"> form_id, dept_id, user_name, dept_name, form_name, type, content, create_time, remark </sql> <select id="selectFormVoList" resultType="WfFormVo"> SELECT t1.form_id AS formId, t1.form_name AS formName, t1.content AS content FROM wf_form t1 LEFT JOIN wf_deploy_form t2 ON t1.form_id = t2.form_id ${ew.getCustomSqlSegment} </select> <select id="selectWfFormList" resultMap="WfFormResult"> select DISTINCT <include refid="selectWfFormVo"/> FROM ( select <include refid="selectWfFormVo"/> FROM wf_form where dept_id in <foreach item="deptId" collection="deptIdList" open="(" separator="," close=")"> #{deptId} </foreach> UNION ALL select <include refid="selectWfFormVo"/> FROM wf_form where dept_id = #{wfForm.deptId} and type = '1' UNION ALL select <include refid="selectWfFormVo"/> FROM wf_form where dept_id in <foreach item="deptId" collection="ancestorsList" open="(" separator="," close=")"> #{deptId} </foreach> and type = '2' ) f <where> <if test="wfForm.formName != null and wfForm.formName != ''">and form_name = #{wfForm.formName}</if> </where> </select> </mapper>
281677160/openwrt-package
5,572
luci-app-homeproxy/root/etc/homeproxy/scripts/generate_server.uc
#!/usr/bin/ucode /* * SPDX-License-Identifier: GPL-2.0-only * * Copyright (C) 2023 ImmortalWrt.org */ 'use strict'; import { writefile } from 'fs'; import { cursor } from 'uci'; import { isEmpty, strToBool, strToInt, strToTime, removeBlankAttrs, HP_DIR, RUN_DIR } from 'homeproxy'; /* UCI config start */ const uci = cursor(); const uciconfig = 'homeproxy'; uci.load(uciconfig); const uciserver = 'server'; const log_level = uci.get(uciconfig, uciserver, 'log_level') || 'warn'; /* UCI config end */ const config = {}; /* Log */ config.log = { disabled: false, level: log_level, output: RUN_DIR + '/sing-box-s.log', timestamp: true }; config.inbounds = []; uci.foreach(uciconfig, uciserver, (cfg) => { if (cfg.enabled !== '1') return; push(config.inbounds, { type: cfg.type, tag: 'cfg-' + cfg['.name'] + '-in', listen: cfg.address || '::', listen_port: strToInt(cfg.port), bind_interface: cfg.bind_interface, reuse_addr: strToBool(cfg.reuse_addr), tcp_fast_open: strToBool(cfg.tcp_fast_open), tcp_multi_path: strToBool(cfg.tcp_multi_path), udp_fragment: strToBool(cfg.udp_fragment), udp_timeout: strToTime(cfg.udp_timeout), network: cfg.network, /* AnyTLS */ padding_scheme: cfg.anytls_padding_scheme, /* Hysteria */ up_mbps: strToInt(cfg.hysteria_up_mbps), down_mbps: strToInt(cfg.hysteria_down_mbps), obfs: cfg.hysteria_obfs_type ? { type: cfg.hysteria_obfs_type, password: cfg.hysteria_obfs_password } : cfg.hysteria_obfs_password, recv_window_conn: strToInt(cfg.hysteria_recv_window_conn), recv_window_client: strToInt(cfg.hysteria_revc_window_client), max_conn_client: strToInt(cfg.hysteria_max_conn_client), disable_mtu_discovery: strToBool(cfg.hysteria_disable_mtu_discovery), ignore_client_bandwidth: strToBool(cfg.hysteria_ignore_client_bandwidth), masquerade: cfg.hysteria_masquerade, /* Shadowsocks */ method: (cfg.type === 'shadowsocks') ? cfg.shadowsocks_encrypt_method : null, password: (cfg.type in ['shadowsocks', 'shadowtls']) ? cfg.password : null, /* Tuic */ congestion_control: cfg.tuic_congestion_control, auth_timeout: strToTime(cfg.tuic_auth_timeout), zero_rtt_handshake: strToBool(cfg.tuic_enable_zero_rtt), heartbeat: strToTime(cfg.tuic_heartbeat), /* AnyTLS / HTTP / Hysteria (2) / Mixed / Socks / Trojan / Tuic / VLESS / VMess */ users: (cfg.type !== 'shadowsocks') ? [ { name: !(cfg.type in ['http', 'mixed', 'naive', 'socks']) ? 'cfg-' + cfg['.name'] + '-server' : null, username: cfg.username, password: cfg.password, /* Hysteria */ auth: (cfg.hysteria_auth_type === 'base64') ? cfg.hysteria_auth_payload : null, auth_str: (cfg.hysteria_auth_type === 'string') ? cfg.hysteria_auth_payload : null, /* Tuic */ uuid: cfg.uuid, /* VLESS / VMess */ flow: cfg.vless_flow, alterId: strToInt(cfg.vmess_alterid) } ] : null, multiplex: (cfg.multiplex === '1') ? { enabled: true, padding: strToBool(cfg.multiplex_padding), brutal: (cfg.multiplex_brutal === '1') ? { enabled: true, up_mbps: strToInt(cfg.multiplex_brutal_up), down_mbps: strToInt(cfg.multiplex_brutal_down) } : null } : null, tls: (cfg.tls === '1') ? { enabled: true, server_name: cfg.tls_sni, alpn: cfg.tls_alpn, min_version: cfg.tls_min_version, max_version: cfg.tls_max_version, cipher_suites: cfg.tls_cipher_suites, certificate_path: cfg.tls_cert_path, key_path: cfg.tls_key_path, acme: (cfg.tls_acme === '1') ? { domain: cfg.tls_acme_domain, data_directory: HP_DIR + '/certs', default_server_name: cfg.tls_acme_dsn, email: cfg.tls_acme_email, provider: cfg.tls_acme_provider, disable_http_challenge: strToBool(cfg.tls_acme_dhc), disable_tls_alpn_challenge: (cfg.tls_acme_dtac), alternative_http_port: strToInt(cfg.tls_acme_ahp), alternative_tls_port: strToInt(cfg.tls_acme_atp), external_account: (cfg.tls_acme_external_account === '1') ? { key_id: cfg.tls_acme_ea_keyid, mac_key: cfg.tls_acme_ea_mackey } : null, dns01_challenge: (cfg.tls_dns01_challenge === '1') ? { provider: cfg.tls_dns01_provider, access_key_id: cfg.tls_dns01_ali_akid, access_key_secret: cfg.tls_dns01_ali_aksec, region_id: cfg.tls_dns01_ali_rid, api_token: cfg.tls_dns01_cf_api_token } : null } : null, ech: (cfg.tls_ech_key) ? { enabled: true, key: split(cfg.tls_ech_key, '\n'), // config: split(cfg.tls_ech_config, '\n') } : null, reality: (cfg.tls_reality === '1') ? { enabled: true, private_key: cfg.tls_reality_private_key, short_id: cfg.tls_reality_short_id, max_time_difference: strToTime(cfg.tls_reality_max_time_difference), handshake: { server: cfg.tls_reality_server_addr, server_port: strToInt(cfg.tls_reality_server_port) } } : null } : null, transport: !isEmpty(cfg.transport) ? { type: cfg.transport, host: cfg.http_host || cfg.httpupgrade_host, path: cfg.http_path || cfg.ws_path, headers: cfg.ws_host ? { Host: cfg.ws_host } : null, method: cfg.http_method, max_early_data: strToInt(cfg.websocket_early_data), early_data_header_name: cfg.websocket_early_data_header, service_name: cfg.grpc_servicename, idle_timeout: strToTime(cfg.http_idle_timeout), ping_timeout: strToTime(cfg.http_ping_timeout) } : null }); }); if (length(config.inbounds) === 0) exit(1); system('mkdir -p ' + RUN_DIR); writefile(RUN_DIR + '/sing-box-s.json', sprintf('%.J\n', removeBlankAttrs(config)));
281677160/openwrt-package
2,695
luci-app-homeproxy/root/etc/homeproxy/scripts/update_resources.sh
#!/bin/sh # SPDX-License-Identifier: GPL-2.0-only # # Copyright (C) 2022-2025 ImmortalWrt.org NAME="homeproxy" RESOURCES_DIR="/etc/$NAME/resources" mkdir -p "$RESOURCES_DIR" RUN_DIR="/var/run/$NAME" LOG_PATH="$RUN_DIR/$NAME.log" mkdir -p "$RUN_DIR" log() { echo -e "$(date "+%Y-%m-%d %H:%M:%S") $*" >> "$LOG_PATH" } to_upper() { echo -e "$1" | tr "[a-z]" "[A-Z]" } check_list_update() { local listtype="$1" local listrepo="$2" local listref="$3" local listname="$4" local lock="$RUN_DIR/update_resources-$listtype.lock" local github_token="$(uci -q get homeproxy.config.github_token)" local wget="wget --timeout=10 -q" exec 200>"$lock" if ! flock -n 200 &> "/dev/null"; then log "[$(to_upper "$listtype")] A task is already running." return 2 fi [ -z "$github_token" ] || github_token="--header=Authorization: Bearer $github_token" local list_info="$($wget "${github_token:--q}" -O- "https://api.github.com/repos/$listrepo/commits?sha=$listref&path=$listname&per_page=1")" local list_sha="$(echo -e "$list_info" | jsonfilter -qe "@[0].sha")" local list_ver="$(echo -e "$list_info" | jsonfilter -qe "@[0].commit.message" | grep -Eo "[0-9-]+" | tr -d '-')" if [ -z "$list_sha" ] || [ -z "$list_ver" ]; then log "[$(to_upper "$listtype")] Failed to get the latest version, please retry later." return 1 fi local local_list_ver="$(cat "$RESOURCES_DIR/$listtype.ver" 2>"/dev/null" || echo "NOT FOUND")" if [ "$local_list_ver" = "$list_ver" ]; then log "[$(to_upper "$listtype")] Current version: $list_ver." log "[$(to_upper "$listtype")] You're already at the latest version." return 3 else log "[$(to_upper "$listtype")] Local version: $local_list_ver, latest version: $list_ver." fi if ! $wget "https://fastly.jsdelivr.net/gh/$listrepo@$list_sha/$listname" -O "$RUN_DIR/$listname" || [ ! -s "$RUN_DIR/$listname" ]; then rm -f "$RUN_DIR/$listname" log "[$(to_upper "$listtype")] Update failed." return 1 fi mv -f "$RUN_DIR/$listname" "$RESOURCES_DIR/$listtype.${listname##*.}" echo -e "$list_ver" > "$RESOURCES_DIR/$listtype.ver" log "[$(to_upper "$listtype")] Successfully updated." return 0 } case "$1" in "china_ip4") check_list_update "$1" "1715173329/IPCIDR-CHINA" "master" "ipv4.txt" ;; "china_ip6") check_list_update "$1" "1715173329/IPCIDR-CHINA" "master" "ipv6.txt" ;; "gfw_list") check_list_update "$1" "Loyalsoldier/v2ray-rules-dat" "release" "gfw.txt" ;; "china_list") check_list_update "$1" "Loyalsoldier/v2ray-rules-dat" "release" "direct-list.txt" && \ sed -i -e "s/full://g" -e "/:/d" "$RESOURCES_DIR/china_list.txt" ;; *) echo -e "Usage: $0 <china_ip4 / china_ip6 / gfw_list / china_list>" exit 1 ;; esac
2929004360/ruoyi-sign
4,225
ruoyi-flowable/src/main/resources/mapper/flowable/WfModelProcdefMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfModelProcdefMapper"> <resultMap type="WfModelProcdef" id="WfModelProcdefResult"> <result property="modelId" column="model_id"/> <result property="procdefId" column="procdef_id"/> <result property="formType" column="form_type"/> <result property="formCreatePath" column="form_create_path"/> <result property="formViewPath" column="form_view_path"/> </resultMap> <sql id="selectWfModelProcdefVo"> select model_id, procdef_id, form_type, form_create_path, form_view_path from wf_model_procdef </sql> <select id="selectWfModelProcdefList" parameterType="WfModelProcdef" resultMap="WfModelProcdefResult"> <include refid="selectWfModelProcdefVo"/> <where> <if test="modelId != null and modelId != ''">and model_id = #{modelId}</if> <if test="procdefId != null and procdefId != ''">and procdef_id = #{procdefId}</if> <if test="formType != null and formType != ''">and form_type = #{formType}</if> <if test="formCreatePath != null and formCreatePath != ''">and form_create_path = #{formCreatePath}</if> <if test="formViewPath != null and formViewPath != ''">and form_view_path = #{formViewPath}</if> </where> </select> <select id="selectWfModelProcdefByModelId" parameterType="String" resultMap="WfModelProcdefResult"> <include refid="selectWfModelProcdefVo"/> where model_id = #{modelId} </select> <select id="selectWfModelProcdefListByModelIdList" resultType="java.lang.String"> select procdef_id from wf_model_procdef where model_id in <foreach item="modelId" collection="modelIdList" open="(" separator="," close=")"> #{modelId} </foreach> </select> <select id="selectWfModelProcdefByProcdefId" parameterType="String" resultMap="WfModelProcdefResult"> <include refid="selectWfModelProcdefVo"/> where procdef_id = #{procdefId} </select> <insert id="insertWfModelProcdef" parameterType="WfModelProcdef"> insert into wf_model_procdef <trim prefix="(" suffix=")" suffixOverrides=","> <if test="modelId != null">model_id,</if> <if test="procdefId != null">procdef_id,</if> <if test="formType != null">form_type,</if> <if test="formCreatePath != null">form_create_path,</if> <if test="formViewPath != null">form_view_path,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="modelId != null">#{modelId},</if> <if test="procdefId != null">#{procdefId},</if> <if test="formType != null">#{formType},</if> <if test="formCreatePath != null">#{formCreatePath},</if> <if test="formViewPath != null">#{formViewPath},</if> </trim> </insert> <update id="updateWfModelProcdef" parameterType="WfModelProcdef"> update wf_model_procdef <trim prefix="SET" suffixOverrides=","> <if test="procdefId != null">procdef_id = #{procdefId},</if> <if test="formType != null">form_type = #{formType},</if> <if test="formCreatePath != null">form_create_path = #{formCreatePath},</if> <if test="formViewPath != null">form_view_path = #{formViewPath},</if> </trim> where model_id = #{modelId} </update> <delete id="deleteWfModelProcdefByModelId" parameterType="String"> delete from wf_model_procdef where model_id = #{modelId} </delete> <delete id="deleteWfModelProcdefByModelIds" parameterType="String"> delete from wf_model_procdef where model_id in <foreach item="modelId" collection="array" open="(" separator="," close=")"> #{modelId} </foreach> </delete> <delete id="deleteWfModelProcdefByProcdefId"> delete from wf_model_procdef where procdef_id = #{procdefId} </delete> </mapper>
2929004360/ruoyi-sign
2,216
ruoyi-flowable/src/main/resources/mapper/flowable/WfIconMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ruoyi.flowable.mapper.WfIconMapper"> <resultMap type="WfIcon" id="WfIconResult"> <result property="deploymentId" column="deployment_id" /> <result property="icon" column="icon" /> </resultMap> <sql id="selectWfIconVo"> select deployment_id, icon from wf_icon </sql> <select id="selectWfIconList" parameterType="WfIcon" resultMap="WfIconResult"> <include refid="selectWfIconVo"/> <where> <if test="deploymentId != null and deploymentId != ''"> and deployment_id = #{deploymentId}</if> <if test="icon != null and icon != ''"> and icon = #{icon}</if> </where> </select> <select id="selectWfIconByDeploymentId" parameterType="String" resultMap="WfIconResult"> <include refid="selectWfIconVo"/> where deployment_id = #{deploymentId} </select> <insert id="insertWfIcon" parameterType="WfIcon"> insert into wf_icon <trim prefix="(" suffix=")" suffixOverrides=","> <if test="deploymentId != null">deployment_id,</if> <if test="icon != null">icon,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="deploymentId != null">#{deploymentId},</if> <if test="icon != null">#{icon},</if> </trim> </insert> <update id="updateWfIcon" parameterType="WfIcon"> update wf_icon <trim prefix="SET" suffixOverrides=","> <if test="icon != null">icon = #{icon},</if> </trim> where deployment_id = #{deploymentId} </update> <delete id="deleteWfIconByDeploymentId" parameterType="String"> delete from wf_icon where deployment_id = #{deploymentId} </delete> <delete id="deleteWfIconByDeploymentIds" parameterType="String"> delete from wf_icon where deployment_id in <foreach item="deploymentId" collection="array" open="(" separator="," close=")"> #{deploymentId} </foreach> </delete> </mapper>
2977094657/BilibiliHistoryFetcher
81,320
routers/video_details.py
import asyncio import concurrent.futures import json import os import random import sqlite3 import time from typing import Dict, Any, Optional, List import httpx from fastapi import APIRouter, HTTPException, Query, BackgroundTasks from fastapi.responses import StreamingResponse from loguru import logger from scripts.utils import load_config router = APIRouter(tags=["视频详情"]) # 数据库路径 DB_PATH = os.path.join("output", "database", "bilibili_video_details.db") # 全局进度状态 video_details_progress = { "is_processing": False, "is_complete": False, "is_stopped": False, # 新增:是否被用户停止 "total_videos": 0, "processed_videos": 0, "success_count": 0, "failed_count": 0, "error_videos": [], "skipped_invalid_count": 0, "start_time": 0, "last_update_time": 0 } # 确保数据库目录存在 os.makedirs(os.path.join("output", "database"), exist_ok=True) def init_db() -> None: """初始化数据库""" with sqlite3.connect(DB_PATH) as conn: cursor = conn.cursor() # 视频基本信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS video_base_info ( id INTEGER PRIMARY KEY, bvid TEXT NOT NULL UNIQUE, aid INTEGER NOT NULL, videos INTEGER DEFAULT 1, tid INTEGER, tid_v2 INTEGER, tname TEXT, tname_v2 TEXT, copyright INTEGER, pic TEXT, title TEXT NOT NULL, pubdate INTEGER, ctime INTEGER, desc TEXT, desc_v2 TEXT, state INTEGER DEFAULT 0, duration INTEGER, mission_id INTEGER, dynamic TEXT, cid INTEGER, season_id INTEGER, premiere INTEGER, teenage_mode INTEGER DEFAULT 0, is_chargeable_season INTEGER DEFAULT 0, is_story INTEGER DEFAULT 0, is_upower_exclusive INTEGER DEFAULT 0, is_upower_play INTEGER DEFAULT 0, is_upower_preview INTEGER DEFAULT 0, enable_vt INTEGER DEFAULT 0, vt_display TEXT, is_upower_exclusive_with_qa INTEGER DEFAULT 0, no_cache INTEGER DEFAULT 0, is_season_display INTEGER DEFAULT 0, like_icon TEXT, need_jump_bv INTEGER DEFAULT 0, disable_show_up_info INTEGER DEFAULT 0, is_story_play INTEGER DEFAULT 0, owner_mid INTEGER, owner_name TEXT, owner_face TEXT, stat_view INTEGER DEFAULT 0, stat_danmaku INTEGER DEFAULT 0, stat_reply INTEGER DEFAULT 0, stat_favorite INTEGER DEFAULT 0, stat_coin INTEGER DEFAULT 0, stat_share INTEGER DEFAULT 0, stat_like INTEGER DEFAULT 0, stat_dislike INTEGER DEFAULT 0, stat_his_rank INTEGER DEFAULT 0, stat_now_rank INTEGER DEFAULT 0, stat_evaluation TEXT, stat_vt INTEGER DEFAULT 0, dimension_width INTEGER, dimension_height INTEGER, dimension_rotate INTEGER DEFAULT 0, rights_bp INTEGER DEFAULT 0, rights_elec INTEGER DEFAULT 0, rights_download INTEGER DEFAULT 0, rights_movie INTEGER DEFAULT 0, rights_pay INTEGER DEFAULT 0, rights_hd5 INTEGER DEFAULT 0, rights_no_reprint INTEGER DEFAULT 0, rights_autoplay INTEGER DEFAULT 0, rights_ugc_pay INTEGER DEFAULT 0, rights_is_cooperation INTEGER DEFAULT 0, rights_ugc_pay_preview INTEGER DEFAULT 0, rights_no_background INTEGER DEFAULT 0, rights_clean_mode INTEGER DEFAULT 0, rights_is_stein_gate INTEGER DEFAULT 0, rights_is_360 INTEGER DEFAULT 0, rights_no_share INTEGER DEFAULT 0, rights_arc_pay INTEGER DEFAULT 0, rights_free_watch INTEGER DEFAULT 0, argue_msg TEXT, argue_type INTEGER DEFAULT 0, argue_link TEXT, fetch_time INTEGER NOT NULL, update_time INTEGER DEFAULT 0 ) """) # 视频分P信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS video_pages ( id INTEGER PRIMARY KEY, bvid TEXT NOT NULL, cid INTEGER NOT NULL, page INTEGER NOT NULL, part TEXT, duration INTEGER, from_source TEXT, vid TEXT, weblink TEXT, dimension_width INTEGER, dimension_height INTEGER, dimension_rotate INTEGER DEFAULT 0, first_frame TEXT, ctime INTEGER DEFAULT 0, UNIQUE(bvid, cid) ) """) # 视频标签信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS video_tags ( id INTEGER PRIMARY KEY, bvid TEXT NOT NULL, tag_id INTEGER NOT NULL, tag_name TEXT NOT NULL, music_id TEXT, tag_type TEXT, jump_url TEXT, cover TEXT, content TEXT, short_content TEXT, type INTEGER, state INTEGER, UNIQUE(bvid, tag_id) ) """) # UP主详细信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS uploader_info ( mid INTEGER PRIMARY KEY, name TEXT NOT NULL, sex TEXT, face TEXT, face_nft INTEGER DEFAULT 0, face_nft_type INTEGER DEFAULT 0, sign TEXT, rank TEXT, level INTEGER DEFAULT 0, regtime INTEGER DEFAULT 0, spacesta INTEGER DEFAULT 0, birthday TEXT, place TEXT, description TEXT, article INTEGER DEFAULT 0, fans INTEGER DEFAULT 0, friend INTEGER DEFAULT 0, attention INTEGER DEFAULT 0, official_role INTEGER DEFAULT 0, official_title TEXT, official_desc TEXT, official_type INTEGER DEFAULT 0, vip_type INTEGER DEFAULT 0, vip_status INTEGER DEFAULT 0, vip_due_date INTEGER DEFAULT 0, vip_pay_type INTEGER DEFAULT 0, vip_theme_type INTEGER DEFAULT 0, vip_avatar_subscript INTEGER DEFAULT 0, vip_nickname_color TEXT, vip_role INTEGER DEFAULT 0, vip_avatar_subscript_url TEXT, pendant_pid INTEGER DEFAULT 0, pendant_name TEXT, pendant_image TEXT, pendant_expire INTEGER DEFAULT 0, nameplate_nid INTEGER DEFAULT 0, nameplate_name TEXT, nameplate_image TEXT, nameplate_image_small TEXT, nameplate_level TEXT, nameplate_condition TEXT, is_senior_member INTEGER DEFAULT 0, following INTEGER DEFAULT 0, archive_count INTEGER DEFAULT 0, article_count INTEGER DEFAULT 0, like_num INTEGER DEFAULT 0, fetch_time INTEGER NOT NULL, update_time INTEGER DEFAULT 0 ) """) # 视频荣誉信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS video_honors ( id INTEGER PRIMARY KEY, bvid TEXT NOT NULL, aid INTEGER NOT NULL, type INTEGER NOT NULL, desc TEXT, weekly_recommend_num INTEGER DEFAULT 0, UNIQUE(bvid, type) ) """) # 视频字幕信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS video_subtitles ( id INTEGER PRIMARY KEY, bvid TEXT NOT NULL, allow_submit INTEGER DEFAULT 0, subtitle_id INTEGER, lan TEXT, lan_doc TEXT, is_lock INTEGER DEFAULT 0, subtitle_url TEXT, UNIQUE(bvid, subtitle_id) ) """) # 相关视频信息表 cursor.execute(""" CREATE TABLE IF NOT EXISTS related_videos ( id INTEGER PRIMARY KEY, bvid TEXT NOT NULL, related_bvid TEXT NOT NULL, related_aid INTEGER NOT NULL, related_title TEXT, related_pic TEXT, related_owner_mid INTEGER, related_owner_name TEXT, related_owner_face TEXT, UNIQUE(bvid, related_bvid) ) """) # 创建索引 cursor.execute("CREATE INDEX IF NOT EXISTS idx_video_base_info_owner_mid ON video_base_info (owner_mid)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_video_base_info_fetch_time ON video_base_info (fetch_time)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_video_pages_bvid ON video_pages (bvid)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_video_tags_bvid ON video_tags (bvid)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_video_honors_bvid ON video_honors (bvid)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_video_subtitles_bvid ON video_subtitles (bvid)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_related_videos_bvid ON related_videos (bvid)") # 提交更改 conn.commit() async def get_video_detail(bvid: str) -> Dict[str, Any]: """ 获取视频超详细信息 Args: bvid: 视频的BV号 Returns: 视频详细信息 """ config = load_config() cookies = config.get("cookies", {}) cookie_str = "; ".join([f"{k}={v}" for k, v in cookies.items()]) if cookies else "" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36", "Referer": "https://www.bilibili.com", "Cookie": cookie_str } url = f"https://api.bilibili.com/x/web-interface/view/detail?bvid={bvid}" try: async with httpx.AsyncClient(timeout=30) as client: response = await client.get(url, headers=headers) response.raise_for_status() data = response.json() if data.get("code") != 0: raise HTTPException(status_code=400, detail=f"API错误: {data.get('message', '未知错误')}") return data except httpx.HTTPError as e: logger.error(f"请求视频详情API失败: {e}") raise HTTPException(status_code=500, detail=f"请求API失败: {str(e)}") def get_video_detail_sync(bvid: str, cookie_str: str = "", use_sessdata: bool = True) -> Dict[str, Any]: """ 同步获取视频超详细信息(用于线程池) Args: bvid: 视频的BV号 cookie_str: Cookie字符串 use_sessdata: 是否使用SESSDATA Returns: 视频详细信息 """ import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36", "Referer": "https://www.bilibili.com" } if use_sessdata and cookie_str: headers["Cookie"] = cookie_str url = f"https://api.bilibili.com/x/web-interface/view/detail?bvid={bvid}" try: response = requests.get(url, headers=headers, timeout=30) response.raise_for_status() data = response.json() if data.get("code") != 0: logger.warning(f"API错误 {bvid}: {data.get('message', '未知错误')}") return data # 返回错误数据,让调用者处理 return data except requests.RequestException as e: logger.error(f"请求视频详情API失败 {bvid}: {e}") return {"code": -1, "message": f"请求失败: {str(e)}"} def save_video_detail_to_db(data: Dict[str, Any]) -> None: """ 将视频详细信息保存到数据库 Args: data: 视频详细信息数据 """ # 确保数据库已初始化 init_db() # 打印原始响应数据,方便调试 logger.info(f"保存视频详情原始数据: {json.dumps(data, ensure_ascii=False)[:500]}...") # 保存完整的API响应到文件,方便排查错误 try: os.makedirs(os.path.join("output", "api_responses"), exist_ok=True) response_file = os.path.join("output", "api_responses", f"video_detail_{int(time.time())}.json") with open(response_file, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) logger.info(f"已保存完整API响应到文件: {response_file}") except Exception as e: logger.error(f"保存API响应到文件时出错: {e}") now_timestamp = int(time.time()) view_data = data.get("data", {}).get("View", {}) card_data = data.get("data", {}).get("Card", {}) tags_data = data.get("data", {}).get("Tags", []) related_data = data.get("data", {}).get("Related", []) honor_reply_data = view_data.get("honor_reply", {}).get("honor", []) if view_data.get("honor_reply") else [] subtitle_data = view_data.get("subtitle", {}) if view_data.get("subtitle") else {} # 调试: 获取表中实际的列名和数量 try: with sqlite3.connect(DB_PATH) as conn: cursor = conn.cursor() cursor.execute("PRAGMA table_info(video_base_info)") table_columns = cursor.fetchall() column_names = [column[1] for column in table_columns] logger.info(f"数据库video_base_info表中实际的列名: {column_names}") logger.info(f"数据库video_base_info表中实际的列数: {len(column_names)}") except Exception as e: logger.error(f"获取表结构时出错: {e}") # 调试: 计算并打印值的数量,检查SQL语句列数是否匹配 debug_values_count = [ "bvid", "aid", "videos", "tid", "tid_v2", "tname", "tname_v2", "copyright", "pic", "title", "pubdate", "ctime", "desc", "desc_v2", "state", "duration", "mission_id", "dynamic", "cid", "season_id", "premiere", "teenage_mode", "is_chargeable_season", "is_story", "is_upower_exclusive", "is_upower_play", "is_upower_preview", "enable_vt", "vt_display", "is_upower_exclusive_with_qa", "no_cache", "is_season_display", "like_icon", "need_jump_bv", "disable_show_up_info", "is_story_play", "owner_mid", "owner_name", "owner_face", "stat_view", "stat_danmaku", "stat_reply", "stat_favorite", "stat_coin", "stat_share", "stat_like", "stat_dislike", "stat_his_rank", "stat_now_rank", "stat_evaluation", "stat_vt", "dimension_width", "dimension_height", "dimension_rotate", "rights_bp", "rights_elec", "rights_download", "rights_movie", "rights_pay", "rights_hd5", "rights_no_reprint", "rights_autoplay", "rights_ugc_pay", "rights_is_cooperation", "rights_ugc_pay_preview", "rights_no_background", "rights_clean_mode", "rights_is_stein_gate", "rights_is_360", "rights_no_share", "rights_arc_pay", "rights_free_watch", "argue_msg", "argue_type", "argue_link", "fetch_time", "update_time" ] logger.info(f"调试: 插入表的列数量={len(debug_values_count)}, VALUES 参数数量应为: {len(debug_values_count)}") # 调试: 尝试找出我们定义的列和表中实际列之间的差异 try: with sqlite3.connect(DB_PATH) as conn: cursor = conn.cursor() cursor.execute("PRAGMA table_info(video_base_info)") table_columns = cursor.fetchall() db_column_names = [column[1] for column in table_columns] # 比较列名 our_columns = set(debug_values_count) db_columns = set(db_column_names) missing_in_our_def = db_columns - our_columns extra_in_our_def = our_columns - db_columns if missing_in_our_def: logger.warning(f"我们定义中缺少的列: {missing_in_our_def}") if extra_in_our_def: logger.warning(f"我们定义中多余的列: {extra_in_our_def}") # 检查顺序是否一致 if len(debug_values_count) == len(db_column_names) - 1: # 减1是因为id列是自增的 for i, (ours, db) in enumerate(zip(debug_values_count, db_column_names[1:])): # 跳过id列 if ours != db: logger.warning(f"列顺序不匹配: 索引{i},我们的定义是 '{ours}',数据库是 '{db}'") except Exception as e: logger.error(f"比较列名时出错: {e}") if not view_data: logger.error("视频数据为空") return bvid = view_data.get("bvid") if not bvid: logger.error("视频BV号为空") return # 记录详细的数据结构信息 logger.debug(f"保存视频 {bvid} 详情: view_data keys: {view_data.keys()}") logger.debug(f"rights keys: {view_data.get('rights', {}).keys()}") try: with sqlite3.connect(DB_PATH) as conn: conn.execute("PRAGMA foreign_keys = ON") cursor = conn.cursor() # 1. 保存视频基本信息 owner = view_data.get("owner", {}) stat = view_data.get("stat", {}) dimension = view_data.get("dimension", {}) rights = view_data.get("rights", {}) argue_info = view_data.get("argue_info", {}) # 检查视频是否已存在 cursor.execute("SELECT bvid FROM video_base_info WHERE bvid = ?", (bvid,)) existing = cursor.fetchone() if existing: # 更新现有数据 cursor.execute(""" UPDATE video_base_info SET videos = ?, tid = ?, tid_v2 = ?, tname = ?, tname_v2 = ?, copyright = ?, pic = ?, title = ?, pubdate = ?, ctime = ?, desc = ?, desc_v2 = ?, state = ?, duration = ?, mission_id = ?, dynamic = ?, cid = ?, season_id = ?, premiere = ?, teenage_mode = ?, is_chargeable_season = ?, is_story = ?, is_upower_exclusive = ?, is_upower_play = ?, is_upower_preview = ?, enable_vt = ?, vt_display = ?, is_upower_exclusive_with_qa = ?, no_cache = ?, is_season_display = ?, like_icon = ?, need_jump_bv = ?, disable_show_up_info = ?, is_story_play = ?, owner_mid = ?, owner_name = ?, owner_face = ?, stat_view = ?, stat_danmaku = ?, stat_reply = ?, stat_favorite = ?, stat_coin = ?, stat_share = ?, stat_like = ?, stat_dislike = ?, stat_his_rank = ?, stat_now_rank = ?, stat_evaluation = ?, stat_vt = ?, dimension_width = ?, dimension_height = ?, dimension_rotate = ?, rights_bp = ?, rights_elec = ?, rights_download = ?, rights_movie = ?, rights_pay = ?, rights_hd5 = ?, rights_no_reprint = ?, rights_autoplay = ?, rights_ugc_pay = ?, rights_is_cooperation = ?, rights_ugc_pay_preview = ?, rights_no_background = ?, rights_clean_mode = ?, rights_is_stein_gate = ?, rights_is_360 = ?, rights_no_share = ?, rights_arc_pay = ?, rights_free_watch = ?, argue_msg = ?, argue_type = ?, argue_link = ?, update_time = ? WHERE bvid = ? """, ( view_data.get("videos", 1), view_data.get("tid"), view_data.get("tid_v2"), view_data.get("tname"), view_data.get("tname_v2"), view_data.get("copyright"), view_data.get("pic"), view_data.get("title"), view_data.get("pubdate"), view_data.get("ctime"), view_data.get("desc"), # 对于desc_v2字段,如果是列表且有内容,只取第一项的raw_text值 (view_data.get("desc_v2")[0].get("raw_text") if isinstance(view_data.get("desc_v2"), list) and view_data.get("desc_v2") else ""), view_data.get("state", 0), view_data.get("duration"), view_data.get("mission_id"), view_data.get("dynamic"), view_data.get("cid"), view_data.get("season_id"), 1 if view_data.get("premiere") else 0, view_data.get("teenage_mode", 0), 1 if view_data.get("is_chargeable_season") else 0, 1 if view_data.get("is_story") else 0, 1 if view_data.get("is_upower_exclusive") else 0, 1 if view_data.get("is_upower_play") else 0, 1 if view_data.get("is_upower_preview") else 0, view_data.get("enable_vt", 0), view_data.get("vt_display", ""), 1 if view_data.get("is_upower_exclusive_with_qa") else 0, 1 if view_data.get("no_cache") else 0, 1 if view_data.get("is_season_display") else 0, view_data.get("like_icon", ""), 1 if view_data.get("need_jump_bv") else 0, 1 if view_data.get("disable_show_up_info") else 0, view_data.get("is_story_play", 0), owner.get("mid"), owner.get("name"), owner.get("face"), stat.get("view", 0), stat.get("danmaku", 0), stat.get("reply", 0), stat.get("favorite", 0), stat.get("coin", 0), stat.get("share", 0), stat.get("like", 0), stat.get("dislike", 0), stat.get("his_rank", 0), stat.get("now_rank", 0), stat.get("evaluation", ""), stat.get("vt", 0), dimension.get("width"), dimension.get("height"), dimension.get("rotate", 0), rights.get("bp", 0), rights.get("elec", 0), rights.get("download", 0), rights.get("movie", 0), rights.get("pay", 0), rights.get("hd5", 0), rights.get("no_reprint", 0), rights.get("autoplay", 0), rights.get("ugc_pay", 0), rights.get("is_cooperation", 0), rights.get("ugc_pay_preview", 0), rights.get("no_background", 0), rights.get("clean_mode", 0), rights.get("is_stein_gate", 0), rights.get("is_360", 0), rights.get("no_share", 0), rights.get("arc_pay", 0), rights.get("free_watch", 0), argue_info.get("argue_msg", ""), argue_info.get("argue_type", 0), argue_info.get("argue_link", ""), now_timestamp, bvid )) else: # 插入新数据 # 创建参数列表,先明确所有参数,便于调试 insert_params = [ bvid, # 1. bvid view_data.get("aid"), # 2. aid view_data.get("videos", 1), # 3. videos view_data.get("tid"), # 4. tid view_data.get("tid_v2"), # 5. tid_v2 view_data.get("tname"), # 6. tname view_data.get("tname_v2"), # 7. tname_v2 view_data.get("copyright"), # 8. copyright view_data.get("pic"), # 9. pic view_data.get("title"), # 10. title view_data.get("pubdate"), # 11. pubdate view_data.get("ctime"), # 12. ctime view_data.get("desc"), # 13. desc # 对于desc_v2字段,如果是列表且有内容,只取第一项的raw_text值 (view_data.get("desc_v2")[0].get("raw_text") if isinstance(view_data.get("desc_v2"), list) and view_data.get("desc_v2") else ""), # 14. desc_v2 view_data.get("state", 0), # 15. state view_data.get("duration"), # 16. duration view_data.get("mission_id"), # 17. mission_id view_data.get("dynamic"), # 18. dynamic view_data.get("cid"), # 19. cid view_data.get("season_id"), # 20. season_id 1 if view_data.get("premiere") else 0, # 21. premiere view_data.get("teenage_mode", 0), # 22. teenage_mode 1 if view_data.get("is_chargeable_season") else 0, # 23. is_chargeable_season 1 if view_data.get("is_story") else 0, # 24. is_story 1 if view_data.get("is_upower_exclusive") else 0, # 25. is_upower_exclusive 1 if view_data.get("is_upower_play") else 0, # 26. is_upower_play 1 if view_data.get("is_upower_preview") else 0, # 27. is_upower_preview view_data.get("enable_vt", 0), # 28. enable_vt view_data.get("vt_display", ""), # 29. vt_display 1 if view_data.get("is_upower_exclusive_with_qa") else 0, # 30. is_upower_exclusive_with_qa 1 if view_data.get("no_cache") else 0, # 31. no_cache 1 if view_data.get("is_season_display") else 0, # 32. is_season_display view_data.get("like_icon", ""), # 33. like_icon 1 if view_data.get("need_jump_bv") else 0, # 34. need_jump_bv 1 if view_data.get("disable_show_up_info") else 0, # 35. disable_show_up_info view_data.get("is_story_play", 0), # 36. is_story_play owner.get("mid"), # 37. owner_mid owner.get("name"), # 38. owner_name owner.get("face"), # 39. owner_face stat.get("view", 0), # 40. stat_view stat.get("danmaku", 0), # 41. stat_danmaku stat.get("reply", 0), # 42. stat_reply stat.get("favorite", 0), # 43. stat_favorite stat.get("coin", 0), # 44. stat_coin stat.get("share", 0), # 45. stat_share stat.get("like", 0), # 46. stat_like stat.get("dislike", 0), # 47. stat_dislike stat.get("his_rank", 0), # 48. stat_his_rank stat.get("now_rank", 0), # 49. stat_now_rank stat.get("evaluation", ""), # 50. stat_evaluation stat.get("vt", 0), # 51. stat_vt dimension.get("width"), # 52. dimension_width dimension.get("height"), # 53. dimension_height dimension.get("rotate", 0), # 54. dimension_rotate rights.get("bp", 0), # 55. rights_bp rights.get("elec", 0), # 56. rights_elec rights.get("download", 0), # 57. rights_download rights.get("movie", 0), # 58. rights_movie rights.get("pay", 0), # 59. rights_pay rights.get("hd5", 0), # 60. rights_hd5 rights.get("no_reprint", 0), # 61. rights_no_reprint rights.get("autoplay", 0), # 62. rights_autoplay rights.get("ugc_pay", 0), # 63. rights_ugc_pay rights.get("is_cooperation", 0), # 64. rights_is_cooperation rights.get("ugc_pay_preview", 0), # 65. rights_ugc_pay_preview rights.get("no_background", 0), # 66. rights_no_background rights.get("clean_mode", 0), # 67. rights_clean_mode rights.get("is_stein_gate", 0), # 68. rights_is_stein_gate rights.get("is_360", 0), # 69. rights_is_360 rights.get("no_share", 0), # 70. rights_no_share rights.get("arc_pay", 0), # 71. rights_arc_pay rights.get("free_watch", 0), # 72. rights_free_watch argue_info.get("argue_msg", ""), # 73. argue_msg argue_info.get("argue_type", 0), # 74. argue_type argue_info.get("argue_link", ""), # 75. argue_link now_timestamp, # 76. fetch_time now_timestamp # 77. update_time ] # 打印参数数量以便调试 logger.info(f"实际准备插入的参数数量: {len(insert_params)}") # 计算VALUES子句中的问号数量 values_clause = """( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 1-20 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 21-40 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 41-60 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? /* 61-77 */ )""" question_marks_count = values_clause.count('?') logger.info(f"VALUES子句中的问号数量: {question_marks_count}") # 确保问号数量和参数数量匹配 if question_marks_count != len(insert_params): logger.error(f"问号数量({question_marks_count})和参数数量({len(insert_params)})不匹配!") for i, param in enumerate(insert_params): logger.debug(f"参数 {i+1}: {param}") raise ValueError(f"SQL绑定参数不匹配: 需要 {question_marks_count} 个值,但提供了 {len(insert_params)} 个") # 检查所有参数的类型,确保它们是SQLite支持的类型 for i, param in enumerate(insert_params): if isinstance(param, (list, dict)): logger.warning(f"参数 {i+1} 是不支持的类型: {type(param)}, 值: {param}") # 将不支持的类型转换为JSON字符串 insert_params[i] = json.dumps(param, ensure_ascii=False) logger.info(f"已将参数 {i+1} 转换为字符串: {insert_params[i]}") # 我们已经在上面的代码中处理了所有参数的类型转换,包括desc_v2 # 确保列和值的数量匹配 - 使用明确的格式确保77个问号 cursor.execute(""" INSERT INTO video_base_info ( bvid, aid, videos, tid, tid_v2, tname, tname_v2, copyright, pic, title, pubdate, ctime, desc, desc_v2, state, duration, mission_id, dynamic, cid, season_id, premiere, teenage_mode, is_chargeable_season, is_story, is_upower_exclusive, is_upower_play, is_upower_preview, enable_vt, vt_display, is_upower_exclusive_with_qa, no_cache, is_season_display, like_icon, need_jump_bv, disable_show_up_info, is_story_play, owner_mid, owner_name, owner_face, stat_view, stat_danmaku, stat_reply, stat_favorite, stat_coin, stat_share, stat_like, stat_dislike, stat_his_rank, stat_now_rank, stat_evaluation, stat_vt, dimension_width, dimension_height, dimension_rotate, rights_bp, rights_elec, rights_download, rights_movie, rights_pay, rights_hd5, rights_no_reprint, rights_autoplay, rights_ugc_pay, rights_is_cooperation, rights_ugc_pay_preview, rights_no_background, rights_clean_mode, rights_is_stein_gate, rights_is_360, rights_no_share, rights_arc_pay, rights_free_watch, argue_msg, argue_type, argue_link, fetch_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 1-20 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 21-40 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 41-60 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? /* 61-77 */ ) """, insert_params) # 2. 保存视频分P信息 # 先删除旧的分P信息 cursor.execute("DELETE FROM video_pages WHERE bvid = ?", (bvid,)) # 插入新的分P信息 pages = view_data.get("pages", []) if pages: for page in pages: page_dimension = page.get("dimension", {}) cursor.execute(""" INSERT INTO video_pages ( bvid, cid, page, part, duration, from_source, vid, weblink, dimension_width, dimension_height, dimension_rotate, first_frame, ctime ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( bvid, page.get("cid"), page.get("page"), page.get("part"), page.get("duration"), page.get("from"), page.get("vid", ""), page.get("weblink", ""), page_dimension.get("width"), page_dimension.get("height"), page_dimension.get("rotate", 0), page.get("first_frame"), page.get("ctime", 0) )) # 3. 保存视频标签信息 # 先删除旧的标签信息 cursor.execute("DELETE FROM video_tags WHERE bvid = ?", (bvid,)) # 插入新的标签信息 if tags_data: for tag in tags_data: cursor.execute(""" INSERT INTO video_tags ( bvid, tag_id, tag_name, music_id, tag_type, jump_url, cover, content, short_content, type, state ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( bvid, tag.get("tag_id"), tag.get("tag_name"), tag.get("music_id", ""), tag.get("tag_type", ""), tag.get("jump_url", ""), tag.get("cover"), tag.get("content"), tag.get("short_content"), tag.get("type"), tag.get("state") )) # 4. 保存UP主信息 if card_data and "card" in card_data: up_info = card_data["card"] mid = up_info.get("mid") if mid: # 检查UP主表结构,打印列信息用于调试 cursor.execute("PRAGMA table_info(uploader_info)") up_table_columns = cursor.fetchall() up_column_names = [column[1] for column in up_table_columns] logger.info(f"uploader_info表中的列数: {len(up_column_names)}") logger.info(f"uploader_info表的列名: {up_column_names}") # 检查UP主是否已存在 cursor.execute("SELECT mid FROM uploader_info WHERE mid = ?", (mid,)) existing_up = cursor.fetchone() official = up_info.get("Official", {}) level_info = up_info.get("level_info", {}) vip = up_info.get("vip", {}) pendant = up_info.get("pendant", {}) nameplate = up_info.get("nameplate", {}) if existing_up: # 更新UP主信息 cursor.execute(""" UPDATE uploader_info SET name = ?, sex = ?, face = ?, face_nft = ?, face_nft_type = ?, sign = ?, rank = ?, level = ?, regtime = ?, spacesta = ?, birthday = ?, place = ?, description = ?, article = ?, fans = ?, friend = ?, attention = ?, official_role = ?, official_title = ?, official_desc = ?, official_type = ?, vip_type = ?, vip_status = ?, vip_due_date = ?, vip_pay_type = ?, vip_theme_type = ?, vip_avatar_subscript = ?, vip_nickname_color = ?, vip_role = ?, vip_avatar_subscript_url = ?, pendant_pid = ?, pendant_name = ?, pendant_image = ?, pendant_expire = ?, nameplate_nid = ?, nameplate_name = ?, nameplate_image = ?, nameplate_image_small = ?, nameplate_level = ?, nameplate_condition = ?, is_senior_member = ?, following = ?, archive_count = ?, article_count = ?, like_num = ?, update_time = ? WHERE mid = ? """, ( up_info.get("name"), up_info.get("sex"), up_info.get("face"), up_info.get("face_nft", 0), up_info.get("face_nft_type", 0), up_info.get("sign"), up_info.get("rank"), level_info.get("current_level", 0), up_info.get("regtime", 0), up_info.get("spacesta", 0), up_info.get("birthday", ""), up_info.get("place", ""), up_info.get("description", ""), up_info.get("article", 0), up_info.get("fans", 0), up_info.get("friend", 0), up_info.get("attention", 0), official.get("role", 0), official.get("title", ""), official.get("desc", ""), official.get("type", 0), vip.get("type", 0), vip.get("status", 0), vip.get("due_date", 0), vip.get("vip_pay_type", 0), vip.get("theme_type", 0), vip.get("avatar_subscript", 0), vip.get("nickname_color", ""), vip.get("role", 0), vip.get("avatar_subscript_url", ""), pendant.get("pid", 0), pendant.get("name", ""), pendant.get("image", ""), pendant.get("expire", 0), nameplate.get("nid", 0), nameplate.get("name", ""), nameplate.get("image", ""), nameplate.get("image_small", ""), nameplate.get("level", ""), nameplate.get("condition", ""), up_info.get("is_senior_member", 0), card_data.get("following", 0), card_data.get("archive_count", 0), card_data.get("article_count", 0), card_data.get("like_num", 0), now_timestamp, mid )) else: # 创建插入参数列表,便于调试 uploader_params = [ mid, # 1. mid up_info.get("name"), # 2. name up_info.get("sex"), # 3. sex up_info.get("face"), # 4. face up_info.get("face_nft", 0), # 5. face_nft up_info.get("face_nft_type", 0), # 6. face_nft_type up_info.get("sign"), # 7. sign up_info.get("rank"), # 8. rank level_info.get("current_level", 0), # 9. level up_info.get("regtime", 0), # 10. regtime up_info.get("spacesta", 0), # 11. spacesta up_info.get("birthday", ""), # 12. birthday up_info.get("place", ""), # 13. place up_info.get("description", ""), # 14. description up_info.get("article", 0), # 15. article up_info.get("fans", 0), # 16. fans up_info.get("friend", 0), # 17. friend up_info.get("attention", 0), # 18. attention official.get("role", 0), # 19. official_role official.get("title", ""), # 20. official_title official.get("desc", ""), # 21. official_desc official.get("type", 0), # 22. official_type vip.get("type", 0), # 23. vip_type vip.get("status", 0), # 24. vip_status vip.get("due_date", 0), # 25. vip_due_date vip.get("vip_pay_type", 0), # 26. vip_pay_type vip.get("theme_type", 0), # 27. vip_theme_type vip.get("avatar_subscript", 0), # 28. vip_avatar_subscript vip.get("nickname_color", ""), # 29. vip_nickname_color vip.get("role", 0), # 30. vip_role vip.get("avatar_subscript_url", ""), # 31. vip_avatar_subscript_url pendant.get("pid", 0), # 32. pendant_pid pendant.get("name", ""), # 33. pendant_name pendant.get("image", ""), # 34. pendant_image pendant.get("expire", 0), # 35. pendant_expire nameplate.get("nid", 0), # 36. nameplate_nid nameplate.get("name", ""), # 37. nameplate_name nameplate.get("image", ""), # 38. nameplate_image nameplate.get("image_small", ""), # 39. nameplate_image_small nameplate.get("level", ""), # 40. nameplate_level nameplate.get("condition", ""), # 41. nameplate_condition up_info.get("is_senior_member", 0), # 42. is_senior_member card_data.get("following", 0), # 43. following card_data.get("archive_count", 0), # 44. archive_count card_data.get("article_count", 0), # 45. article_count card_data.get("like_num", 0), # 46. like_num now_timestamp, # 47. fetch_time now_timestamp # 48. update_time ] # 打印参数数量和列数量 logger.info(f"准备插入的UP主参数数量: {len(uploader_params)}") # 确保参数数量和问号一致 # 插入新的UP主信息 cursor.execute(""" INSERT INTO uploader_info ( mid, name, sex, face, face_nft, face_nft_type, sign, rank, level, regtime, spacesta, birthday, place, description, article, fans, friend, attention, official_role, official_title, official_desc, official_type, vip_type, vip_status, vip_due_date, vip_pay_type, vip_theme_type, vip_avatar_subscript, vip_nickname_color, vip_role, vip_avatar_subscript_url, pendant_pid, pendant_name, pendant_image, pendant_expire, nameplate_nid, nameplate_name, nameplate_image, nameplate_image_small, nameplate_level, nameplate_condition, is_senior_member, following, archive_count, article_count, like_num, fetch_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 1-10 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 11-20 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 21-30 */ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, /* 31-40 */ ?, ?, ?, ?, ?, ?, ?, ? /* 41-48 */ ) """, uploader_params) # 5. 保存视频荣誉信息 if honor_reply_data: # 先删除旧的荣誉信息 cursor.execute("DELETE FROM video_honors WHERE bvid = ?", (bvid,)) # 插入新的荣誉信息 for honor in honor_reply_data: cursor.execute(""" INSERT INTO video_honors ( bvid, aid, type, desc, weekly_recommend_num ) VALUES (?, ?, ?, ?, ?) """, ( bvid, honor.get("aid", view_data.get("aid")), honor.get("type", 0), honor.get("desc", ""), honor.get("weekly_recommend_num", 0) )) # 6. 保存视频字幕信息 if subtitle_data: # 先删除旧的字幕信息 cursor.execute("DELETE FROM video_subtitles WHERE bvid = ?", (bvid,)) # 插入字幕允许提交状态 allow_submit = 1 if subtitle_data.get("allow_submit") else 0 # 插入字幕列表 subtitle_list = subtitle_data.get("list", []) if subtitle_list: for subtitle in subtitle_list: cursor.execute(""" INSERT INTO video_subtitles ( bvid, allow_submit, subtitle_id, lan, lan_doc, is_lock, subtitle_url ) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( bvid, allow_submit, subtitle.get("id", 0), subtitle.get("lan", ""), subtitle.get("lan_doc", ""), 1 if subtitle.get("is_lock") else 0, subtitle.get("subtitle_url", "") )) else: # 如果没有字幕,但有allow_submit信息,也插入一条记录 cursor.execute(""" INSERT INTO video_subtitles ( bvid, allow_submit, subtitle_id, lan, lan_doc, is_lock, subtitle_url ) VALUES (?, ?, ?, ?, ?, ?, ?) """, ( bvid, allow_submit, 0, "", "", 0, "" )) # 7. 保存相关视频信息 if related_data: # 先删除旧的相关视频信息 cursor.execute("DELETE FROM related_videos WHERE bvid = ?", (bvid,)) # 插入新的相关视频信息 for related in related_data: related_owner = related.get("owner", {}) cursor.execute(""" INSERT INTO related_videos ( bvid, related_bvid, related_aid, related_title, related_pic, related_owner_mid, related_owner_name, related_owner_face ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """, ( bvid, related.get("bvid", ""), related.get("aid", 0), related.get("title", ""), related.get("pic", ""), related_owner.get("mid", 0), related_owner.get("name", ""), related_owner.get("face", "") )) conn.commit() logger.info(f"已保存视频 {bvid} 的超详细信息到数据库") except sqlite3.Error as e: logger.error(f"保存视频详情到数据库时出错: {e}") logger.debug(f"视频详情数据: {json.dumps(data, ensure_ascii=False)}") raise @router.get("/fetch/{bvid}", summary="获取单个视频详情") async def fetch_video_detail(bvid: str): """获取并保存视频超详细信息""" try: logger.info(f"开始获取视频 {bvid} 的超详细信息") data = await get_video_detail(bvid) logger.info(f"成功获取视频 {bvid} 的API响应,准备保存到数据库") # 检查关键数据是否存在 view_data = data.get("data", {}).get("View", {}) if not view_data: logger.error(f"视频 {bvid} 的View数据不存在: {json.dumps(data, ensure_ascii=False)[:500]}") raise HTTPException(status_code=400, detail=f"视频 {bvid} 的详情数据不完整") # 检查权限数据是否存在 rights = view_data.get("rights", {}) if not rights: logger.warning(f"视频 {bvid} 的rights数据不存在,将使用空字典") # 打印权限字段列表,确认完整性 logger.info(f"视频 {bvid} 的rights字段: {list(rights.keys())}") # 打印统计字段列表 stat = view_data.get("stat", {}) logger.info(f"视频 {bvid} 的stat字段: {list(stat.keys())}") save_video_detail_to_db(data) logger.info(f"成功保存视频 {bvid} 的超详细信息到数据库") return {"status": "success", "message": f"成功获取并保存视频 {bvid} 的超详细信息"} except Exception as e: logger.exception(f"处理视频详情时出错: {e}") # 打印详细的错误堆栈 import traceback error_stack = traceback.format_exc() logger.error(f"错误堆栈: {error_stack}") raise HTTPException(status_code=500, detail=f"处理视频详情时出错: {str(e)}") @router.get("/info/{bvid}", summary="从数据库获取视频信息") async def get_video_info_from_db(bvid: str): """从数据库获取视频信息""" try: with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() # 获取视频基本信息 cursor.execute(""" SELECT * FROM video_base_info WHERE bvid = ? """, (bvid,)) video_info = cursor.fetchone() if not video_info: raise HTTPException(status_code=404, detail=f"未找到视频 {bvid} 的信息") # 转换为字典 video_info_dict = dict(video_info) # 获取视频分P信息 cursor.execute(""" SELECT * FROM video_pages WHERE bvid = ? ORDER BY page """, (bvid,)) pages = [dict(page) for page in cursor.fetchall()] video_info_dict["pages"] = pages # 获取视频标签信息 cursor.execute(""" SELECT * FROM video_tags WHERE bvid = ? """, (bvid,)) tags = [dict(tag) for tag in cursor.fetchall()] video_info_dict["tags"] = tags # 获取UP主信息 if "owner_mid" in video_info_dict and video_info_dict["owner_mid"]: cursor.execute(""" SELECT * FROM uploader_info WHERE mid = ? """, (video_info_dict["owner_mid"],)) up_info = cursor.fetchone() if up_info: video_info_dict["owner_info"] = dict(up_info) # 获取视频荣誉信息 cursor.execute(""" SELECT * FROM video_honors WHERE bvid = ? """, (bvid,)) honors = [dict(honor) for honor in cursor.fetchall()] if honors: video_info_dict["honors"] = honors # 获取视频字幕信息 cursor.execute(""" SELECT * FROM video_subtitles WHERE bvid = ? """, (bvid,)) subtitles = [dict(subtitle) for subtitle in cursor.fetchall()] if subtitles: video_info_dict["subtitles"] = subtitles # 获取相关视频信息 cursor.execute(""" SELECT * FROM related_videos WHERE bvid = ? """, (bvid,)) related_videos = [dict(related) for related in cursor.fetchall()] if related_videos: video_info_dict["related_videos"] = related_videos return video_info_dict except sqlite3.Error as e: logger.exception(f"从数据库获取视频信息时出错: {e}") raise HTTPException(status_code=500, detail=f"从数据库获取视频信息时出错: {str(e)}") @router.get("/search", summary="搜索视频") async def search_videos( keyword: str = Query(None, description="关键词"), uploader_mid: int = Query(None, description="UP主ID"), page: int = Query(1, description="页码"), per_page: int = Query(20, description="每页数量") ): """搜索视频""" try: with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() params = [] where_clauses = [] if keyword: where_clauses.append("(title LIKE ? OR desc LIKE ?)") keyword_pattern = f"%{keyword}%" params.extend([keyword_pattern, keyword_pattern]) if uploader_mid: where_clauses.append("owner_mid = ?") params.append(uploader_mid) # 构建WHERE子句 where_clause = " AND ".join(where_clauses) if where_clauses else "1=1" # 计算总数 cursor.execute(f"SELECT COUNT(*) as total FROM video_base_info WHERE {where_clause}", params) total = cursor.fetchone()["total"] # 查询数据 offset = (page - 1) * per_page query = f""" SELECT * FROM video_base_info WHERE {where_clause} ORDER BY pubdate DESC LIMIT ? OFFSET ? """ params.extend([per_page, offset]) cursor.execute(query, params) videos = [dict(video) for video in cursor.fetchall()] return { "total": total, "page": page, "per_page": per_page, "videos": videos } except sqlite3.Error as e: logger.exception(f"搜索视频时出错: {e}") raise HTTPException(status_code=500, detail=f"搜索视频时出错: {str(e)}") @router.post("/batch_fetch", summary="批量获取视频详情") async def batch_fetch_video_details(bvids: List[str]): """批量获取多个视频的超详细信息""" results = [] errors = [] for bvid in bvids: try: data = await get_video_detail(bvid) save_video_detail_to_db(data) results.append({"bvid": bvid, "status": "success"}) except Exception as e: logger.error(f"处理视频 {bvid} 详情时出错: {e}") errors.append({"bvid": bvid, "error": str(e)}) return { "success_count": len(results), "error_count": len(errors), "results": results, "errors": errors } @router.get("/batch_fetch_from_history", summary="从历史记录批量获取视频详情") async def batch_fetch_video_details_from_history( background_tasks: BackgroundTasks, max_videos: int = Query(100, description="本次最多处理的视频数量,0表示不限制"), specific_videos: Optional[str] = Query(None, description="要获取的特定视频ID列表,用逗号分隔"), use_sessdata: bool = Query(True, description="是否使用SESSDATA获取详情,某些视频需要登录才能查看"), batch_size: int = Query(20, description="批次大小,每批处理的视频数量") ): """从历史记录中获取视频ID,批量获取视频超详细信息""" try: # 获取数据库路径 db_path = os.path.join("output", "bilibili_history.db") if not os.path.exists(db_path): raise HTTPException(status_code=404, detail="历史记录数据库不存在,请先获取历史记录") # 连接数据库获取视频列表 with sqlite3.connect(db_path) as conn: cursor = conn.cursor() # 获取所有历史记录表名 cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'bilibili_history_%' """) table_names = [row[0] for row in cursor.fetchall()] if not table_names: raise HTTPException(status_code=404, detail="未找到任何历史记录表") if specific_videos: # 处理特定视频列表 video_list = [v.strip() for v in specific_videos.split(',') if v.strip()] if not video_list: raise HTTPException(status_code=400, detail="特定视频列表为空") # 验证这些视频是否在历史记录中 placeholders = ','.join(['?' for _ in video_list]) union_queries = [] for table_name in table_names: union_queries.append(f"SELECT DISTINCT bvid FROM {table_name} WHERE bvid IN ({placeholders}) AND bvid IS NOT NULL AND bvid != ''") if union_queries: union_query = " UNION ".join(union_queries) # 为每个表的查询准备参数 all_params = video_list * len(table_names) cursor.execute(union_query, all_params) else: # 获取所有历史记录中的视频 union_queries = [] for table_name in table_names: if max_videos > 0: union_queries.append(f"SELECT DISTINCT bvid, view_at FROM {table_name} WHERE bvid IS NOT NULL AND bvid != ''") else: union_queries.append(f"SELECT DISTINCT bvid, view_at FROM {table_name} WHERE bvid IS NOT NULL AND bvid != ''") if union_queries: union_query = " UNION ".join(union_queries) final_query = f"SELECT DISTINCT bvid FROM ({union_query}) ORDER BY view_at DESC" if max_videos > 0: final_query += f" LIMIT {max_videos}" cursor.execute(final_query) video_rows = cursor.fetchall() all_video_list = [row[0] for row in video_rows] if not all_video_list: return { "status": "success", "message": "没有找到需要获取详情的视频", "data": { "total_videos": 0, "success_count": 0, "error_count": 0, "results": [], "errors": [] } } # 过滤掉已存在的视频,只获取数据库中不存在的视频 video_list = [] existing_count = 0 if os.path.exists(DB_PATH): with sqlite3.connect(DB_PATH) as details_conn: details_cursor = details_conn.cursor() for bvid in all_video_list: # 检查视频是否已存在于数据库中 details_cursor.execute("SELECT 1 FROM video_base_info WHERE bvid = ? LIMIT 1", (bvid,)) if details_cursor.fetchone() is None: video_list.append(bvid) else: existing_count += 1 else: # 如果详情数据库不存在,则所有视频都需要获取 video_list = all_video_list logger.info(f"历史记录中共有 {len(all_video_list)} 个视频,其中 {existing_count} 个已存在,需要获取 {len(video_list)} 个") if not video_list: return { "status": "success", "message": f"所有视频详情都已存在,无需重复获取。历史记录总数: {len(all_video_list)},已存在: {existing_count}", "data": { "total_videos": 0, "success_count": 0, "error_count": 0, "results": [], "errors": [], "existing_count": existing_count, "total_history_videos": len(all_video_list) } } # 检查是否已有任务在运行 if video_details_progress["is_processing"]: raise HTTPException(status_code=400, detail="已有视频详情获取任务在运行中") # 重置并初始化进度状态 reset_video_details_progress() video_details_progress.update({ "is_processing": True, "total_videos": len(video_list), "start_time": time.time(), "last_update_time": time.time() }) # 使用后台任务异步执行详情获取 background_tasks.add_task( fetch_video_details_background_task, video_list, batch_size, use_sessdata ) # 立即返回响应,让用户看到任务已启动 return { "status": "success", "message": f"视频详情获取已在后台启动。历史记录总数: {len(all_video_list)},已存在: {existing_count},需要获取: {len(video_list)}", "data": { "is_processing": True, "total_videos": len(video_list), "processed_videos": 0, "success_count": 0, "failed_count": 0, "progress_percentage": 0, "elapsed_time": "0.00秒", "existing_count": existing_count, "total_history_videos": len(all_video_list) } } except Exception as e: logger.error(f"批量获取视频详情失败: {e}") raise HTTPException(status_code=500, detail=f"批量获取视频详情失败: {str(e)}") @router.get("/stats", summary="获取视频详情统计信息") async def get_video_details_database_stats(): """获取视频详情数据库统计信息""" try: # 确保数据库已初始化 init_db() # 获取历史记录数据库路径 history_db_path = os.path.join("output", "bilibili_history.db") # 获取视频详情数据库路径 details_db_path = DB_PATH if not os.path.exists(history_db_path): raise HTTPException(status_code=404, detail="历史记录数据库不存在") stats = {} # 连接历史记录数据库 with sqlite3.connect(history_db_path) as history_conn: history_cursor = history_conn.cursor() # 获取所有历史记录表名 history_cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'bilibili_history_%' """) table_names = [row[0] for row in history_cursor.fetchall()] total_videos = 0 if table_names: # 构建联合查询来获取所有年份的视频总数 union_queries = [] for table_name in table_names: union_queries.append(f"SELECT DISTINCT bvid FROM {table_name} WHERE bvid IS NOT NULL AND bvid != ''") if union_queries: union_query = " UNION ".join(union_queries) final_query = f"SELECT COUNT(*) FROM ({union_query})" history_cursor.execute(final_query) total_videos = history_cursor.fetchone()[0] stats["total_videos"] = total_videos # 如果视频详情数据库存在,获取详情统计 if os.path.exists(details_db_path): with sqlite3.connect(details_db_path) as details_conn: details_cursor = details_conn.cursor() try: # 获取已获取详情的视频数 details_cursor.execute("SELECT COUNT(DISTINCT bvid) FROM video_base_info") videos_with_details = details_cursor.fetchone()[0] stats["videos_with_details"] = videos_with_details # 获取UP主信息数量 details_cursor.execute("SELECT COUNT(*) FROM uploader_info") uploader_count = details_cursor.fetchone()[0] stats["uploader_count"] = uploader_count # 获取视频标签数量 details_cursor.execute("SELECT COUNT(*) FROM video_tags") tag_count = details_cursor.fetchone()[0] stats["tag_count"] = tag_count # 获取视频分P数量 details_cursor.execute("SELECT COUNT(*) FROM video_pages") page_count = details_cursor.fetchone()[0] stats["page_count"] = page_count except sqlite3.OperationalError as e: # 如果表不存在,设置为0 logger.warning(f"视频详情数据库表不存在: {e}") stats["videos_with_details"] = 0 stats["uploader_count"] = 0 stats["tag_count"] = 0 stats["page_count"] = 0 else: stats["videos_with_details"] = 0 stats["uploader_count"] = 0 stats["tag_count"] = 0 stats["page_count"] = 0 # 计算待获取详情的视频数 stats["videos_without_details"] = stats["total_videos"] - stats["videos_with_details"] # 计算完成百分比 if stats["total_videos"] > 0: stats["completion_percentage"] = round((stats["videos_with_details"] / stats["total_videos"]) * 100, 2) else: stats["completion_percentage"] = 0 return { "status": "success", "message": "成功获取视频详情统计数据", "data": stats } except Exception as e: logger.error(f"获取视频详情统计数据失败: {e}") raise HTTPException(status_code=500, detail=f"获取统计数据失败: {str(e)}") @router.get("/database_stats", summary="获取数据库详细统计") async def get_database_stats(): """获取数据库统计信息""" try: with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() # 获取视频总数 cursor.execute("SELECT COUNT(*) as total FROM video_base_info") total_videos = cursor.fetchone()["total"] # 获取UP主总数 cursor.execute("SELECT COUNT(*) as total FROM uploader_info") total_uploaders = cursor.fetchone()["total"] # 获取标签总数 cursor.execute("SELECT COUNT(DISTINCT tag_id) as total FROM video_tags") total_tags = cursor.fetchone()["total"] # 获取最近添加的10个视频 cursor.execute(""" SELECT bvid, title, owner_name, fetch_time FROM video_base_info ORDER BY fetch_time DESC LIMIT 10 """) recent_videos = [dict(video) for video in cursor.fetchall()] return { "total_videos": total_videos, "total_uploaders": total_uploaders, "total_tags": total_tags, "recent_videos": recent_videos, "database_path": DB_PATH } except sqlite3.Error as e: logger.exception(f"获取数据库统计信息时出错: {e}") raise HTTPException(status_code=500, detail=f"获取数据库统计信息时出错: {str(e)}") @router.get("/uploaders", summary="获取UP主列表") async def list_uploaders( page: int = Query(1, description="页码"), per_page: int = Query(20, description="每页数量"), order_by: str = Query("fans", description="排序字段") ): """获取UP主列表""" valid_order_fields = ["mid", "name", "fans", "archive_count", "like_num", "fetch_time"] if order_by not in valid_order_fields: order_by = "fans" try: with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() # 计算总数 cursor.execute("SELECT COUNT(*) as total FROM uploader_info") total = cursor.fetchone()["total"] # 查询数据 offset = (page - 1) * per_page query = f""" SELECT * FROM uploader_info ORDER BY {order_by} DESC LIMIT ? OFFSET ? """ cursor.execute(query, (per_page, offset)) uploaders = [dict(uploader) for uploader in cursor.fetchall()] return { "total": total, "page": page, "per_page": per_page, "uploaders": uploaders } except sqlite3.Error as e: logger.exception(f"获取UP主列表时出错: {e}") raise HTTPException(status_code=500, detail=f"获取UP主列表时出错: {str(e)}") @router.get("/tags", summary="获取视频标签列表") async def list_tags( page: int = Query(1, description="页码"), per_page: int = Query(100, description="每页数量") ): """获取标签列表""" try: with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() # 计算总数 cursor.execute("SELECT COUNT(DISTINCT tag_id) as total FROM video_tags") total = cursor.fetchone()["total"] # 查询数据 offset = (page - 1) * per_page query = """ SELECT tag_id, tag_name, COUNT(*) as video_count FROM video_tags GROUP BY tag_id, tag_name ORDER BY video_count DESC LIMIT ? OFFSET ? """ cursor.execute(query, (per_page, offset)) tags = [dict(tag) for tag in cursor.fetchall()] return { "total": total, "page": page, "per_page": per_page, "tags": tags } except sqlite3.Error as e: logger.exception(f"获取标签列表时出错: {e}") raise HTTPException(status_code=500, detail=f"获取标签列表时出错: {str(e)}") @router.get("/uploader/{mid}", summary="获取UP主详细信息") async def get_uploader_details(mid: int): """获取UP主详细信息及其视频列表""" try: with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() # 获取UP主基本信息 cursor.execute("SELECT * FROM uploader_info WHERE mid = ?", (mid,)) uploader = cursor.fetchone() if not uploader: raise HTTPException(status_code=404, detail=f"未找到UP主 {mid} 的信息") uploader_dict = dict(uploader) # 获取UP主的视频列表 cursor.execute(""" SELECT * FROM video_base_info WHERE owner_mid = ? ORDER BY pubdate DESC LIMIT 50 """, (mid,)) videos = [dict(video) for video in cursor.fetchall()] uploader_dict["videos"] = videos return uploader_dict except sqlite3.Error as e: logger.exception(f"获取UP主 {mid} 详情时出错: {e}") raise HTTPException(status_code=500, detail=f"获取UP主详情时出错: {str(e)}") async def fetch_video_details_background_task(video_list: List[str], batch_size: int, use_sessdata: bool): """后台任务:批量获取视频详情,支持秒级进度更新和停止功能""" try: logger.info(f"开始后台批量获取 {len(video_list)} 个视频的超详细信息") # 初始化数据库(确保表结构存在) try: init_db() logger.info("数据库初始化完成") except Exception as e: logger.error(f"数据库初始化失败: {e}") raise # 随机打乱视频顺序,避免按顺序请求被检测 random.shuffle(video_list) # 降低并发线程数,避免过高并发导致412错误 max_workers = min(8, batch_size) # 进一步降低并发数 # 获取配置和cookie config = load_config() cookies = config.get("cookies", {}) cookie_str = "; ".join([f"{k}={v}" for k, v in cookies.items()]) if cookies else "" cookie_to_use = cookie_str if use_sessdata else "" # 分批处理视频,每批之间有延迟 total_videos = len(video_list) # 按批次处理视频 for i in range(0, total_videos, batch_size): batch_videos = video_list[i:i + batch_size] batch_num = i // batch_size + 1 total_batches = (total_videos + batch_size - 1) // batch_size logger.info(f"开始处理第 {batch_num}/{total_batches} 批,包含 {len(batch_videos)} 个视频") # 检查是否被用户停止 if video_details_progress["is_stopped"]: logger.info("用户停止了视频详情获取任务") break # 使用线程池处理当前批次的视频 with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: # 提交当前批次的任务 future_to_bvid = { executor.submit(get_video_detail_sync, bvid, cookie_to_use, use_sessdata): bvid for bvid in batch_videos } # 逐个处理完成的任务,实现秒级更新 for future in concurrent.futures.as_completed(future_to_bvid): # 检查是否被用户停止 if video_details_progress["is_stopped"]: logger.info("用户停止了视频详情获取任务") # 取消剩余的任务 for remaining_future in future_to_bvid: if not remaining_future.done(): remaining_future.cancel() break bvid = future_to_bvid[future] try: # 在处理前再次检查是否已存在(防止并发情况下的重复) with sqlite3.connect(DB_PATH) as check_conn: check_cursor = check_conn.cursor() check_cursor.execute("SELECT 1 FROM video_base_info WHERE bvid = ? LIMIT 1", (bvid,)) if check_cursor.fetchone() is not None: logger.info(f"视频 {bvid} 已存在于数据库中,跳过") video_details_progress["skipped_invalid_count"] += 1 video_details_progress["processed_videos"] += 1 video_details_progress["last_update_time"] = time.time() continue result = future.result() if result and result.get("code") == 0: # 保存到数据库 try: save_video_detail_to_db(result) video_details_progress["success_count"] += 1 logger.info(f"成功获取并保存视频 {bvid} 的详情") except Exception as e: logger.error(f"保存视频 {bvid} 详情到数据库失败: {e}") video_details_progress["failed_count"] += 1 video_details_progress["error_videos"].append(bvid) else: video_details_progress["failed_count"] += 1 video_details_progress["error_videos"].append(bvid) error_msg = result.get("message", "未知错误") if result else "请求失败" logger.warning(f"获取视频 {bvid} 详情失败: {error_msg}") except Exception as e: logger.error(f"获取视频 {bvid} 详情失败: {e}") video_details_progress["failed_count"] += 1 video_details_progress["error_videos"].append(bvid) # 更新进度(每个视频完成后立即更新) video_details_progress["processed_videos"] += 1 video_details_progress["last_update_time"] = time.time() # 添加小延迟,避免请求过快 await asyncio.sleep(0.1 + random.random() * 0.2) # 0.1-0.3秒随机延迟 # 批次间延迟(除了最后一批) if batch_num < total_batches and not video_details_progress["is_stopped"]: delay_time = 3 + random.random() * 2 # 3-5秒随机延迟 logger.info(f"第 {batch_num} 批处理完成,等待 {delay_time:.1f} 秒后处理下一批") await asyncio.sleep(delay_time) # 任务完成或被停止 video_details_progress["is_processing"] = False video_details_progress["is_complete"] = True video_details_progress["last_update_time"] = time.time() if video_details_progress["is_stopped"]: logger.info(f"视频详情获取被用户停止,已处理: {video_details_progress['processed_videos']}/{len(video_list)}") else: logger.info(f"批量获取视频详情完成,成功: {video_details_progress['success_count']}, 失败: {video_details_progress['failed_count']}") except Exception as e: logger.error(f"后台获取视频详情任务失败: {e}") video_details_progress["is_processing"] = False video_details_progress["is_complete"] = True video_details_progress["last_update_time"] = time.time() def reset_video_details_progress(): """重置视频详情进度状态到初始状态""" global video_details_progress video_details_progress.update({ "is_processing": False, "is_complete": False, "is_stopped": False, "total_videos": 0, "processed_videos": 0, "success_count": 0, "failed_count": 0, "error_videos": [], "skipped_invalid_count": 0, "start_time": 0, "last_update_time": 0 }) @router.post("/stop", summary="停止视频详情获取任务") async def stop_video_details_fetch(): """停止视频详情获取任务""" try: if not video_details_progress["is_processing"]: # 如果没有正在运行的任务,直接重置状态 reset_video_details_progress() return { "status": "success", "message": "当前没有正在运行的任务,已重置状态" } # 设置停止标志 video_details_progress["is_stopped"] = True video_details_progress["last_update_time"] = time.time() logger.info("用户请求停止视频详情获取任务") # 等待一小段时间让后台任务处理停止信号 await asyncio.sleep(0.5) # 强制重置状态到初始状态 reset_video_details_progress() return { "status": "success", "message": "任务已停止,状态已重置", "data": { "is_processing": False, "is_complete": False, "is_stopped": False } } except Exception as e: logger.error(f"停止视频详情获取任务失败: {e}") raise HTTPException(status_code=500, detail=f"停止任务失败: {str(e)}") @router.post("/reset", summary="重置视频详情获取状态") async def reset_video_details_status(): """重置视频详情获取状态到初始状态""" try: reset_video_details_progress() logger.info("用户手动重置了视频详情获取状态") return { "status": "success", "message": "状态已重置到初始状态", "data": { "is_processing": False, "is_complete": False, "is_stopped": False, "total_videos": 0, "processed_videos": 0, "success_count": 0, "failed_count": 0 } } except Exception as e: logger.error(f"重置视频详情状态失败: {e}") raise HTTPException(status_code=500, detail=f"重置状态失败: {str(e)}") @router.get("/progress", summary="获取视频详情获取进度") async def get_video_details_progress( update_interval: float = Query(0.1, description="更新间隔,单位秒") ): """获取视频详情获取进度的SSE流""" async def generate_progress(): while True: # 计算进度百分比 progress_percentage = 0 if video_details_progress["total_videos"] > 0: progress_percentage = (video_details_progress["processed_videos"] / video_details_progress["total_videos"]) * 100 # 计算已用时间 elapsed_time = "0.00秒" if video_details_progress["start_time"] > 0: elapsed_seconds = time.time() - video_details_progress["start_time"] elapsed_time = f"{elapsed_seconds:.2f}秒" # 构建进度数据 progress_data = { "is_processing": video_details_progress["is_processing"], "is_complete": video_details_progress["is_complete"], "is_stopped": video_details_progress["is_stopped"], "total_videos": video_details_progress["total_videos"], "processed_videos": video_details_progress["processed_videos"], "success_count": video_details_progress["success_count"], "failed_count": video_details_progress["failed_count"], "error_videos": video_details_progress["error_videos"], "skipped_invalid_count": video_details_progress["skipped_invalid_count"], "progress_percentage": progress_percentage, "elapsed_time": elapsed_time, "last_update_time": video_details_progress["last_update_time"] } # 发送数据 yield f"data: {json.dumps(progress_data, ensure_ascii=False)}\n\n" # 如果任务完成或停止,发送最后一次数据后退出 if video_details_progress["is_complete"] or video_details_progress["is_stopped"]: break # 等待指定的更新间隔 await asyncio.sleep(update_interval) return StreamingResponse( generate_progress(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*" } )
2929004360/ruoyi-sign
999
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/FlowTaskMapper.java
package com.ruoyi.flowable.mapper; import org.apache.ibatis.annotations.Param; import org.flowable.engine.runtime.ActivityInstance; import java.util.Date; import java.util.List; public interface FlowTaskMapper { List<ActivityInstance> queryActivityInstance(@Param("disActivityId") String disActivityId, @Param("processInstanceId") String processInstanceId, @Param("endTime") Date endTime); /** * 删除运行节点表信息 * * @param runActivityIds */ void deleteRunActinstsByIds(List<String> runActivityIds); /** * 删除历史节点表信息 * * @param runActivityIds */ void deleteHisActinstsByIds(List<String> runActivityIds); /** * 通过流程实例id,删除运行中的任务和历史相关数据,目前主要针对自定义业务 * * @param processInstanceId */ void deleteAllHisAndRun(String processInstanceId); int querySubTaskByParentTaskId(@Param("parentTaskId") String parentTaskId); }
2977094657/BilibiliHistoryFetcher
6,304
routers/email_config.py
from typing import Optional from fastapi import APIRouter, Body, HTTPException from pydantic import BaseModel, EmailStr import yaml import os import re from scripts.utils import load_config from scripts.send_log_email import send_email router = APIRouter() def get_config_path(): """获取配置文件路径""" base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) return os.path.join(base_dir, 'config', 'config.yaml') def update_yaml_field(content: str, field_path: list, new_value: Optional[str]) -> str: """ 更新YAML文件中特定字段的值,保持其他内容不变 Args: content: YAML文件内容 field_path: 字段路径,如 ['email', 'smtp_server'] new_value: 新的值,如果为None则删除该字段 """ # 构建YAML路径的正则表达式 indent = ' ' * (2 * (len(field_path) - 1)) # YAML标准缩进 field = field_path[-1] pattern = f"^{indent}{field}:.*$" # 处理多行内容 lines = content.split('\n') for i, line in enumerate(lines): if re.match(pattern, line, re.MULTILINE): if new_value is None or new_value == "": lines[i] = f"{indent}{field}:" # 设置为空值 else: lines[i] = f"{indent}{field}: {new_value}" break return '\n'.join(lines) class EmailConfig(BaseModel): """邮件配置模型""" smtp_server: Optional[str] = None smtp_port: Optional[int] = None sender: Optional[EmailStr] = None password: Optional[str] = None receiver: Optional[EmailStr] = None class TestEmailRequest(BaseModel): """测试邮件请求模型""" to_email: Optional[EmailStr] = None # 可选,如果为空则使用配置中的接收者邮箱 subject: str = "测试邮件" content: str = "这是一封测试邮件,用于验证邮箱配置是否有效。" @router.get("/email-config", summary="获取邮件配置") async def get_email_config(): """获取当前邮件配置""" try: config = load_config() email_config = config.get('email', {}) return { "smtp_server": email_config.get('smtp_server'), "smtp_port": email_config.get('smtp_port'), "sender": email_config.get('sender'), "receiver": email_config.get('receiver'), "password": email_config.get('password') # 返回明文密码 } except Exception as e: raise HTTPException( status_code=500, detail=f"获取邮件配置失败: {str(e)}" ) @router.post("/email-config", summary="更新邮件配置") async def update_email_config( smtp_server: Optional[str] = Body(default=...), smtp_port: Optional[int] = Body(default=...), sender: Optional[str] = Body(default=...), # 改为str类型以接受空字符串 password: Optional[str] = Body(default=...), receiver: Optional[str] = Body(default=...) # 改为str类型以接受空字符串 ): """ 更新邮件配置 - **smtp_server**: SMTP服务器地址,可以为空 - **smtp_port**: SMTP服务器端口,可以为空 - **sender**: 发件人邮箱,可以为空 - **password**: 邮箱授权码,可以为空 - **receiver**: 收件人邮箱,可以为空 """ try: # 读取当前配置文件内容 config_path = get_config_path() with open(config_path, 'r', encoding='utf-8') as f: content = f.read() config = yaml.safe_load(content) # 仅用于获取当前配置 # 获取当前邮件配置 email_config = config.get('email', {}) # 逐个更新配置字段 if smtp_server is not ...: # 检查是否提供了该参数 value = f'"{smtp_server}"' if smtp_server else None content = update_yaml_field(content, ['email', 'smtp_server'], value) email_config['smtp_server'] = smtp_server if smtp_port is not ...: value = str(smtp_port) if smtp_port is not None else None content = update_yaml_field(content, ['email', 'smtp_port'], value) email_config['smtp_port'] = smtp_port if sender is not ...: value = f'"{sender}"' if sender else None content = update_yaml_field(content, ['email', 'sender'], value) email_config['sender'] = sender if password is not ...: value = f'"{password}"' if password else None content = update_yaml_field(content, ['email', 'password'], value) email_config['password'] = password if receiver is not ...: value = f'"{receiver}"' if receiver else None content = update_yaml_field(content, ['email', 'receiver'], value) email_config['receiver'] = receiver # 写回配置文件 with open(config_path, 'w', encoding='utf-8') as f: f.write(content) return { "status": "success", "message": "邮件配置更新成功", "config": { "smtp_server": email_config.get('smtp_server'), "smtp_port": email_config.get('smtp_port'), "sender": email_config.get('sender'), "receiver": email_config.get('receiver'), "password": email_config.get('password') # 返回明文密码 } } except Exception as e: raise HTTPException( status_code=500, detail=f"更新邮件配置失败: {str(e)}" ) @router.post("/test-email", summary="发送测试邮件") async def send_test_email(request: TestEmailRequest): """ 发送测试邮件以验证邮箱配置是否有效 - **to_email**: 收件人邮箱,可选,如果为空则使用配置中的收件人 - **subject**: 邮件主题,默认为"测试邮件" - **content**: 邮件内容,默认为"这是一封测试邮件,用于验证邮箱配置是否有效。" 返回: - **status**: 发送状态,"success"或"error" - **message**: 状态描述信息 """ try: # 获取当前邮件配置 config = load_config() email_config = config.get('email', {}) # 检查邮件配置是否完整 if not all([ email_config.get('smtp_server'), email_config.get('smtp_port'), email_config.get('sender'), email_config.get('password'), request.to_email or email_config.get('receiver') ]): raise ValueError("邮件配置不完整,请先完善邮件配置") # 发送测试邮件 result = await send_email( subject=request.subject, content=request.content, to_email=request.to_email ) return result except ValueError as e: raise HTTPException( status_code=400, detail=str(e) ) except Exception as e: raise HTTPException( status_code=500, detail=f"发送测试邮件失败: {str(e)}" )
2977094657/BilibiliHistoryFetcher
10,806
routers/popular_videos.py
from fastapi import APIRouter, Query, HTTPException, BackgroundTasks from typing import Dict, Any, List, Optional from pydantic import BaseModel import asyncio import time from datetime import datetime from scripts.popular_videos import ( get_all_popular_videos, query_recent_videos, get_fetch_history, get_video_tracking_stats, cleanup_inactive_video_records ) # 创建路由器 router = APIRouter() class PopularVideosResponse(BaseModel): status: str message: Optional[str] = None total_videos: Optional[int] = None fetch_stats: Optional[Dict[str, Any]] = None data: Optional[List[Dict[str, Any]]] = None task_id: Optional[str] = None class FetchHistoryResponse(BaseModel): status: str message: Optional[str] = None data: Optional[List[Dict[str, Any]]] = None class TrackingStatsResponse(BaseModel): status: str message: Optional[str] = None total: Optional[int] = None data: Optional[List[Dict[str, Any]]] = None # 用于存储后台任务的状态和清理机制 task_status = {} MAX_TASKS_HISTORY = 100 # 最多保存的任务数量 TASK_EXPIRY_TIME = 3600 # 任务过期时间(秒) # 清理过期任务 def cleanup_old_tasks(): """清理过期的任务""" current_time = time.time() expired_tasks = [] for task_id, task_info in task_status.items(): # 检查任务是否有时间戳,如果没有则添加 if "timestamp" not in task_info: task_info["timestamp"] = current_time continue # 检查任务是否已完成且超过过期时间 if (task_info["status"] in ["completed", "failed"] and current_time - task_info["timestamp"] > TASK_EXPIRY_TIME): expired_tasks.append(task_id) # 删除过期任务 for task_id in expired_tasks: del task_status[task_id] # 如果任务数量过多,按时间戳删除最旧的任务 if len(task_status) > MAX_TASKS_HISTORY: # 按时间戳排序 sorted_tasks = sorted( task_status.items(), key=lambda x: x[1].get("timestamp", 0) ) # 计算需要删除的任务数量 tasks_to_remove = len(task_status) - MAX_TASKS_HISTORY # 删除最旧的任务 for i in range(tasks_to_remove): if i < len(sorted_tasks): del task_status[sorted_tasks[i][0]] @router.get("/popular/all", summary="获取B站所有热门视频", response_model=PopularVideosResponse) async def get_all_popular_videos_api( background_tasks: BackgroundTasks, size: int = Query(20, description="每页视频数量", ge=1, le=50), max_pages: int = Query(100, description="最大获取页数", ge=1, le=500), save_to_db: bool = Query(True, description="是否保存到数据库"), include_videos: bool = Query(False, description="是否在响应中包含视频数据") ): """ 获取B站当前所有热门视频并保存到数据库(异步后台处理) 此接口会立即返回一个任务ID,然后在后台处理获取视频的请求。 使用返回的任务ID通过 `/popular/task/{task_id}` 端点查询任务状态和结果。 - **size**: 每页视频数量,默认为20,范围1-50 - **max_pages**: 最大获取页数,默认为100,范围1-500 - **save_to_db**: 是否保存到数据库,默认为True - **include_videos**: 是否在响应中包含视频数据,默认为False 返回: - **status**: 请求状态,"accepted"表示已接受任务 - **message**: 状态消息 - **task_id**: 用于查询任务状态的唯一ID """ # 清理过期任务 cleanup_old_tasks() # 生成唯一任务ID import uuid task_id = str(uuid.uuid4()) # 创建初始状态响应 task_status[task_id] = { "status": "processing", "message": "任务已开始处理", "progress": 0, "result": None, "timestamp": time.time() } # 定义后台任务函数 async def process_popular_videos_task(): try: # 定义进度回调函数 def update_progress(progress, message, current_page, total_pages, success=True): nonlocal task_id task_status[task_id].update({ "status": "processing" if success else "error", "message": message, "progress": progress, "current_page": current_page, "total_pages": total_pages, "timestamp": time.time() # 更新时间戳 }) # 在后台线程中执行耗时操作 loop = asyncio.get_event_loop() videos, success, fetch_stats = await loop.run_in_executor( None, lambda: get_all_popular_videos( page_size=size, max_pages=max_pages, save_to_db=save_to_db, progress_callback=update_progress ) ) # 构建结果 result = { "status": "success" if success else "error", "total_videos": len(videos), "fetch_stats": fetch_stats["fetch_stats"] if "fetch_stats" in fetch_stats else fetch_stats } # 如果需要包含视频数据 if include_videos and videos: result["data"] = videos if not success: result["message"] = fetch_stats.get("message", "获取热门视频失败") # 更新任务状态为完成 task_status[task_id] = { "status": "completed" if success else "failed", "progress": 100, "result": result, "timestamp": time.time(), "message": "热门视频获取完成" if success else fetch_stats.get("message", "获取热门视频失败") } except Exception as e: # 更新任务状态为失败 task_status[task_id] = { "status": "failed", "message": f"处理任务失败: {str(e)}", "progress": 0, "result": None, "timestamp": time.time() } # 添加到后台任务 background_tasks.add_task(process_popular_videos_task) # 立即返回响应,不等待任务完成 return PopularVideosResponse( status="accepted", message="任务已开始处理,请使用任务ID查询进度", task_id=task_id ) @router.get("/popular/task/{task_id}", summary="获取热门视频获取任务状态") async def get_task_status(task_id: str): """ 获取热门视频获取任务的处理状态和结果 使用从 `/popular/all` 接口获取的任务ID查询任务进度和结果。 - 如果任务仍在处理中,将返回进度信息 - 如果任务已完成,将返回完整的结果 - 如果任务失败,将返回错误信息 任务状态会在服务器上保留一段时间(默认1小时),过期后会被自动清理。 """ if task_id not in task_status: raise HTTPException(status_code=404, detail="未找到指定任务ID") task_info = task_status[task_id] # 如果任务完成且有结果,返回结果 if task_info["status"] == "completed" and task_info["result"]: return task_info["result"] # 否则返回任务状态 return { "status": task_info["status"], "message": task_info.get("message", "任务正在处理中"), "progress": task_info.get("progress", 0) } @router.get("/popular/recent", summary="获取最近保存的热门视频", response_model=PopularVideosResponse) async def get_recent_popular_videos_api( limit: int = Query(20, description="返回视频的数量限制", ge=1, le=200) ): """ 从数据库获取最近保存的热门视频 - **limit**: 返回视频的数量限制,默认为20 """ try: # 从数据库查询最近的热门视频 videos = query_recent_videos(limit=limit) if not videos: return PopularVideosResponse( status="success", message="未找到任何热门视频记录", total_videos=0, data=[] ) return PopularVideosResponse( status="success", total_videos=len(videos), data=videos ) except Exception as e: raise HTTPException( status_code=500, detail=f"获取热门视频记录失败: {str(e)}" ) @router.get("/popular/history", summary="获取热门视频抓取历史", response_model=FetchHistoryResponse) async def get_fetch_history_api( limit: int = Query(10, description="返回历史记录的数量限制", ge=1, le=100) ): """ 获取热门视频的抓取历史记录 - **limit**: 返回历史记录的数量限制,默认为10 """ try: # 获取抓取历史记录 history = get_fetch_history(limit=limit) if not history: return FetchHistoryResponse( status="success", message="未找到任何抓取历史记录", data=[] ) return FetchHistoryResponse( status="success", data=history ) except Exception as e: raise HTTPException( status_code=500, detail=f"获取抓取历史记录失败: {str(e)}" ) @router.get("/popular/tracking", summary="获取视频热门持续时间统计", response_model=TrackingStatsResponse) async def get_video_tracking_stats_api( limit: int = Query(20, description="返回视频的数量限制", ge=1, le=100) ): """ 获取视频在热门列表中持续时间的统计信息 - **limit**: 返回视频的数量限制,默认为20 """ try: # 获取视频热门跟踪统计 stats = get_video_tracking_stats(limit=limit) if not stats: return TrackingStatsResponse( status="success", message="未找到任何视频热门跟踪记录", total=0, data=[] ) return TrackingStatsResponse( status="success", total=len(stats), data=stats ) except Exception as e: raise HTTPException( status_code=500, detail=f"获取视频热门跟踪统计失败: {str(e)}" ) @router.get("/popular/tasks", summary="获取所有热门视频获取任务") async def list_all_tasks(): """ 获取所有热门视频获取任务的状态列表 返回当前服务器上所有正在处理中和已完成的热门视频获取任务, 包括每个任务的ID、状态、进度和创建时间等信息。 可以使用返回的任务ID通过 `/popular/task/{task_id}` 端点查询具体任务的详细信息。 """ # 清理过期任务 cleanup_old_tasks() # 返回任务基本信息 tasks_info = {} for task_id, task_info in task_status.items(): task_summary = { "status": task_info["status"], "message": task_info.get("message", ""), "progress": task_info.get("progress", 0), "timestamp": task_info.get("timestamp", 0), "created": datetime.fromtimestamp( task_info.get("timestamp", 0) ).strftime("%Y-%m-%d %H:%M:%S") if task_info.get("timestamp") else "" } tasks_info[task_id] = task_summary return { "status": "success", "total_tasks": len(tasks_info), "tasks": tasks_info } @router.post("/popular/cleanup", summary="清理已经不在热门列表的视频数据") async def trigger_data_cleanup(background_tasks: BackgroundTasks): """ 触发清理已经不在热门列表的视频数据的操作 此操作会删除所有已经不在热门列表的视频中间的记录,只保留首条和末条记录。 由于清理操作可能需要较长时间,此API会在后台执行清理并立即返回。 清理结果将记录在日志中。 """ # 定义后台任务函数 async def run_cleanup_task(): # 在异步上下文中执行同步耗时操作 loop = asyncio.get_event_loop() try: # 使用run_in_executor在线程池中执行同步操作 stats = await loop.run_in_executor(None, cleanup_inactive_video_records) print(f"数据清理完成,统计信息:{stats}") except Exception as e: print(f"数据清理过程中出错:{str(e)}") # 添加到后台任务 background_tasks.add_task(run_cleanup_task) # 立即返回响应 return { "status": "accepted", "message": "数据清理任务已开始,将在后台执行。结果将记录在日志中。" }
2929004360/ruoyi-sign
1,079
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfIconMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfIcon; import java.util.List; /** * 流程图标Mapper接口 * * @author fengcheng * @date 2024-07-09 */ public interface WfIconMapper { /** * 查询流程图标 * * @param deploymentId 流程图标主键 * @return 流程图标 */ public WfIcon selectWfIconByDeploymentId(String deploymentId); /** * 查询流程图标列表 * * @param wfIcon 流程图标 * @return 流程图标集合 */ public List<WfIcon> selectWfIconList(WfIcon wfIcon); /** * 新增流程图标 * * @param wfIcon 流程图标 * @return 结果 */ public int insertWfIcon(WfIcon wfIcon); /** * 修改流程图标 * * @param wfIcon 流程图标 * @return 结果 */ public int updateWfIcon(WfIcon wfIcon); /** * 删除流程图标 * * @param deploymentId 流程图标主键 * @return 结果 */ public int deleteWfIconByDeploymentId(String deploymentId); /** * 批量删除流程图标 * * @param deploymentIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfIconByDeploymentIds(String[] deploymentIds); }
2929004360/ruoyi-sign
1,071
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfFormMapper.java
package com.ruoyi.flowable.mapper; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.toolkit.Constants; import com.ruoyi.flowable.base.BaseMapperPlus; import com.ruoyi.flowable.domain.WfForm; import com.ruoyi.flowable.domain.bo.WfFormBo; import com.ruoyi.flowable.domain.vo.WfFormVo; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 流程表单Mapper接口 * * @author fengcheng * @createTime 2022/3/7 22:07 */ public interface WfFormMapper extends BaseMapperPlus<WfFormMapper, WfForm, WfFormVo> { /** * 查询流程表单列表 * * @param queryWrapper * @return */ List<WfFormVo> selectFormVoList(@Param(Constants.WRAPPER) Wrapper<WfForm> queryWrapper); /** * 查询流程表单列表 * * @param wfForm 流程表单 * @param deptIdList 子部门id数据 * @param ancestorsList 祖父部门id数据 * @return 流程表单 */ List<WfFormVo> selectWfFormList(@Param("wfForm") WfFormBo wfForm, @Param("deptIdList") List<Long> deptIdList, @Param("ancestorsList") List<Long> ancestorsList); }
2929004360/ruoyi-sign
1,694
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfModelAssociationTemplateMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfModelAssociationTemplate; import java.util.List; /** * 模型关联模板Mapper接口 * * @author fengcheng * @date 2024-07-23 */ public interface WfModelAssociationTemplateMapper { /** * 查询模型关联模板 * * @param modelTemplateId 模型关联模板主键 * @return 模型关联模板 */ public WfModelAssociationTemplate selectWfModelAssociationTemplateByModelTemplateId(String modelTemplateId); /** * 查询模型关联模板列表 * * @param wfModelAssociationTemplate 模型关联模板 * @return 模型关联模板集合 */ public List<WfModelAssociationTemplate> selectWfModelAssociationTemplateList(WfModelAssociationTemplate wfModelAssociationTemplate); /** * 新增模型关联模板 * * @param wfModelAssociationTemplate 模型关联模板 * @return 结果 */ public int insertWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate); /** * 修改模型关联模板 * * @param wfModelAssociationTemplate 模型关联模板 * @return 结果 */ public int updateWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate); /** * 删除模型关联模板 * * @param modelTemplateId 模型关联模板主键 * @return 结果 */ public int deleteWfModelAssociationTemplateByModelTemplateId(String modelTemplateId); /** * 批量删除模型关联模板 * * @param modelTemplateIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfModelAssociationTemplateByModelTemplateIds(String[] modelTemplateIds); /** * 删除模型关联模板信息 * * @param wfModelAssociationTemplate */ int deleteWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate); }
2977094657/BilibiliHistoryFetcher
6,402
routers/fetch_bili_history.py
from typing import Optional, Union from fastapi import APIRouter, Query, HTTPException from loguru import logger from pydantic import BaseModel, Field from scripts.bilibili_history import fetch_history, find_latest_local_history, fetch_and_compare_history, save_history, \ load_cookie, get_invalid_videos_from_db from scripts.import_sqlite import import_all_history_files from scripts.utils import load_config, setup_logger # 确保日志系统已初始化 setup_logger() router = APIRouter() config = load_config() # 定义请求体模型 class FetchHistoryRequest(BaseModel): sessdata: Optional[str] = Field(None, description="用户的 SESSDATA") # 定义响应模型 class ResponseModel(BaseModel): status: str message: str data: Optional[Union[list, dict]] = None def get_headers(): """获取请求头""" # 动态读取配置文件,获取最新的SESSDATA current_config = load_config() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Cookie': f'SESSDATA={current_config["SESSDATA"]}' } return headers @router.get("/bili-history", summary="获取B站历史记录") async def get_bili_history(output_dir: Optional[str] = "history_by_date", skip_exists: bool = True, process_video_details: bool = False): """获取B站历史记录""" try: result = await fetch_history(output_dir, skip_exists, process_video_details) return { "status": "success", "message": "历史记录获取成功", "data": result } except Exception as e: return { "status": "error", "message": f"获取历史记录失败: {str(e)}" } @router.get("/bili-history-realtime", summary="实时获取B站历史记录", response_model=ResponseModel) async def get_bili_history_realtime(sync_deleted: bool = False, process_video_details: bool = False): """实时获取B站历史记录""" try: # 获取最新的本地历史记录时间戳 latest_history = find_latest_local_history() if not latest_history: return {"status": "error", "message": "未找到本地历史记录"} # 获取cookie cookie = load_cookie() if not cookie: return {"status": "error", "message": "未找到有效的cookie"} # 获取新的历史记录 - 使用await,因为fetch_and_compare_history现在是异步函数 new_records = await fetch_and_compare_history(cookie, latest_history, True, process_video_details) # 传递process_video_details参数 # 保存新历史记录的结果信息 history_result = {"new_records_count": 0, "inserted_count": 0} video_details_result = {"processed": False} if new_records: # 保存新记录 save_result = save_history(new_records) logger.info("成功保存新记录到本地文件") history_result["new_records_count"] = len(new_records) # 更新SQLite数据库 logger.info("=== 开始更新SQLite数据库 ===") logger.info(f"同步已删除记录: {sync_deleted}") db_result = import_all_history_files(sync_deleted=sync_deleted) if db_result["status"] == "success": history_result["inserted_count"] = db_result['inserted_count'] history_result["status"] = "success" else: history_result["status"] = "error" history_result["message"] = db_result["message"] else: history_result["status"] = "success" history_result["message"] = "没有新记录" # 处理视频详情 - 已经在fetch_and_compare_history中处理过,这里不需要重复处理 # 只需生成结果信息 if process_video_details: logger.info("视频详情已在历史记录获取过程中处理") video_details_result = { "status": "success", "message": "视频详情已在历史记录获取过程中处理", "processed": True } # 返回综合结果 if history_result.get("status") == "success" and (not process_video_details or video_details_result.get("status") == "success"): message = "实时更新成功" if history_result.get("new_records_count", 0) > 0: message += f",获取到 {history_result['new_records_count']} 条新记录" if history_result.get("inserted_count", 0) > 0: message += f",成功导入 {history_result['inserted_count']} 条记录到SQLite数据库" else: message += ",暂无新历史记录" if process_video_details: message += "。视频详情已在历史记录获取过程中处理" return { "status": "success", "message": message, "data": { "history": history_result, "video_details": video_details_result.get("data", {}) } } else: # 有一个失败就返回错误 error_message = [] if history_result.get("status") == "error": error_message.append(f"历史记录处理失败: {history_result.get('message', '未知错误')}") if process_video_details and video_details_result.get("status") == "error": error_message.append(f"视频详情处理失败: {video_details_result.get('message', '未知错误')}") return { "status": "error", "message": " | ".join(error_message), "data": { "history": history_result, "video_details": video_details_result.get("data", {}) } } except Exception as e: error_msg = f"实时更新失败: {str(e)}" logger.error(error_msg) import traceback logger.error(traceback.format_exc()) # 添加详细的堆栈跟踪 return {"status": "error", "message": error_msg} # 全局变量,用于存储处理进度 video_details_progress = { "is_processing": False, "total_videos": 0, "processed_videos": 0, "success_count": 0, "failed_count": 0, "error_videos": [], "skipped_invalid_count": 0, "start_time": 0, "last_update_time": 0, "is_complete": False } # 添加新的API端点用于查询失效视频列表 @router.get("/invalid-videos", summary="获取失效视频列表") async def get_invalid_videos( page: int = Query(1, description="页码,从1开始"), limit: int = Query(50, description="每页返回数量,最大100"), error_type: Optional[str] = Query(None, description="按错误类型筛选") ): """获取失效视频列表""" try: result = await get_invalid_videos_from_db(page, limit, error_type) return result except Exception as e: print(f"获取失效视频列表失败: {str(e)}") raise HTTPException( status_code=500, detail=f"获取失效视频列表失败: {str(e)}" )
2977094657/BilibiliHistoryFetcher
4,040
routers/export.py
from fastapi import APIRouter, HTTPException, Query from fastapi.responses import FileResponse from scripts.export_to_excel import export_bilibili_history from scripts.utils import get_output_path, load_config from typing import Dict, Any import os from datetime import datetime router = APIRouter() config = load_config() @router.post( "/export_history", summary="导出Bilibili历史记录到Excel", response_model=Dict[str, Any], description="将历史记录数据导出为Excel文件,支持按年份、月份或日期范围导出数据" ) def export_history( year: int = Query(None, description="要导出的年份,不指定则使用当前年份"), month: int = Query(None, description="要导出的月份(1-12),如果指定则只导出该月数据", ge=1, le=12), start_date: str = Query(None, description="开始日期,格式为'YYYY-MM-DD',如果指定则从该日期开始导出"), end_date: str = Query(None, description="结束日期,格式为'YYYY-MM-DD',如果指定则导出到该日期为止") ): """ 导出Bilibili历史记录到Excel文件。 Args: year: 要导出的年份,不指定则使用当前年份 month: 要导出的月份(1-12),如果指定则只导出该月数据 start_date: 开始日期,格式为'YYYY-MM-DD',如果指定则从该日期开始导出 end_date: 结束日期,格式为'YYYY-MM-DD',如果指定则导出到该日期为止 Returns: Dict[str, Any]: 包含状态和消息的响应 """ # 验证日期格式 if start_date: try: datetime.strptime(start_date, '%Y-%m-%d') except ValueError: raise HTTPException(status_code=400, detail="开始日期格式错误,应为'YYYY-MM-DD'") if end_date: try: datetime.strptime(end_date, '%Y-%m-%d') except ValueError: raise HTTPException(status_code=400, detail="结束日期格式错误,应为'YYYY-MM-DD'") result = export_bilibili_history(year, month, start_date, end_date) if result["status"] == "success": # 返回文件名信息,便于前端下载 filename = os.path.basename(result["message"].split("数据已成功导出到 ")[-1]) return {"status": "success", "message": result["message"], "filename": filename} else: raise HTTPException(status_code=500, detail=result["message"]) @router.get( "/download_excel/{filename}", summary="下载Excel文件", description="下载指定的Excel文件,支持浏览器直接下载", response_class=FileResponse, responses={ 200: { "description": "Excel文件", "content": { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { "schema": {"type": "string", "format": "binary"} } } }, 404: { "description": "文件不存在", "content": { "application/json": { "example": {"detail": "未找到指定的Excel文件"} } } } } ) def download_excel(filename: str): """ 下载指定的Excel文件。 Args: filename: 要下载的文件名 Returns: FileResponse: Excel文件响应 """ file_path = get_output_path(filename) if not os.path.exists(file_path): raise HTTPException(status_code=404, detail=f"未找到文件 {filename}") return FileResponse( path=file_path, filename=filename, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) @router.get( "/download_db", summary="下载SQLite数据库", description="下载完整的SQLite数据库文件,包含所有年份的历史记录数据", response_class=FileResponse, responses={ 200: { "description": "SQLite数据库文件", "content": { "application/x-sqlite3": { "schema": {"type": "string", "format": "binary"} } } }, 404: { "description": "文件不存在", "content": { "application/json": { "example": {"detail": "数据库文件不存在"} } } } } ) def download_db(): """ 下载完整的SQLite数据库文件。 Returns: FileResponse: 数据库文件响应 """ db_path = get_output_path(config['db_file']) if not os.path.exists(db_path): raise HTTPException(status_code=404, detail="数据库文件不存在") return FileResponse( path=db_path, filename="bilibili_history.db", media_type="application/x-sqlite3" )
2977094657/BilibiliHistoryFetcher
14,426
routers/collection_download.py
import os import re from typing import Optional, List, Dict, Any, Tuple from fastapi import APIRouter, HTTPException from fastapi.responses import StreamingResponse from pydantic import BaseModel, Field import httpx from scripts.utils import load_config from scripts.yutto_runner import run_yutto router = APIRouter() config = load_config() class CollectionInfo(BaseModel): """合集信息""" is_collection: bool = Field(..., description="是否为合集") collection_id: Optional[str] = Field(None, description="合集ID") collection_title: Optional[str] = Field(None, description="合集标题") total_videos: Optional[int] = Field(None, description="合集中视频总数") current_video_index: Optional[int] = Field(None, description="当前视频在合集中的位置") videos: Optional[List[Dict[str, Any]]] = Field(None, description="合集中的视频列表") uploader_mid: Optional[int] = Field(None, description="UP主的UID") class CollectionDownloadRequest(BaseModel): """合集下载请求 - 简化版,只用于整个合集下载""" url: str = Field(..., description="合集URL") cid: int = Field(..., description="视频的 CID,用于分类存储") # 基础下载参数 sessdata: Optional[str] = Field(None, description="用户的 SESSDATA") download_cover: Optional[bool] = Field(True, description="是否下载视频封面") only_audio: Optional[bool] = Field(False, description="是否仅下载音频") video_quality: Optional[int] = Field(None, description="视频清晰度等级") audio_quality: Optional[int] = Field(None, description="音频码率等级") vcodec: Optional[str] = Field(None, description="视频编码") acodec: Optional[str] = Field(None, description="音频编码") download_vcodec_priority: Optional[str] = Field(None, description="视频下载编码优先级") output_format: Optional[str] = Field(None, description="输出格式") output_format_audio_only: Optional[str] = Field(None, description="仅包含音频流时的输出格式") video_only: Optional[bool] = Field(False, description="是否仅下载视频流") danmaku_only: Optional[bool] = Field(False, description="是否仅生成弹幕文件") no_danmaku: Optional[bool] = Field(False, description="是否不生成弹幕文件") subtitle_only: Optional[bool] = Field(False, description="是否仅生成字幕文件") no_subtitle: Optional[bool] = Field(False, description="是否不生成字幕文件") metadata_only: Optional[bool] = Field(False, description="是否仅生成媒体元数据文件") save_cover: Optional[bool] = Field(False, description="生成视频流封面时是否单独保存封面") cover_only: Optional[bool] = Field(False, description="是否仅生成视频封面") no_chapter_info: Optional[bool] = Field(False, description="是否不生成章节信息") def extract_video_info_from_url(url: str) -> Dict[str, Any]: """ 从URL中提取视频信息 Args: url: 视频URL Returns: 包含视频信息的字典 """ # 提取BV号或AV号 bv_match = re.search(r'BV[a-zA-Z0-9]+', url) av_match = re.search(r'av(\d+)', url) video_id = None if bv_match: video_id = bv_match.group() elif av_match: video_id = f"av{av_match.group(1)}" # 提取分P信息 p_match = re.search(r'[?&]p=(\d+)', url) page = int(p_match.group(1)) if p_match else 1 return { "video_id": video_id, "page": page, "original_url": url } async def get_video_collection_info(url: str, sessdata: Optional[str] = None) -> CollectionInfo: """ 获取视频的合集信息 Args: url: 视频URL sessdata: 可选的SESSDATA用于认证 Returns: 合集信息对象 """ try: video_info = extract_video_info_from_url(url) if not video_info["video_id"]: return CollectionInfo(is_collection=False) # 构建API请求 api_url = f"https://api.bilibili.com/x/web-interface/view" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer': 'https://www.bilibili.com/' } if sessdata: headers['Cookie'] = f'SESSDATA={sessdata}' elif config.get('SESSDATA'): headers['Cookie'] = f'SESSDATA={config["SESSDATA"]}' params = {} if video_info["video_id"].startswith('BV'): params['bvid'] = video_info["video_id"] else: params['aid'] = video_info["video_id"][2:] # 去掉'av'前缀 async with httpx.AsyncClient() as client: response = await client.get(api_url, params=params, headers=headers) response.raise_for_status() data = response.json() if data.get('code') != 0: return CollectionInfo(is_collection=False) video_data = data.get('data', {}) # 检查是否有合集信息 ugc_season = video_data.get('ugc_season') if ugc_season: # 这是一个合集 collection_info = CollectionInfo( is_collection=True, collection_id=str(ugc_season.get('id')), collection_title=ugc_season.get('title'), total_videos=len(ugc_season.get('sections', [{}])[0].get('episodes', [])), videos=[], # 添加UP主信息用于构建合集URL uploader_mid=video_data.get('owner', {}).get('mid') ) # 获取合集中的视频列表 episodes = ugc_season.get('sections', [{}])[0].get('episodes', []) for i, episode in enumerate(episodes): video_item = { "index": i + 1, "title": episode.get('title'), "bvid": episode.get('bvid'), "cid": episode.get('cid'), "duration": episode.get('arc', {}).get('duration'), "page": episode.get('page', 1) } collection_info.videos.append(video_item) # 检查当前视频在合集中的位置 if episode.get('bvid') == video_info["video_id"]: collection_info.current_video_index = i + 1 return collection_info # 检查是否有分P视频(多P视频也可以视为一种合集) pages = video_data.get('pages', []) if len(pages) > 1: collection_info = CollectionInfo( is_collection=True, collection_id=video_info["video_id"], collection_title=video_data.get('title'), total_videos=len(pages), current_video_index=video_info["page"], videos=[], uploader_mid=video_data.get('owner', {}).get('mid') ) for page in pages: video_item = { "index": page.get('page'), "title": page.get('part'), "bvid": video_info["video_id"], "cid": page.get('cid'), "duration": page.get('duration'), "page": page.get('page') } collection_info.videos.append(video_item) return collection_info # 不是合集,只是单个视频 return CollectionInfo(is_collection=False) except Exception as e: print(f"获取合集信息时出错:{str(e)}") return CollectionInfo(is_collection=False) def check_download_directories() -> Tuple[str, str]: """ 检查下载目录和临时目录是否存在且有写入权限 Returns: 下载目录和临时目录的路径元组 Raises: HTTPException: 如果目录不存在或没有写入权限 """ download_dir = os.path.normpath(config['yutto']['basic']['dir']) tmp_dir = os.path.normpath(config['yutto']['basic']['tmp_dir']) # 创建目录(如果不存在) os.makedirs(download_dir, exist_ok=True) os.makedirs(tmp_dir, exist_ok=True) # 检查目录权限 if not os.access(download_dir, os.W_OK): raise HTTPException( status_code=500, detail=f"没有下载目录的写入权限:{download_dir}" ) if not os.access(tmp_dir, os.W_OK): raise HTTPException( status_code=500, detail=f"没有临时目录的写入权限:{tmp_dir}" ) return download_dir, tmp_dir def add_download_params_to_command(command: List[str], params: CollectionDownloadRequest) -> List[str]: """ 将下载参数添加到命令中 Args: command: 命令列表 params: 包含下载参数的对象 Returns: 添加了下载参数的命令列表 """ # 基础参数 if params.video_quality is not None: command.extend(['--video-quality', str(params.video_quality)]) if params.audio_quality is not None: command.extend(['--audio-quality', str(params.audio_quality)]) if params.vcodec: command.extend(['--vcodec', params.vcodec]) if params.acodec: command.extend(['--acodec', params.acodec]) if params.download_vcodec_priority: command.extend(['--download-vcodec-priority', params.download_vcodec_priority]) if params.output_format: command.extend(['--output-format', params.output_format]) if params.output_format_audio_only: command.extend(['--output-format-audio-only', params.output_format_audio_only]) # 资源选择参数 if params.video_only: command.append('--video-only') if params.only_audio: command.append('--audio-only') if params.no_danmaku: command.append('--no-danmaku') if params.danmaku_only: command.append('--danmaku-only') if params.no_subtitle or not config['yutto']['resource']['require_subtitle']: command.append('--no-subtitle') if params.subtitle_only: command.append('--subtitle-only') if params.metadata_only: command.append('--metadata-only') if not params.download_cover: command.append('--no-cover') if params.save_cover: command.append('--save-cover') if params.cover_only: command.append('--cover-only') if params.no_chapter_info: command.append('--no-chapter-info') # 添加其他 yutto 配置 if config['yutto']['danmaku']['font_size']: command.extend(['--danmaku-font-size', str(config['yutto']['danmaku']['font_size'])]) if config['yutto']['batch']['with_section']: command.append('--with-section') # 如果提供了 SESSDATA,添加到命令中 if params.sessdata: command.extend(['--sessdata', params.sessdata]) elif config.get('SESSDATA'): command.extend(['--sessdata', config['SESSDATA']]) return command @router.get("/check_collection", summary="检查视频是否为合集") async def check_collection(url: str, sessdata: Optional[str] = None): """ 检查给定的视频URL是否为合集 Args: url: 视频URL sessdata: 可选的SESSDATA用于认证 Returns: 合集信息 """ try: collection_info = await get_video_collection_info(url, sessdata) return { "status": "success", "data": collection_info.model_dump() } except Exception as e: raise HTTPException( status_code=500, detail=f"检查合集信息时出错:{str(e)}" ) @router.post("/download_collection", summary="下载整个合集") async def download_collection(request: CollectionDownloadRequest): """ 下载B站整个合集或多P视频的所有分P Args: request: 包含合集下载参数的请求对象 """ try: # 检查下载目录和临时目录 download_dir, tmp_dir = check_download_directories() # 首先检查是否为合集 collection_info = await get_video_collection_info(request.url, request.sessdata) if not collection_info.is_collection: raise HTTPException( status_code=400, detail="提供的URL不是合集或多P视频" ) # 构建下载整个合集的命令 # 使用安全的文件名(移除特殊字符) safe_collection_title = "".join(c for c in collection_info.collection_title if c.isalnum() or c in (' ', '-', '_')).rstrip() if collection_info.collection_id and collection_info.collection_id != collection_info.videos[0]["bvid"]: # 真正的合集,构建合集的专用URL if collection_info.uploader_mid: # 使用合集的专用URL格式 collection_url = f"https://space.bilibili.com/{collection_info.uploader_mid}/channel/collectiondetail?sid={collection_info.collection_id}" command = [ collection_url, '--batch', # 批量下载模式 '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{safe_collection_title}_collection/{{title}}_{{username}}_{{download_date@%Y%m%d_%H%M%S}}/{{title}}', '--with-metadata' ] else: # 如果没有UP主信息,回退到使用单个视频URL + batch模式 video_info = extract_video_info_from_url(request.url) base_url = f"https://www.bilibili.com/video/{video_info['video_id']}" command = [ base_url, '--batch', # 批量下载模式 '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{safe_collection_title}_collection/{{title}}_{{username}}_{{download_date@%Y%m%d_%H%M%S}}/{{title}}', '--with-metadata' ] else: # 多P视频,下载所有分P video_info = extract_video_info_from_url(request.url) base_url = f"https://www.bilibili.com/video/{video_info['video_id']}" command = [ base_url, '--batch', # 批量下载模式 '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{safe_collection_title}_multipart/{{title}}_{{username}}_{{download_date@%Y%m%d_%H%M%S}}/{{title}}', '--with-metadata' ] # 添加下载参数 command = add_download_params_to_command(command, request) print(f"执行合集下载命令:yutto {' '.join(command)}") print(f"合集信息:{collection_info.collection_title},共 {collection_info.total_videos} 个视频") print("注意:如果合集中包含分P视频,yutto可能会报错,这是yutto限制,和本项目无关") async def event_stream(): # 发送开始信息 yield f"event: info\ndata: 开始下载合集:{collection_info.collection_title}\n\n" yield f"event: info\ndata: 合集共包含 {collection_info.total_videos} 个视频\n\n" yield f"event: info\ndata: 注意:如遇到分P视频,yutto可能会报错停止,这是yutto限制,和本项目无关\n\n" async for chunk in run_yutto(command): yield chunk yield "event: close\ndata: close\n\n" return StreamingResponse(event_stream(), media_type="text/event-stream") except HTTPException: raise except FileNotFoundError: raise HTTPException( status_code=500, detail="找不到 yutto 命令,请确保已正确安装" ) except Exception as e: raise HTTPException( status_code=500, detail=f"下载过程出错:{str(e)}" )
281677160/openwrt-package
29,274
luci-app-homeproxy/root/etc/homeproxy/scripts/generate_client.uc
#!/usr/bin/ucode /* * SPDX-License-Identifier: GPL-2.0-only * * Copyright (C) 2023-2025 ImmortalWrt.org */ 'use strict'; import { readfile, writefile } from 'fs'; import { isnan } from 'math'; import { connect } from 'ubus'; import { cursor } from 'uci'; import { isEmpty, parseURL, strToBool, strToInt, strToTime, removeBlankAttrs, validation, HP_DIR, RUN_DIR } from 'homeproxy'; const ubus = connect(); /* const features = ubus.call('luci.homeproxy', 'singbox_get_features') || {}; */ /* UCI config start */ const uci = cursor(); const uciconfig = 'homeproxy'; uci.load(uciconfig); const uciinfra = 'infra', ucimain = 'config', ucicontrol = 'control'; const ucidnssetting = 'dns', ucidnsserver = 'dns_server', ucidnsrule = 'dns_rule'; const uciroutingsetting = 'routing', uciroutingnode = 'routing_node', uciroutingrule = 'routing_rule'; const ucinode = 'node'; const uciruleset = 'ruleset'; const routing_mode = uci.get(uciconfig, ucimain, 'routing_mode') || 'bypass_mainland_china'; let wan_dns = ubus.call('network.interface', 'status', {'interface': 'wan'})?.['dns-server']?.[0]; if (!wan_dns) wan_dns = (routing_mode in ['proxy_mainland_china', 'global']) ? '8.8.8.8' : '223.5.5.5'; const dns_port = uci.get(uciconfig, uciinfra, 'dns_port') || '5333'; const ntp_server = uci.get(uciconfig, uciinfra, 'ntp_server') || 'time.apple.com'; const ipv6_support = uci.get(uciconfig, ucimain, 'ipv6_support') || '0'; let main_node, main_udp_node, dedicated_udp_node, default_outbound, default_outbound_dns, domain_strategy, sniff_override, dns_server, china_dns_server, dns_default_strategy, dns_default_server, dns_disable_cache, dns_disable_cache_expire, dns_independent_cache, dns_client_subnet, cache_file_store_rdrc, cache_file_rdrc_timeout, direct_domain_list, proxy_domain_list; if (routing_mode !== 'custom') { main_node = uci.get(uciconfig, ucimain, 'main_node') || 'nil'; main_udp_node = uci.get(uciconfig, ucimain, 'main_udp_node') || 'nil'; dedicated_udp_node = !isEmpty(main_udp_node) && !(main_udp_node in ['same', main_node]); dns_server = uci.get(uciconfig, ucimain, 'dns_server'); if (isEmpty(dns_server) || dns_server === 'wan') dns_server = wan_dns; if (routing_mode === 'bypass_mainland_china') { china_dns_server = uci.get(uciconfig, ucimain, 'china_dns_server'); if (isEmpty(china_dns_server) || type(china_dns_server) !== 'string' || china_dns_server === 'wan') china_dns_server = wan_dns; } dns_default_strategy = (ipv6_support !== '1') ? 'ipv4_only' : null; direct_domain_list = trim(readfile(HP_DIR + '/resources/direct_list.txt')); if (direct_domain_list) direct_domain_list = split(direct_domain_list, /[\r\n]/); proxy_domain_list = trim(readfile(HP_DIR + '/resources/proxy_list.txt')); if (proxy_domain_list) proxy_domain_list = split(proxy_domain_list, /[\r\n]/); sniff_override = uci.get(uciconfig, uciinfra, 'sniff_override') || '1'; } else { /* DNS settings */ dns_default_strategy = uci.get(uciconfig, ucidnssetting, 'default_strategy'); dns_default_server = uci.get(uciconfig, ucidnssetting, 'default_server'); dns_disable_cache = uci.get(uciconfig, ucidnssetting, 'disable_cache'); dns_disable_cache_expire = uci.get(uciconfig, ucidnssetting, 'disable_cache_expire'); dns_independent_cache = uci.get(uciconfig, ucidnssetting, 'independent_cache'); dns_client_subnet = uci.get(uciconfig, ucidnssetting, 'client_subnet'); cache_file_store_rdrc = uci.get(uciconfig, ucidnssetting, 'cache_file_store_rdrc'), cache_file_rdrc_timeout = uci.get(uciconfig, ucidnssetting, 'cache_file_rdrc_timeout'); /* Routing settings */ default_outbound = uci.get(uciconfig, uciroutingsetting, 'default_outbound') || 'nil'; default_outbound_dns = uci.get(uciconfig, uciroutingsetting, 'default_outbound_dns') || 'default-dns'; domain_strategy = uci.get(uciconfig, uciroutingsetting, 'domain_strategy'); sniff_override = uci.get(uciconfig, uciroutingsetting, 'sniff_override'); } const proxy_mode = uci.get(uciconfig, ucimain, 'proxy_mode') || 'redirect_tproxy', default_interface = uci.get(uciconfig, ucicontrol, 'bind_interface'); const mixed_port = uci.get(uciconfig, uciinfra, 'mixed_port') || '5330'; let self_mark, redirect_port, tproxy_port, tun_name, tun_addr4, tun_addr6, tun_mtu, tcpip_stack, endpoint_independent_nat, udp_timeout; if (routing_mode === 'custom') udp_timeout = uci.get(uciconfig, uciroutingsetting, 'udp_timeout'); else udp_timeout = uci.get(uciconfig, 'infra', 'udp_timeout'); if (match(proxy_mode, /redirect/)) { self_mark = uci.get(uciconfig, 'infra', 'self_mark') || '100'; redirect_port = uci.get(uciconfig, 'infra', 'redirect_port') || '5331'; } if (match(proxy_mode), /tproxy/) if (main_udp_node !== 'nil' || routing_mode === 'custom') tproxy_port = uci.get(uciconfig, 'infra', 'tproxy_port') || '5332'; if (match(proxy_mode), /tun/) { tun_name = uci.get(uciconfig, uciinfra, 'tun_name') || 'singtun0'; tun_addr4 = uci.get(uciconfig, uciinfra, 'tun_addr4') || '172.19.0.1/30'; tun_addr6 = uci.get(uciconfig, uciinfra, 'tun_addr6') || 'fdfe:dcba:9876::1/126'; tun_mtu = uci.get(uciconfig, uciinfra, 'tun_mtu') || '9000'; tcpip_stack = 'system'; if (routing_mode === 'custom') { tcpip_stack = uci.get(uciconfig, uciroutingsetting, 'tcpip_stack') || 'system'; endpoint_independent_nat = uci.get(uciconfig, uciroutingsetting, 'endpoint_independent_nat'); } } const log_level = uci.get(uciconfig, ucimain, 'log_level') || 'warn'; /* UCI config end */ /* Config helper start */ function parse_port(strport) { if (type(strport) !== 'array' || isEmpty(strport)) return null; let ports = []; for (let i in strport) push(ports, int(i)); return ports; } function parse_dnserver(server_addr, default_protocol) { if (isEmpty(server_addr)) return null; if (!match(server_addr, /:\/\//)) server_addr = (default_protocol || 'udp') + '://' + (validation('ip6addr', dns_server) ? `[${dns_server}]` : dns_server); server_addr = parseURL(server_addr); return { type: server_addr.protocol, server: server_addr.hostname, server_port: strToInt(server_addr.port), path: (server_addr.pathname !== '/') ? server_addr.pathname : null, } } function parse_dnsquery(strquery) { if (type(strquery) !== 'array' || isEmpty(strquery)) return null; let querys = []; for (let i in strquery) isnan(int(i)) ? push(querys, i) : push(querys, int(i)); return querys; } function generate_endpoint(node) { if (type(node) !== 'object' || isEmpty(node)) return null; const endpoint = { type: node.type, tag: 'cfg-' + node['.name'] + '-out', address: node.wireguard_local_address, mtu: strToInt(node.wireguard_mtu), private_key: node.wireguard_private_key, peers: (node.type === 'wireguard') ? [ { address: node.address, port: strToInt(node.port), allowed_ips: [ '0.0.0.0/0', '::/0' ], persistent_keepalive_interval: strToInt(node.wireguard_persistent_keepalive_interval), public_key: node.wireguard_peer_public_key, pre_shared_key: node.wireguard_pre_shared_key, reserved: parse_port(node.wireguard_reserved), } ] : null, system: (node.type === 'wireguard') ? false : null, tcp_fast_open: strToBool(node.tcp_fast_open), tcp_multi_path: strToBool(node.tcp_multi_path), udp_fragment: strToBool(node.udp_fragment) }; return endpoint; } function generate_outbound(node) { if (type(node) !== 'object' || isEmpty(node)) return null; const outbound = { type: node.type, tag: 'cfg-' + node['.name'] + '-out', routing_mark: strToInt(self_mark), server: node.address, server_port: strToInt(node.port), /* Hysteria(2) */ server_ports: node.hysteria_hopping_port, username: (node.type !== 'ssh') ? node.username : null, user: (node.type === 'ssh') ? node.username : null, password: node.password, /* Direct */ override_address: node.override_address, override_port: strToInt(node.override_port), proxy_protocol: strToInt(node.proxy_protocol), /* AnyTLS */ idle_session_check_interval: strToTime(node.anytls_idle_session_check_interval), idle_session_timeout: strToTime(node.anytls_idle_session_timeout), min_idle_session: strToInt(node.anytls_min_idle_session), /* Hysteria (2) */ hop_interval: strToTime(node.hysteria_hop_interval), up_mbps: strToInt(node.hysteria_up_mbps), down_mbps: strToInt(node.hysteria_down_mbps), obfs: node.hysteria_obfs_type ? { type: node.hysteria_obfs_type, password: node.hysteria_obfs_password } : node.hysteria_obfs_password, auth: (node.hysteria_auth_type === 'base64') ? node.hysteria_auth_payload : null, auth_str: (node.hysteria_auth_type === 'string') ? node.hysteria_auth_payload : null, recv_window_conn: strToInt(node.hysteria_recv_window_conn), recv_window: strToInt(node.hysteria_revc_window), disable_mtu_discovery: strToBool(node.hysteria_disable_mtu_discovery), /* Shadowsocks */ method: node.shadowsocks_encrypt_method, plugin: node.shadowsocks_plugin, plugin_opts: node.shadowsocks_plugin_opts, /* ShadowTLS / Socks */ version: (node.type === 'shadowtls') ? strToInt(node.shadowtls_version) : ((node.type === 'socks') ? node.socks_version : null), /* SSH */ client_version: node.ssh_client_version, host_key: node.ssh_host_key, host_key_algorithms: node.ssh_host_key_algo, private_key: node.ssh_priv_key, private_key_passphrase: node.ssh_priv_key_pp, /* Tuic */ uuid: node.uuid, congestion_control: node.tuic_congestion_control, udp_relay_mode: node.tuic_udp_relay_mode, udp_over_stream: strToBool(node.tuic_udp_over_stream), zero_rtt_handshake: strToBool(node.tuic_enable_zero_rtt), heartbeat: strToTime(node.tuic_heartbeat), /* VLESS / VMess */ flow: node.vless_flow, alter_id: strToInt(node.vmess_alterid), security: node.vmess_encrypt, global_padding: strToBool(node.vmess_global_padding), authenticated_length: strToBool(node.vmess_authenticated_length), packet_encoding: node.packet_encoding, multiplex: (node.multiplex === '1') ? { enabled: true, protocol: node.multiplex_protocol, max_connections: strToInt(node.multiplex_max_connections), min_streams: strToInt(node.multiplex_min_streams), max_streams: strToInt(node.multiplex_max_streams), padding: strToBool(node.multiplex_padding), brutal: (node.multiplex_brutal === '1') ? { enabled: true, up_mbps: strToInt(node.multiplex_brutal_up), down_mbps: strToInt(node.multiplex_brutal_down) } : null } : null, tls: (node.tls === '1') ? { enabled: true, server_name: node.tls_sni, insecure: strToBool(node.tls_insecure), alpn: node.tls_alpn, min_version: node.tls_min_version, max_version: node.tls_max_version, cipher_suites: node.tls_cipher_suites, certificate_path: node.tls_cert_path, ech: (node.tls_ech === '1') ? { enabled: true, config: node.tls_ech_config, config_path: node.tls_ech_config_path } : null, utls: !isEmpty(node.tls_utls) ? { enabled: true, fingerprint: node.tls_utls } : null, reality: (node.tls_reality === '1') ? { enabled: true, public_key: node.tls_reality_public_key, short_id: node.tls_reality_short_id } : null } : null, transport: !isEmpty(node.transport) ? { type: node.transport, host: node.http_host || node.httpupgrade_host, path: node.http_path || node.ws_path, headers: node.ws_host ? { Host: node.ws_host } : null, method: node.http_method, max_early_data: strToInt(node.websocket_early_data), early_data_header_name: node.websocket_early_data_header, service_name: node.grpc_servicename, idle_timeout: (node.http_idle_timeout), ping_timeout: (node.http_ping_timeout), permit_without_stream: strToBool(node.grpc_permit_without_stream) } : null, udp_over_tcp: (node.udp_over_tcp === '1') ? { enabled: true, version: strToInt(node.udp_over_tcp_version) } : null, tcp_fast_open: strToBool(node.tcp_fast_open), tcp_multi_path: strToBool(node.tcp_multi_path), udp_fragment: strToBool(node.udp_fragment) }; return outbound; } function get_outbound(cfg) { if (isEmpty(cfg)) return null; if (type(cfg) === 'array') { if ('any-out' in cfg) return 'any'; let outbounds = []; for (let i in cfg) push(outbounds, get_outbound(i)); return outbounds; } else { switch (cfg) { case 'block-out': case 'direct-out': return cfg; default: const node = uci.get(uciconfig, cfg, 'node'); if (isEmpty(node)) die(sprintf("%s's node is missing, please check your configuration.", cfg)); else if (node === 'urltest') return 'cfg-' + cfg + '-out'; else return 'cfg-' + node + '-out'; } } } function get_resolver(cfg) { if (isEmpty(cfg)) return null; switch (cfg) { case 'default-dns': case 'system-dns': return cfg; default: return 'cfg-' + cfg + '-dns'; } } function get_ruleset(cfg) { if (isEmpty(cfg)) return null; let rules = []; for (let i in cfg) push(rules, isEmpty(i) ? null : 'cfg-' + i + '-rule'); return rules; } /* Config helper end */ const config = {}; /* Log */ config.log = { disabled: false, level: log_level, output: RUN_DIR + '/sing-box-c.log', timestamp: true }; /* NTP */ if (!isEmpty(ntp_server)) config.ntp = { enabled: true, server: ntp_server, detour: 'direct-out', domain_resolver: 'default-dns', }; /* DNS start */ /* Default settings */ config.dns = { servers: [ { tag: 'default-dns', type: 'udp', server: wan_dns, detour: self_mark ? 'direct-out' : null }, { tag: 'system-dns', type: 'local', detour: self_mark ? 'direct-out' : null } ], rules: [], strategy: dns_default_strategy, disable_cache: strToBool(dns_disable_cache), disable_expire: strToBool(dns_disable_cache_expire), independent_cache: strToBool(dns_independent_cache), client_subnet: dns_client_subnet }; if (!isEmpty(main_node)) { /* Main DNS */ push(config.dns.servers, { tag: 'main-dns', domain_resolver: { server: 'default-dns', strategy: (ipv6_support !== '1') ? 'ipv4_only' : null }, detour: 'main-out', ...parse_dnserver(dns_server, 'tcp') }); config.dns.final = 'main-dns'; if (length(direct_domain_list)) push(config.dns.rules, { rule_set: 'direct-domain', action: 'route', server: (routing_mode === 'bypass_mainland_china') ? 'china-dns' : 'default-dns' }); /* Filter out SVCB/HTTPS queries for "exquisite" Apple devices */ if (routing_mode === 'gfwlist' || length(proxy_domain_list)) push(config.dns.rules, { rule_set: (routing_mode !== 'gfwlist') ? 'proxy-domain' : null, query_type: [64, 65], action: 'reject' }); if (routing_mode === 'bypass_mainland_china') { push(config.dns.servers, { tag: 'china-dns', domain_resolver: { server: 'default-dns', strategy: 'prefer_ipv6' }, detour: self_mark ? 'direct-out' : null, ...parse_dnserver(china_dns_server) }); if (length(proxy_domain_list)) push(config.dns.rules, { rule_set: 'proxy-domain', action: 'route', server: 'main-dns' }); push(config.dns.rules, { rule_set: 'geosite-cn', action: 'route', server: 'china-dns', strategy: 'prefer_ipv6' }); push(config.dns.rules, { type: 'logical', mode: 'and', rules: [ { rule_set: 'geosite-noncn', invert: true }, { rule_set: 'geoip-cn' } ], action: 'route', server: 'china-dns', strategy: 'prefer_ipv6' }); } } else if (!isEmpty(default_outbound)) { /* DNS servers */ uci.foreach(uciconfig, ucidnsserver, (cfg) => { if (cfg.enabled !== '1') return; let outbound = get_outbound(cfg.outbound); if (outbound === 'direct-out' && isEmpty(self_mark)) outbound = null; push(config.dns.servers, { tag: 'cfg-' + cfg['.name'] + '-dns', type: cfg.type, server: cfg.server, server_port: strToInt(cfg.server_port), path: cfg.path, headers: cfg.headers, tls: cfg.tls_sni ? { enabled: true, server_name: cfg.tls_sni } : null, domain_resolver: (cfg.address_resolver || cfg.address_strategy) ? { server: get_resolver(cfg.address_resolver || dns_default_server), strategy: cfg.address_strategy } : null, detour: outbound }); }); /* DNS rules */ uci.foreach(uciconfig, ucidnsrule, (cfg) => { if (cfg.enabled !== '1') return; push(config.dns.rules, { ip_version: strToInt(cfg.ip_version), query_type: parse_dnsquery(cfg.query_type), network: cfg.network, protocol: cfg.protocol, domain: cfg.domain, domain_suffix: cfg.domain_suffix, domain_keyword: cfg.domain_keyword, domain_regex: cfg.domain_regex, port: parse_port(cfg.port), port_range: cfg.port_range, source_ip_cidr: cfg.source_ip_cidr, source_ip_is_private: strToBool(cfg.source_ip_is_private), ip_cidr: cfg.ip_cidr, ip_is_private: strToBool(cfg.ip_is_private), source_port: parse_port(cfg.source_port), source_port_range: cfg.source_port_range, process_name: cfg.process_name, process_path: cfg.process_path, process_path_regex: cfg.process_path_regex, user: cfg.user, rule_set: get_ruleset(cfg.rule_set), rule_set_ip_cidr_match_source: strToBool(cfg.rule_set_ip_cidr_match_source), invert: strToBool(cfg.invert), outbound: get_outbound(cfg.outbound), action: cfg.action, server: get_resolver(cfg.server), strategy: cfg.domain_strategy, disable_cache: strToBool(cfg.dns_disable_cache), rewrite_ttl: strToInt(cfg.rewrite_ttl), client_subnet: cfg.client_subnet, method: cfg.reject_method, no_drop: strToBool(cfg.reject_no_drop), rcode: cfg.predefined_rcode, answer: cfg.predefined_answer, ns: cfg.predefined_ns, extra: cfg.predefined_extra }); }); if (isEmpty(config.dns.rules)) config.dns.rules = null; config.dns.final = get_resolver(dns_default_server); } /* DNS end */ /* Inbound start */ config.inbounds = []; push(config.inbounds, { type: 'direct', tag: 'dns-in', listen: '::', listen_port: int(dns_port) }); push(config.inbounds, { type: 'mixed', tag: 'mixed-in', listen: '::', listen_port: int(mixed_port), udp_timeout: strToTime(udp_timeout), sniff: true, sniff_override_destination: strToBool(sniff_override), set_system_proxy: false }); if (match(proxy_mode, /redirect/)) push(config.inbounds, { type: 'redirect', tag: 'redirect-in', listen: '::', listen_port: int(redirect_port), sniff: true, sniff_override_destination: strToBool(sniff_override) }); if (match(proxy_mode, /tproxy/)) push(config.inbounds, { type: 'tproxy', tag: 'tproxy-in', listen: '::', listen_port: int(tproxy_port), network: 'udp', udp_timeout: strToTime(udp_timeout), sniff: true, sniff_override_destination: strToBool(sniff_override) }); if (match(proxy_mode, /tun/)) push(config.inbounds, { type: 'tun', tag: 'tun-in', interface_name: tun_name, address: (ipv6_support === '1') ? [tun_addr4, tun_addr6] : [tun_addr4], mtu: strToInt(tun_mtu), auto_route: false, endpoint_independent_nat: strToBool(endpoint_independent_nat), udp_timeout: strToTime(udp_timeout), stack: tcpip_stack, sniff: true, sniff_override_destination: strToBool(sniff_override) }); /* Inbound end */ /* Outbound start */ config.endpoints = []; /* Default outbounds */ config.outbounds = [ { type: 'direct', tag: 'direct-out', routing_mark: strToInt(self_mark) }, { type: 'block', tag: 'block-out' } ]; /* Main outbounds */ if (!isEmpty(main_node)) { let urltest_nodes = []; if (main_node === 'urltest') { const main_urltest_nodes = uci.get(uciconfig, ucimain, 'main_urltest_nodes') || []; const main_urltest_interval = uci.get(uciconfig, ucimain, 'main_urltest_interval'); const main_urltest_tolerance = uci.get(uciconfig, ucimain, 'main_urltest_tolerance'); push(config.outbounds, { type: 'urltest', tag: 'main-out', outbounds: map(main_urltest_nodes, (k) => `cfg-${k}-out`), interval: strToTime(main_urltest_interval), tolerance: strToInt(main_urltest_tolerance), idle_timeout: (strToInt(main_urltest_interval) > 1800) ? `${main_urltest_interval * 2}s` : null, }); urltest_nodes = main_urltest_nodes; } else { const main_node_cfg = uci.get_all(uciconfig, main_node) || {}; if (main_node_cfg.type === 'wireguard') { push(config.endpoints, generate_endpoint(main_node_cfg)); config.endpoints[length(config.endpoints)-1].tag = 'main-out'; } else { push(config.outbounds, generate_outbound(main_node_cfg)); config.outbounds[length(config.outbounds)-1].tag = 'main-out'; } } if (main_udp_node === 'urltest') { const main_udp_urltest_nodes = uci.get(uciconfig, ucimain, 'main_udp_urltest_nodes') || []; const main_udp_urltest_interval = uci.get(uciconfig, ucimain, 'main_udp_urltest_interval'); const main_udp_urltest_tolerance = uci.get(uciconfig, ucimain, 'main_udp_urltest_tolerance'); push(config.outbounds, { type: 'urltest', tag: 'main-udp-out', outbounds: map(main_udp_urltest_nodes, (k) => `cfg-${k}-out`), interval: strToTime(main_udp_urltest_interval), tolerance: strToInt(main_udp_urltest_tolerance), idle_timeout: (strToInt(main_udp_urltest_interval) > 1800) ? `${main_udp_urltest_interval * 2}s` : null, }); urltest_nodes = [...urltest_nodes, ...filter(main_udp_urltest_nodes, (l) => !~index(urltest_nodes, l))]; } else if (dedicated_udp_node) { const main_udp_node_cfg = uci.get_all(uciconfig, main_udp_node) || {}; if (main_udp_node_cfg.type === 'wireguard') { push(config.endpoints, generate_endpoint(main_udp_node_cfg)); config.endpoints[length(config.endpoints)-1].tag = 'main-udp-out'; } else { push(config.outbounds, generate_outbound(main_udp_node_cfg)); config.outbounds[length(config.outbounds)-1].tag = 'main-udp-out'; } } for (let i in urltest_nodes) { const urltest_node = uci.get_all(uciconfig, i) || {}; if (urltest_node.type === 'wireguard') { push(config.endpoints, generate_endpoint(urltest_node)); config.endpoints[length(config.endpoints)-1].tag = 'cfg-' + i + '-out'; } else { push(config.outbounds, generate_outbound(urltest_node)); config.outbounds[length(config.outbounds)-1].tag = 'cfg-' + i + '-out'; } } } else if (!isEmpty(default_outbound)) { let urltest_nodes = [], routing_nodes = []; uci.foreach(uciconfig, uciroutingnode, (cfg) => { if (cfg.enabled !== '1') return; if (cfg.node === 'urltest') { push(config.outbounds, { type: 'urltest', tag: 'cfg-' + cfg['.name'] + '-out', outbounds: map(cfg.urltest_nodes, (k) => `cfg-${k}-out`), url: cfg.urltest_url, interval: strToTime(cfg.urltest_interval), tolerance: strToInt(cfg.urltest_tolerance), idle_timeout: strToTime(cfg.urltest_idle_timeout), interrupt_exist_connections: strToBool(cfg.urltest_interrupt_exist_connections) }); urltest_nodes = [...urltest_nodes, ...filter(cfg.urltest_nodes, (l) => !~index(urltest_nodes, l))]; } else { const outbound = uci.get_all(uciconfig, cfg.node) || {}; if (outbound.type === 'wireguard') { push(config.endpoints, generate_endpoint(outbound)); config.endpoints[length(config.endpoints)-1].bind_interface = cfg.bind_interface; config.endpoints[length(config.endpoints)-1].detour = get_outbound(cfg.outbound); if (cfg.domain_resolver) config.endpoints[length(config.endpoints)-1].domain_resolver = { server: get_resolver(cfg.domain_resolver), strategy: cfg.domain_strategy }; } else { push(config.outbounds, generate_outbound(outbound)); config.outbounds[length(config.outbounds)-1].bind_interface = cfg.bind_interface; config.outbounds[length(config.outbounds)-1].detour = get_outbound(cfg.outbound); if (cfg.domain_resolver) config.outbounds[length(config.outbounds)-1].domain_resolver = { server: get_resolver(cfg.domain_resolver), strategy: cfg.domain_strategy }; } push(routing_nodes, cfg.node); } }); for (let i in filter(urltest_nodes, (l) => !~index(routing_nodes, l))) { const urltest_node = uci.get_all(uciconfig, i) || {}; if (urltest_node.type === 'wireguard') push(config.endpoints, generate_endpoint(urltest_node)); else push(config.outbounds, generate_outbound(urltest_node)); } } if (isEmpty(config.endpoints)) config.endpoints = null; /* Outbound end */ /* Routing rules start */ /* Default settings */ config.route = { rules: [ { inbound: 'dns-in', action: 'hijack-dns' } /* * leave for sing-box 1.13.0 * { * action: 'sniff' * } */ ], rule_set: [], auto_detect_interface: isEmpty(default_interface) ? true : null, default_interface: default_interface }; /* Routing rules */ if (!isEmpty(main_node)) { /* Avoid DNS loop */ config.route.default_domain_resolver = { action: 'route', server: (routing_mode === 'bypass_mainland_china') ? 'china-dns' : 'default-dns', strategy: (ipv6_support !== '1') ? 'prefer_ipv4' : null }; /* Direct list */ if (length(direct_domain_list)) push(config.route.rules, { rule_set: 'direct-domain', action: 'route', outbound: 'direct-out' }); /* Main UDP out */ if (dedicated_udp_node) push(config.route.rules, { network: 'udp', action: 'route', outbound: 'main-udp-out' }); config.route.final = 'main-out'; /* Rule set */ /* Direct list */ if (length(direct_domain_list)) push(config.route.rule_set, { type: 'inline', tag: 'direct-domain', rules: [ { domain_keyword: direct_domain_list, } ] }); /* Proxy list */ if (length(proxy_domain_list)) push(config.route.rule_set, { type: 'inline', tag: 'proxy-domain', rules: [ { domain_keyword: proxy_domain_list, } ] }); if (routing_mode === 'bypass_mainland_china') { push(config.route.rule_set, { type: 'remote', tag: 'geoip-cn', format: 'binary', url: 'https://fastly.jsdelivr.net/gh/1715173329/IPCIDR-CHINA@rule-set/cn.srs', download_detour: 'main-out' }); push(config.route.rule_set, { type: 'remote', tag: 'geosite-cn', format: 'binary', url: 'https://fastly.jsdelivr.net/gh/1715173329/sing-geosite@rule-set-unstable/geosite-geolocation-cn.srs', download_detour: 'main-out' }); push(config.route.rule_set, { type: 'remote', tag: 'geosite-noncn', format: 'binary', url: 'https://fastly.jsdelivr.net/gh/1715173329/sing-geosite@rule-set-unstable/geosite-geolocation-!cn.srs', download_detour: 'main-out' }); } if (isEmpty(config.route.rule_set)) config.route.rule_set = null; } else if (!isEmpty(default_outbound)) { config.route.default_domain_resolver = { action: 'resolve', server: get_resolver(default_outbound_dns) }; if (domain_strategy) push(config.route.rules, { action: 'resolve', strategy: domain_strategy }); uci.foreach(uciconfig, uciroutingrule, (cfg) => { if (cfg.enabled !== '1') return null; push(config.route.rules, { ip_version: strToInt(cfg.ip_version), protocol: cfg.protocol, network: cfg.network, domain: cfg.domain, domain_suffix: cfg.domain_suffix, domain_keyword: cfg.domain_keyword, domain_regex: cfg.domain_regex, source_ip_cidr: cfg.source_ip_cidr, source_ip_is_private: strToBool(cfg.source_ip_is_private), ip_cidr: cfg.ip_cidr, ip_is_private: strToBool(cfg.ip_is_private), source_port: parse_port(cfg.source_port), source_port_range: cfg.source_port_range, port: parse_port(cfg.port), port_range: cfg.port_range, process_name: cfg.process_name, process_path: cfg.process_path, process_path_regex: cfg.process_path_regex, user: cfg.user, rule_set: get_ruleset(cfg.rule_set), rule_set_ip_cidr_match_source: strToBool(cfg.rule_set_ip_cidr_match_source), rule_set_ip_cidr_accept_empty: strToBool(cfg.rule_set_ip_cidr_accept_empty), invert: strToBool(cfg.invert), action: cfg.action, outbound: get_outbound(cfg.outbound), override_address: cfg.override_address, override_port: strToInt(cfg.override_port), udp_disable_domain_unmapping: strToBool(cfg.udp_disable_domain_unmapping), udp_connect: strToBool(cfg.udp_connect), udp_timeout: strToTime(cfg.udp_timeout), tls_fragment: strToBool(cfg.tls_fragment), tls_fragment_fallback_delay: strToTime(cfg.tls_fragment_fallback_delay), tls_record_fragment: strToBool(cfg.tls_record_fragment) }); }); config.route.final = get_outbound(default_outbound); /* Rule set */ uci.foreach(uciconfig, uciruleset, (cfg) => { if (cfg.enabled !== '1') return null; push(config.route.rule_set, { type: cfg.type, tag: 'cfg-' + cfg['.name'] + '-rule', format: cfg.format, path: cfg.path, url: cfg.url, download_detour: get_outbound(cfg.outbound), update_interval: cfg.update_interval }); }); } /* Routing rules end */ /* Experimental start */ if (routing_mode in ['bypass_mainland_china', 'custom']) { config.experimental = { cache_file: { enabled: true, path: RUN_DIR + '/cache.db', store_rdrc: strToBool(cache_file_store_rdrc), rdrc_timeout: strToTime(cache_file_rdrc_timeout), } }; } /* Experimental end */ system('mkdir -p ' + RUN_DIR); writefile(RUN_DIR + '/sing-box-c.json', sprintf('%.J\n', removeBlankAttrs(config)));
2929004360/ruoyi-sign
1,734
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfBusinessProcessMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 业务流程Mapper接口 * * @author fengcheng * @date 2024-07-15 */ public interface WfBusinessProcessMapper { /** * 查询业务流程 * * @param businessId 业务流程主键 * @return 业务流程 */ public WfBusinessProcess selectWfBusinessProcessByBusinessId(String businessId); /** * 查询业务流程列表 * * @param wfBusinessProcess 业务流程 * @return 业务流程集合 */ public List<WfBusinessProcess> selectWfBusinessProcessList(WfBusinessProcess wfBusinessProcess); /** * 新增业务流程 * * @param wfBusinessProcess 业务流程 * @return 结果 */ public int insertWfBusinessProcess(WfBusinessProcess wfBusinessProcess); /** * 修改业务流程 * * @param wfBusinessProcess 业务流程 * @return 结果 */ public int updateWfBusinessProcess(WfBusinessProcess wfBusinessProcess); /** * 删除业务流程 * * @param businessId 业务流程主键 * @param type 业务类型 * @return 结果 */ public int deleteWfBusinessProcessByBusinessId(@Param("businessId") String businessId,@Param("type") String type); /** * 批量删除业务流程 * * @param businessIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfBusinessProcessByBusinessIds(String[] businessIds); /** * 根据流程ID查询业务流程 * * @param processId * @return */ WfBusinessProcess selectWfBusinessProcessByProcessId(String processId); /** * 根据流程ID查询业务流程列表 * * @param ids * @return */ List<WfBusinessProcess> selectWfBusinessProcessListByProcessId(@Param("ids") List<String> ids); }
2929004360/ruoyi-sign
1,691
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfModelTemplateMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfModelTemplate; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 模型模板Mapper接口 * * @author fengcheng * @date 2024-07-17 */ public interface WfModelTemplateMapper { /** * 查询模型模板 * * @param modelTemplateId 模型模板主键 * @return 模型模板 */ public WfModelTemplate selectWfModelTemplateByModelTemplateId(String modelTemplateId); /** * 查询模型模板列表 * * @param wfModelTemplate 模型模板 * @return 模型模板集合 */ public List<WfModelTemplate> selectWfModelTemplateList(WfModelTemplate wfModelTemplate); /** * 新增模型模板 * * @param wfModelTemplate 模型模板 * @return 结果 */ public int insertWfModelTemplate(WfModelTemplate wfModelTemplate); /** * 修改模型模板 * * @param wfModelTemplate 模型模板 * @return 结果 */ public int updateWfModelTemplate(WfModelTemplate wfModelTemplate); /** * 删除模型模板 * * @param modelTemplateId 模型模板主键 * @return 结果 */ public int deleteWfModelTemplateByModelTemplateId(String modelTemplateId); /** * 批量删除模型模板 * * @param modelTemplateIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfModelTemplateByModelTemplateIds(String[] modelTemplateIds); /** * 查询模型模板列表 * * @param wfModelTemplate 模型模板 * @param deptIdList 子部门id数据 * @param ancestorsList 祖父部门id数据 * @return */ List<WfModelTemplate> selectWfModelTemplateListVo(@Param("wfModelTemplate") WfModelTemplate wfModelTemplate,@Param("deptIdList") List<Long> deptIdList,@Param("ancestorsList") List<Long> ancestorsList); }
2929004360/ruoyi-sign
1,258
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfFlowMenuMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfFlowMenu; import java.util.List; /** * 流程菜单Mapper接口 * * @author fengcheng * @date 2024-07-12 */ public interface WfFlowMenuMapper { /** * 查询流程菜单 * * @param flowMenuId 流程菜单主键 * @return 流程菜单 */ public WfFlowMenu selectWfFlowMenuByFlowMenuId(String flowMenuId); /** * 查询流程菜单列表 * * @param wfFlowMenu 流程菜单 * @return 流程菜单集合 */ public List<WfFlowMenu> selectWfFlowMenuList(WfFlowMenu wfFlowMenu); /** * 新增流程菜单 * * @param wfFlowMenu 流程菜单 * @return 结果 */ public int insertWfFlowMenu(WfFlowMenu wfFlowMenu); /** * 修改流程菜单 * * @param wfFlowMenu 流程菜单 * @return 结果 */ public int updateWfFlowMenu(WfFlowMenu wfFlowMenu); /** * 删除流程菜单 * * @param flowMenuId 流程菜单主键 * @return 结果 */ public int deleteWfFlowMenuByFlowMenuId(Long flowMenuId); /** * 批量删除流程菜单 * * @param flowMenuIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfFlowMenuByFlowMenuIds(Long[] flowMenuIds); /** * 获取流程菜单信息 * * @param menuId * @return */ WfFlowMenu getWfFlowMenuInfo(String menuId); }
281677160/openwrt-package
8,879
luci-app-homeproxy/root/etc/homeproxy/scripts/migrate_config.uc
#!/usr/bin/ucode /* * SPDX-License-Identifier: GPL-2.0-only * * Copyright (C) 2025 ImmortalWrt.org */ 'use strict'; import { cursor } from 'uci'; import { isEmpty, parseURL } from 'homeproxy'; const uci = cursor(); const uciconfig = 'homeproxy'; uci.load(uciconfig); const uciinfra = 'infra', ucimigration = 'migration', ucimain = 'config', ucinode = 'node', ucidns = 'dns', ucidnsserver = 'dns_server', ucidnsrule = 'dns_rule', ucirouting = 'routing', uciroutingnode = 'routing_node', uciroutingrule = 'routing_rule', uciserver = 'server'; /* chinadns-ng has been removed */ if (uci.get(uciconfig, uciinfra, 'china_dns_port')) uci.delete(uciconfig, uciinfra, 'china_dns_port'); /* chinadns server now only accepts single server */ const china_dns_server = uci.get(uciconfig, ucimain, 'china_dns_server'); if (type(china_dns_server) === 'array') { uci.set(uciconfig, ucimain, 'china_dns_server', china_dns_server[0]); } else { if (china_dns_server === 'wan_114') uci.set(uciconfig, ucimain, 'china_dns_server', '114.114.114.114'); else if (match(china_dns_server, /,/)) uci.set(uciconfig, ucimain, 'china_dns_server', split(china_dns_server, ',')[0]); } /* github_token option has been moved to config section */ const github_token = uci.get(uciconfig, uciinfra, 'github_token'); if (github_token) { uci.set(uciconfig, ucimain, 'github_token', github_token); uci.delete(uciconfig, uciinfra, 'github_token') } /* tun_gso was deprecated in sb 1.11 */ if (!isEmpty(uci.get(uciconfig, uciinfra, 'tun_gso'))) uci.delete(uciconfig, uciinfra, 'tun_gso'); /* create migration section */ if (!uci.get(uciconfig, ucimigration)) uci.set(uciconfig, ucimigration, uciconfig); /* delete old crontab command */ const migration_crontab = uci.get(uciconfig, ucimigration, 'crontab'); if (!migration_crontab) { system('sed -i "/update_crond.sh/d" "/etc/crontabs/root" 2>"/dev/null"'); uci.set(uciconfig, ucimigration, 'crontab', '1'); } /* log_level was introduced */ if (isEmpty(uci.get(uciconfig, ucimain, 'log_level'))) uci.set(uciconfig, ucimain, 'log_level', 'warn'); if (isEmpty(uci.get(uciconfig, uciserver, 'log_level'))) uci.set(uciconfig, uciserver, 'log_level', 'warn'); /* empty value defaults to all ports now */ if (uci.get(uciconfig, ucimain, 'routing_port') === 'all') uci.delete(uciconfig, ucimain, 'routing_port'); /* experimental section was removed */ if (uci.get(uciconfig, 'experimental')) uci.delete(uciconfig, 'experimental'); /* block-dns was removed from built-in dns servers */ const default_dns_server = uci.get(uciconfig, ucidns, 'default_server'); if (default_dns_server === 'block-dns') { /* append a rule at last to block all DNS queries */ uci.set(uciconfig, '_migration_dns_final_block', ucidnsrule); uci.set(uciconfig, '_migration_dns_final_block', 'label', 'migration_final_block_dns'); uci.set(uciconfig, '_migration_dns_final_block', 'enabled', '1'); uci.set(uciconfig, '_migration_dns_final_block', 'mode', 'default'); uci.set(uciconfig, '_migration_dns_final_block', 'action', 'reject'); uci.set(uciconfig, ucidns, 'default_server', 'default-dns'); } const dns_server_migration = {}; /* DNS servers options */ uci.foreach(uciconfig, ucidnsserver, (cfg) => { /* legacy format was deprecated in sb 1.12 */ if (cfg.address) { const addr = parseURL((!match(cfg.address, /:\/\//) ? 'udp://' : '') + (validation('ip6addr', cfg.address) ? `[${cfg.address}]` : cfg.address)); /* RCode was moved into DNS rules */ if (addr.protocol === 'rcode') { dns_server_migration[cfg['.name']] = { action: 'predefined' }; switch (addr.hostname) { case 'success': dns_server_migration[cfg['.name']].rcode = 'NOERROR'; break; case 'format_error': dns_server_migration[cfg['.name']].rcode = 'FORMERR'; break; case 'server_failure': dns_server_migration[cfg['.name']].rcode = 'SERVFAIL'; break; case 'name_error': dns_server_migration[cfg['.name']].rcode = 'NXDOMAIN'; break; case 'not_implemented': dns_server_migration[cfg['.name']].rcode = 'NOTIMP'; break; case 'refused': default: dns_server_migration[cfg['.name']].rcode = 'REFUSED'; break; } uci.delete(uciconfig, cfg['.name']); return; } uci.set(uciconfig, cfg['.name'], 'type', addr.protocol); uci.set(uciconfig, cfg['.name'], 'server', addr.hostname); uci.set(uciconfig, cfg['.name'], 'server_port', addr.port); uci.set(uciconfig, cfg['.name'], 'path', (addr.pathname !== '/') ? addr.pathname : null); uci.delete(uciconfig, cfg['.name'], 'address'); } if (cfg.strategy) { if (cfg['.name'] === default_dns_server) uci.set(uciconfig, ucidns, 'default_strategy', cfg.strategy); dns_server_migration[cfg['.name']] = { strategy: cfg.strategy }; uci.delete(uciconfig, cfg['.name'], 'strategy'); } if (cfg.client_subnet) { if (cfg['.name'] === default_dns_server) uci.set(uciconfig, ucidns, 'client_subnet', cfg.client_subnet); if (isEmpty(dns_server_migration[cfg['.name']])) dns_server_migration[cfg['.name']] = {}; dns_server_migration[cfg['.name']].client_subnet = cfg.client_subnet; uci.delete(uciconfig, cfg['.name'], 'client_subnet'); } }); /* DNS rules options */ uci.foreach(uciconfig, ucidnsrule, (cfg) => { /* outbound was removed in sb 1.12 */ if (cfg.outbound) { uci.delete(uciconfig, cfg['.name']); if (!cfg.enabled) return; map(cfg.outbound, (outbound) => { switch (outbound) { case 'direct-out': case 'block-out': break; case 'any-out': uci.set(uciconfig, ucirouting, 'default_outbound_dns', cfg.server); break; default: uci.set(uciconfig, cfg.outbound, 'domain_resolver', cfg.server); break; } }); return; } /* rule_set_ipcidr_match_source was renamed in sb 1.10 */ if (cfg.rule_set_ipcidr_match_source === '1') uci.rename(uciconfig, cfg['.name'], 'rule_set_ipcidr_match_source', 'rule_set_ip_cidr_match_source'); /* block-dns was moved into action in sb 1.11 */ if (cfg.server === 'block-dns') { uci.set(uciconfig, cfg['.name'], 'action', 'reject'); uci.delete(uciconfig, cfg['.name'], 'server'); } else if (!cfg.action) { /* add missing 'action' field */ uci.set(uciconfig, cfg['.name'], 'action', 'route'); } /* strategy and client_subnet were moved into dns rules */ if (dns_server_migration[cfg.server]) { if (dns_server_migration[cfg.server].strategy) uci.set(uciconfig, cfg['.name'], 'strategy', dns_server_migration[cfg.server].strategy); if (dns_server_migration[cfg.server].client_subnet) uci.set(uciconfig, cfg['.name'], 'client_subnet', dns_server_migration[cfg.server].client_subnet); if (dns_server_migration[cfg.server].rcode) { uci.set(uciconfig, cfg['.name'], 'action', 'predefined'); uci.set(uciconfig, cfg['.name'], 'rcode', dns_server_migration[cfg.server].rcode); uci.delete(uciconfig, cfg['.name'], 'server'); } } }); /* nodes options */ uci.foreach(uciconfig, ucinode, (cfg) => { /* tls_ech_tls_disable_drs is useless and deprecated in sb 1.12 */ if (!isEmpty(cfg.tls_ech_tls_disable_drs)) uci.delete(uciconfig, cfg['.name'], 'tls_ech_tls_disable_drs'); /* tls_ech_enable_pqss is useless and deprecated in sb 1.12 */ if (!isEmpty(cfg.tls_ech_enable_pqss)) uci.delete(uciconfig, cfg['.name'], 'tls_ech_enable_pqss'); /* wireguard_gso was deprecated in sb 1.11 */ if (!isEmpty(cfg.wireguard_gso)) uci.delete(uciconfig, cfg['.name'], 'wireguard_gso'); }); /* routing rules options */ uci.foreach(uciconfig, uciroutingrule, (cfg) => { /* rule_set_ipcidr_match_source was renamed in sb 1.10 */ if (cfg.rule_set_ipcidr_match_source === '1') uci.rename(uciconfig, cfg['.name'], 'rule_set_ipcidr_match_source', 'rule_set_ip_cidr_match_source'); /* block-out was moved into action in sb 1.11 */ if (cfg.outbound === 'block-out') { uci.set(uciconfig, cfg['.name'], 'action', 'reject'); uci.delete(uciconfig, cfg['.name'], 'outbound'); } else if (!cfg.action) { /* add missing 'action' field */ uci.set(uciconfig, cfg['.name'], 'action', 'route'); } }); /* server options */ /* auto_firewall was moved into server options */ const auto_firewall = uci.get(uciconfig, uciserver, 'auto_firewall'); if (!isEmpty(auto_firewall)) uci.delete(uciconfig, uciserver, 'auto_firewall'); uci.foreach(uciconfig, uciserver, (cfg) => { /* auto_firewall was moved into server options */ if (auto_firewall === '1') uci.set(uciconfig, cfg['.name'], 'firewall' , '1'); /* sniff_override was deprecated in sb 1.11 */ if (!isEmpty(cfg.sniff_override)) uci.delete(uciconfig, cfg['.name'], 'sniff_override'); /* domain_strategy is now pointless without sniff override */ if (!isEmpty(cfg.domain_strategy)) uci.delete(uciconfig, cfg['.name'], 'domain_strategy'); }); if (!isEmpty(uci.changes(uciconfig))) uci.commit(uciconfig);
2929004360/ruoyi-sign
1,720
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfModelProcdefMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfModelProcdef; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 模型部署Mapper接口 * * @author fengcheng * @date 2024-07-11 */ public interface WfModelProcdefMapper { /** * 查询模型部署 * * @param modelId 模型部署主键 * @return 模型部署 */ public WfModelProcdef selectWfModelProcdefByModelId(String modelId); /** * 查询模型部署列表 * * @param wfModelProcdef 模型部署 * @return 模型部署集合 */ public List<WfModelProcdef> selectWfModelProcdefList(WfModelProcdef wfModelProcdef); /** * 新增模型部署 * * @param wfModelProcdef 模型部署 * @return 结果 */ public int insertWfModelProcdef(WfModelProcdef wfModelProcdef); /** * 修改模型部署 * * @param wfModelProcdef 模型部署 * @return 结果 */ public int updateWfModelProcdef(WfModelProcdef wfModelProcdef); /** * 删除模型部署 * * @param modelId 模型部署主键 * @return 结果 */ public int deleteWfModelProcdefByModelId(String modelId); /** * 批量删除模型部署 * * @param modelIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfModelProcdefByModelIds(String[] modelIds); /** * 根据模型id列表查询模型部署id * * @param modelIdList * @return */ List<String> selectWfModelProcdefListByModelIdList(@Param("modelIdList") List<String> modelIdList); /** * 根据部署id删除模型部署信息 * * @param deployId * @return */ int deleteWfModelProcdefByProcdefId(String deployId); /** * 根据部署id查询模型部署信息 * * @param procdefId * @return */ WfModelProcdef selectWfModelProcdefByProcdefId(String procdefId); }
2929004360/ruoyi-sign
1,333
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfRoamHistoricalMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfRoamHistorical; import java.util.List; /** * 历史流转记录Mapper接口 * * @author fengcheng * @date 2024-08-16 */ public interface WfRoamHistoricalMapper { /** * 查询历史流转记录 * * @param roamHistoricalId 历史流转记录主键 * @return 历史流转记录 */ public WfRoamHistorical selectWfRoamHistoricalByRoamHistoricalId(String roamHistoricalId); /** * 查询历史流转记录列表 * * @param wfRoamHistorical 历史流转记录 * @return 历史流转记录集合 */ public List<WfRoamHistorical> selectWfRoamHistoricalList(WfRoamHistorical wfRoamHistorical); /** * 新增历史流转记录 * * @param wfRoamHistorical 历史流转记录 * @return 结果 */ public int insertWfRoamHistorical(WfRoamHistorical wfRoamHistorical); /** * 修改历史流转记录 * * @param wfRoamHistorical 历史流转记录 * @return 结果 */ public int updateWfRoamHistorical(WfRoamHistorical wfRoamHistorical); /** * 删除历史流转记录 * * @param roamHistoricalId 历史流转记录主键 * @return 结果 */ public int deleteWfRoamHistoricalByRoamHistoricalId(String roamHistoricalId); /** * 批量删除历史流转记录 * * @param roamHistoricalIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfRoamHistoricalByRoamHistoricalIds(String[] roamHistoricalIds); }
2929004360/ruoyi-sign
1,864
ruoyi-flowable/src/main/java/com/ruoyi/flowable/mapper/WfModelPermissionMapper.java
package com.ruoyi.flowable.mapper; import com.ruoyi.flowable.domain.WfModelPermission; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 流程模型权限Mapper接口 * * @author fengcheng * @date 2024-07-10 */ public interface WfModelPermissionMapper { /** * 查询流程模型权限 * * @param modelPermissionId 流程模型权限主键 * @return 流程模型权限 */ public WfModelPermission selectWfModelPermissionByModelPermissionId(String modelPermissionId); /** * 查询流程模型权限列表 * * @param wfModelPermission 流程模型权限 * @param permissionIdList 业务id列表 * @return 流程模型权限集合 */ public List<WfModelPermission> selectWfModelPermissionList( @Param("wfModelPermission") WfModelPermission wfModelPermission, @Param("permissionIdList") List<Long> permissionIdList ); /** * 新增流程模型权限 * * @param wfModelPermission 流程模型权限 * @return 结果 */ public int insertWfModelPermission(WfModelPermission wfModelPermission); /** * 修改流程模型权限 * * @param wfModelPermission 流程模型权限 * @return 结果 */ public int updateWfModelPermission(WfModelPermission wfModelPermission); /** * 删除流程模型权限 * * @param modelPermissionId 流程模型权限主键 * @return 结果 */ public int deleteWfModelPermissionByModelPermissionId(String modelPermissionId); /** * 批量删除流程模型权限 * * @param modelPermissionIds 需要删除的数据主键集合 * @return 结果 */ public int deleteWfModelPermissionByModelPermissionIds(String[] modelPermissionIds); /** * 批量插入流程模型权限 * * @param permissionsList * @return */ int insertWfModelPermissionList(List<WfModelPermission> permissionsList); /** * 根据模型ID删除流程模型权限 * * @param modelId * @return */ int deleteWfModelPermissionByModelId(String modelId); }
2929004360/ruoyi-sign
2,765
ruoyi-flowable/src/main/java/com/ruoyi/flowable/base/BaseController.java
package com.ruoyi.flowable.base; import com.github.pagehelper.PageInfo; import com.ruoyi.common.constant.HttpStatus; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.PageUtils; import com.ruoyi.flowable.page.TableDataInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import java.beans.PropertyEditorSupport; import java.util.Date; import java.util.List; /** * web层通用数据处理 * * @author ruoyi */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 清理分页的线程变量 */ protected void clearPage() { PageUtils.clearPage(); } /** * 响应请求分页数据 */ @SuppressWarnings({"rawtypes", "unchecked"}) protected TableDataInfo getDataTable(List<?> list) { TableDataInfo rspData = new TableDataInfo(); rspData.setCode(HttpStatus.SUCCESS); rspData.setRows(list); rspData.setMsg("查询成功"); rspData.setTotal(new PageInfo(list).getTotal()); return rspData; } /** * 返回成功 */ public AjaxResult success() { return AjaxResult.success(); } /** * 返回成功消息 */ public AjaxResult success(String message) { return AjaxResult.success(message); } /** * 返回成功消息 */ public AjaxResult success(Object data) { return AjaxResult.success(data); } /** * 返回失败消息 */ public AjaxResult error() { return AjaxResult.error(); } /** * 返回失败消息 */ public AjaxResult error(String message) { return AjaxResult.error(message); } /** * 返回警告消息 */ public AjaxResult warn(String message) { return AjaxResult.warn(message); } /** * 响应返回结果 * * @param rows 影响行数 * @return 操作结果 */ protected AjaxResult toAjax(int rows) { return rows > 0 ? AjaxResult.success() : AjaxResult.error(); } /** * 响应返回结果 * * @param result 结果 * @return 操作结果 */ protected AjaxResult toAjax(boolean result) { return result ? success() : error(); } }
2977094657/BilibiliHistoryFetcher
75,268
routers/download.py
import asyncio import os import re import subprocess import sys from datetime import datetime from typing import Optional, List, Dict, Any, Tuple import requests from fastapi import APIRouter, HTTPException, Query from fastapi.responses import StreamingResponse, FileResponse from pydantic import BaseModel, Field import httpx import json from scripts.utils import load_config from scripts.yutto_runner import run_yutto # 尝试导入 history 模块,用于处理图像 URL try: from routers.history import _process_image_url, get_video_by_cid, _process_record except ImportError: # 如果无法直接导入,则在运行时动态加载 _process_image_url = None get_video_by_cid = None _process_record = None print("无法从 history 模块导入_process_image_url、get_video_by_cid 和_process_record 函数") router = APIRouter() config = load_config() # 辅助函数:检查下载目录和临时目录 def check_download_directories() -> Tuple[str, str]: """ 检查下载目录和临时目录是否存在且有写入权限 Returns: 下载目录和临时目录的路径元组 Raises: HTTPException: 如果目录不存在或没有写入权限 """ download_dir = os.path.normpath(config['yutto']['basic']['dir']) tmp_dir = os.path.normpath(config['yutto']['basic']['tmp_dir']) # 创建目录(如果不存在) os.makedirs(download_dir, exist_ok=True) os.makedirs(tmp_dir, exist_ok=True) # 检查目录权限 if not os.access(download_dir, os.W_OK): raise HTTPException( status_code=500, detail=f"没有下载目录的写入权限:{download_dir}" ) if not os.access(tmp_dir, os.W_OK): raise HTTPException( status_code=500, detail=f"没有临时目录的写入权限:{tmp_dir}" ) return download_dir, tmp_dir # 辅助函数:准备进程参数 def prepare_process_kwargs() -> Dict[str, Any]: """ 准备进程参数 Returns: 进程参数字典 """ # 设置环境变量 env = os.environ.copy() env['PYTHONIOENCODING'] = 'utf-8' env['PYTHONUTF8'] = '1' env['PYTHONUNBUFFERED'] = '1' # 确保 Python 输出不被缓存 # 在 Linux 上确保 PATH 包含 python 环境 if sys.platform != 'win32': env['PATH'] = f"{os.path.dirname(sys.executable)}:{env.get('PATH', '')}" # 添加 virtualenv 的 site-packages 路径(如果存在) site_packages = os.path.join(os.path.dirname(os.path.dirname(sys.executable)), 'lib', 'python*/site-packages') env['PYTHONPATH'] = f"{site_packages}:{env.get('PYTHONPATH', '')}" # 准备进程参数 popen_kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'encoding': 'utf-8', 'errors': 'replace', 'universal_newlines': True, 'env': env, 'bufsize': 1, # 行缓冲 'shell': sys.platform != 'win32' # 在非 Windows 系统上使用 shell } # 在 Windows 系统上添加 CREATE_NO_WINDOW 标志 if sys.platform == 'win32': popen_kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW if hasattr(subprocess, 'CREATE_NO_WINDOW') else 0 popen_kwargs['shell'] = False # Windows 上不使用 shell return popen_kwargs # 辅助函数:格式化命令 def format_command(command: List[str]) -> str: """ 格式化命令,处理特殊字符 Args: command: 命令列表 Returns: 格式化后的命令字符串 """ if sys.platform != 'win32': return ' '.join(f"'{arg}'" if ((' ' in arg) or ("'" in arg) or ('"' in arg)) else arg for arg in command) return ' '.join(command) # 辅助函数:添加下载参数到命令 def add_download_params_to_command(command: List[str], params: Any) -> List[str]: """ 将下载参数添加到命令中 Args: command: 命令列表 params: 包含下载参数的对象 Returns: 添加了下载参数的命令列表 """ # 基础参数 # 视频清晰度 if params.video_quality is not None: command.extend(['--video-quality', str(params.video_quality)]) # 音频码率 if params.audio_quality is not None: command.extend(['--audio-quality', str(params.audio_quality)]) # 视频编码 if params.vcodec: command.extend(['--vcodec', params.vcodec]) # 音频编码 if params.acodec: command.extend(['--acodec', params.acodec]) # 视频下载编码优先级 if params.download_vcodec_priority: command.extend(['--download-vcodec-priority', params.download_vcodec_priority]) # 输出格式 if params.output_format: command.extend(['--output-format', params.output_format]) # 仅包含音频流时的输出格式 if params.output_format_audio_only: command.extend(['--output-format-audio-only', params.output_format_audio_only]) # 资源选择参数 # 仅下载视频流 if params.video_only: command.append('--video-only') # 仅下载音频流 if params.only_audio: command.append('--audio-only') # 不生成弹幕文件 if params.no_danmaku: command.append('--no-danmaku') # 仅生成弹幕文件 if params.danmaku_only: command.append('--danmaku-only') # 不生成字幕文件 if params.no_subtitle or not config['yutto']['resource']['require_subtitle']: command.append('--no-subtitle') # 仅生成字幕文件 if params.subtitle_only: command.append('--subtitle-only') # 仅生成媒体元数据文件 if params.metadata_only: command.append('--metadata-only') # 不生成视频封面 if not params.download_cover: command.append('--no-cover') # 生成视频流封面时单独保存封面 if params.save_cover: command.append('--save-cover') # 仅生成视频封面 if params.cover_only: command.append('--cover-only') # 不生成章节信息 if params.no_chapter_info: command.append('--no-chapter-info') # 添加其他 yutto 配置 if config['yutto']['danmaku']['font_size']: command.extend(['--danmaku-font-size', str(config['yutto']['danmaku']['font_size'])]) if config['yutto']['batch']['with_section']: command.append('--with-section') # 如果提供了 SESSDATA,添加到命令中 if hasattr(params, 'sessdata') and params.sessdata: command.extend(['--sessdata', params.sessdata]) elif config.get('SESSDATA'): command.extend(['--sessdata', config['SESSDATA']]) return command def extract_datetime_from_string(text): """ 从字符串中提取日期时间 支持的格式: 1. YYYYMMDD_HHMMSS 2. YYYYMMDD_HHMM 3. YYYYMMDD 4. Unix 时间戳 Args: text: 要检查的字符串 Returns: 格式化的日期时间字符串或 None """ # 调试信息 print(f"【时间提取】尝试从'{text}'中提取日期时间") # 尝试匹配 YYYYMMDD_HHMMSS 格式 match1 = re.match(r'.*?(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2}).*', text) if match1: year, month, day, hour, minute, second = match1.groups() result = f"{year}-{month}-{day} {hour}:{minute}:{second}" print(f"【时间提取】匹配 YYYYMMDD_HHMMSS 格式:{result}") return result # 尝试匹配 YYYYMMDD_HHMM 格式 match2 = re.match(r'.*?(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2}).*', text) if match2: year, month, day, hour, minute = match2.groups() result = f"{year}-{month}-{day} {hour}:{minute}:00" print(f"【时间提取】匹配 YYYYMMDD_HHMM 格式:{result}") return result # 尝试匹配纯 YYYYMMDD 格式 match3 = re.match(r'.*?(\d{4})(\d{2})(\d{2}).*', text) if match3: year, month, day = match3.groups() result = f"{year}-{month}-{day} 00:00:00" print(f"【时间提取】匹配 YYYYMMDD 格式:{result}") return result # 尝试匹配 Unix 时间戳(最后 10 位数字) match4 = re.match(r'^(\d{10})$', text) if match4: try: timestamp = int(match4.group(1)) dt = datetime.fromtimestamp(timestamp) result = dt.strftime("%Y-%m-%d %H:%M:%S") print(f"【时间提取】匹配 Unix 时间戳:{result}") return result except: pass print(f"【时间提取】未能从'{text}'中提取日期时间") return None # 基础下载参数模型类 class BaseDownloadParams(BaseModel): """所有下载请求的基础参数""" sessdata: Optional[str] = Field(None, description="用户的 SESSDATA") download_cover: Optional[bool] = Field(True, description="是否下载视频封面") only_audio: Optional[bool] = Field(False, description="是否仅下载音频") # 基础参数 video_quality: Optional[int] = Field(None, description="视频清晰度等级,可选值:127|126|125|120|116|112|100|80|74|64|32|16") audio_quality: Optional[int] = Field(None, description="音频码率等级,可选值:30251|30255|30250|30280|30232|30216") vcodec: Optional[str] = Field(None, description="视频编码,格式为'下载编码:保存编码',如'avc:copy'") acodec: Optional[str] = Field(None, description="音频编码,格式为'下载编码:保存编码',如'mp4a:copy'") download_vcodec_priority: Optional[str] = Field(None, description="视频下载编码优先级,如'hevc,avc,av1'") output_format: Optional[str] = Field(None, description="输出格式,可选值:infer|mp4|mkv|mov") output_format_audio_only: Optional[str] = Field(None, description="仅包含音频流时的输出格式,可选值:infer|m4a|aac|mp3|flac|mp4|mkv|mov") # 资源选择参数 video_only: Optional[bool] = Field(False, description="是否仅下载视频流") danmaku_only: Optional[bool] = Field(False, description="是否仅生成弹幕文件") no_danmaku: Optional[bool] = Field(False, description="是否不生成弹幕文件") subtitle_only: Optional[bool] = Field(False, description="是否仅生成字幕文件") no_subtitle: Optional[bool] = Field(False, description="是否不生成字幕文件") metadata_only: Optional[bool] = Field(False, description="是否仅生成媒体元数据文件") save_cover: Optional[bool] = Field(False, description="生成视频流封面时是否单独保存封面") cover_only: Optional[bool] = Field(False, description="是否仅生成视频封面") no_chapter_info: Optional[bool] = Field(False, description="是否不生成章节信息") class DownloadRequest(BaseDownloadParams): """单个视频下载请求""" url: str = Field(..., description="视频URL") cid: int = Field(..., description="视频的 CID,用于分类存储和音频文件命名前缀") class UserSpaceDownloadRequest(BaseDownloadParams): """用户空间视频下载请求""" user_id: str = Field(..., description="用户 UID,例如:100969474") class FavoriteDownloadRequest(BaseDownloadParams): """收藏夹下载请求""" user_id: str = Field(..., description="用户 UID,例如:100969474") fid: Optional[str] = Field(None, description="收藏夹 ID,不提供时下载所有收藏夹") class VideoInfo(BaseModel): """视频信息""" bvid: str = Field(..., description="视频的 BVID") cid: int = Field(..., description="视频的 CID") title: Optional[str] = Field(None, description="视频标题") author: Optional[str] = Field(None, description="视频作者") cover: Optional[str] = Field(None, description="视频封面URL") class BatchDownloadRequest(BaseDownloadParams): """批量下载请求""" videos: List[VideoInfo] = Field(..., description="要下载的视频列表") async def stream_process_output(process: subprocess.Popen): """实时流式输出进程的输出""" try: # 创建异步迭代器来读取输出 async def read_output(): while True: line = await asyncio.get_event_loop().run_in_executor(None, process.stdout.readline) if not line: break yield line.strip() # 实时读取并发送标准输出 async for line in read_output(): if line: yield f"data: {line}\n\n" # 立即刷新输出 await asyncio.sleep(0) # 等待进程完成 return_code = await asyncio.get_event_loop().run_in_executor(None, process.wait) # 读取可能的错误输出 stderr_output = await asyncio.get_event_loop().run_in_executor(None, process.stderr.read) if stderr_output: # 将错误输出按行分割并发送 for line in stderr_output.strip().split('\n'): yield f"data: ERROR: {line}\n\n" await asyncio.sleep(0) # 发送完成事件 if return_code == 0: yield "data: 下载完成\n\n" else: # 如果有错误码,发送更详细的错误信息 yield f"data: 下载失败,错误码:{return_code}\n\n" # 尝试获取更多错误信息 try: if process.stderr: process.stderr.seek(0) full_error = process.stderr.read() if full_error: yield f"data: 完整错误信息:\n{full_error}\n\n" except Exception as e: yield f"data: 无法获取完整错误信息:{str(e)}\n\n" except Exception as e: yield f"data: 处理过程出错:{str(e)}\n\n" import traceback yield f"data: 错误堆栈:\n{traceback.format_exc()}\n\n" finally: # 确保进程已结束 if process.poll() is None: process.terminate() await asyncio.get_event_loop().run_in_executor(None, process.wait) yield "event: close\ndata: close\n\n" @router.post("/download_video", summary="下载 B 站视频") async def download_video(request: DownloadRequest): """ 下载 B 站视频 Args: request: 包含视频 URL 和可选 SESSDATA 的请求对象 """ try: # 检查下载目录和临时目录 download_dir, tmp_dir = check_download_directories() # 构建基本命令 command = [ request.url, '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{{title}}_{{username}}_{{download_date@%Y%m%d_%H%M%S}}_{request.cid}/{{title}}_{request.cid}', '--with-metadata' # 添加元数据文件保存 ] # 添加下载参数 command = add_download_params_to_command(command, request) print(f"执行下载命令:yutto {' '.join(command)}") async def event_stream(): async for chunk in run_yutto(command): yield chunk yield "event: close\ndata: close\n\n" return StreamingResponse(event_stream(), media_type="text/event-stream") except FileNotFoundError: raise HTTPException( status_code=500, detail="找不到 yutto 命令,请确保已正确安装" ) except Exception as e: raise HTTPException( status_code=500, detail=f"下载过程出错:{str(e)}" ) @router.get("/check_ffmpeg", summary="检查 FFmpeg 版本") async def check_ffmpeg(): """ 检查 FFmpeg 是否安装及其版本信息 Returns: 如果安装了 FFmpeg,返回版本信息 如果未安装,返回简单的未安装信息 """ try: # 获取系统信息 import platform system = platform.system().lower() release = platform.release() os_info = { "system": system, "release": release, "platform": platform.platform() } # 根据不同系统使用不同的命令检查 FFmpeg if system == 'windows': ffmpeg_check_cmd = 'where ffmpeg' else: ffmpeg_check_cmd = 'which ffmpeg' # 检查 FFmpeg 是否安装 ffmpeg_process = subprocess.run( ffmpeg_check_cmd.split(), capture_output=True, text=True ) if ffmpeg_process.returncode == 0: # FFmpeg 已安装,获取版本信息 version_process = subprocess.run(['ffmpeg', '-version'], capture_output=True, text=True) if version_process.returncode == 0: version_info = version_process.stdout.splitlines()[0] return { "status": "success", "installed": True, "version": version_info, "path": ffmpeg_process.stdout.strip(), "os_info": os_info } # FFmpeg 未安装,返回简单的未安装信息 return { "status": "error", "installed": False, "message": "FFmpeg 未安装", "os_info": os_info } except Exception as e: return { "status": "error", "installed": False, "message": f"检查 FFmpeg 失败:{str(e)}", "error": str(e), "os_info": os_info if 'os_info' in locals() else { "system": platform.system().lower(), "release": platform.release(), "platform": platform.platform() } } @router.get("/check_video_download", summary="检查视频是否已下载") async def check_video_download(cids: str): """ 检查指定 CID 的视频是否已下载,如果已下载则返回保存路径 支持批量检查多个 CID,使用逗号分隔 Args: cids: 视频的 CID,多个 CID 用逗号分隔,如"12345,67890" Returns: dict: 包含检查结果和视频保存信息的字典 """ try: # 解析 CID 列表 cid_list = [int(cid.strip()) for cid in cids.split(",") if cid.strip()] if not cid_list: return { "status": "error", "message": "未提供有效的 CID" } # 获取下载目录路径 download_dir = os.path.normpath(config['yutto']['basic']['dir']) # 确保下载目录存在 if not os.path.exists(download_dir): return { "status": "success", "results": {cid: {"downloaded": False, "message": "下载目录不存在,视频尚未下载"} for cid in cid_list} } # 存储每个 CID 的检查结果 result_dict = {} # 递归遍历下载目录查找匹配的视频文件 for cid in cid_list: found_files = [] found_directory = None download_time = None for root, dirs, files in os.walk(download_dir): # 检查目录名是否包含 CID dir_name = os.path.basename(root) if f"_{cid}" in dir_name: found_directory = root # 从目录名中提取下载时间 try: # 首先尝试从目录名中直接提取 download_time = extract_datetime_from_string(dir_name) # 如果没找到,尝试从目录名的各个部分提取 if not download_time: dir_parts = dir_name.split('_') for part in dir_parts: extracted_time = extract_datetime_from_string(part) if extracted_time: download_time = extracted_time break # 如果仍然没找到,尝试使用文件的创建时间 if not download_time and files: # 确保有文件存在 # 使用第一个文件的创建时间 first_file_path = os.path.join(root, files[0]) if os.path.exists(first_file_path): creation_time = os.path.getctime(first_file_path) download_time = datetime.fromtimestamp(creation_time).strftime("%Y-%m-%d %H:%M:%S") print(f"【调试】使用文件创建时间作为下载时间:{download_time}") # 额外记录调试信息 if not download_time: print(f"【调试】无法从目录名提取日期时间:{dir_name}") print(f"【调试】目录名各部分:{dir_name.split('_')}") except Exception as e: print(f"提取下载时间出错:{str(e)}") # 检查目录中的文件 for file in files: # 检查文件名是否包含 CID if f"_{cid}" in file: # 检查是否为视频或音频文件 if file.endswith(('.mp4', '.flv', '.m4a', '.mp3')): file_path = os.path.join(root, file) file_size = os.path.getsize(file_path) file_size_mb = round(file_size / (1024 * 1024), 2) found_files.append({ "file_name": file, "file_path": file_path, "size_bytes": file_size, "size_mb": file_size_mb, "created_time": os.path.getctime(file_path), "modified_time": os.path.getmtime(file_path) }) if found_files: result_dict[cid] = { "downloaded": True, "message": f"已找到{len(found_files)}个匹配的视频文件", "files": found_files, "directory": found_directory, "download_time": download_time } else: result_dict[cid] = { "downloaded": False, "message": "未找到已下载的视频文件" } return { "status": "success", "results": result_dict } except Exception as e: return { "status": "error", "message": f"检查视频下载状态时出错:{str(e)}" } @router.get("/list_downloaded_videos", summary="获取或搜索已下载视频列表") async def list_downloaded_videos(search_term: Optional[str] = None, limit: int = 100, page: int = 1, use_local_images: bool = False): """ 获取已下载的视频列表,支持通过标题搜索 Args: search_term: 可选,搜索关键词,会在文件名和目录名中查找 limit: 每页返回的结果数量,默认 100 page: 页码,从 1 开始,默认为第 1 页 use_local_images: 是否使用本地图片,默认为 false Returns: dict: 包含已下载视频列表的字典 """ try: # 获取下载目录路径 download_dir = os.path.normpath(config['yutto']['basic']['dir']) # 确保下载目录存在 if not os.path.exists(download_dir): return { "status": "success", "message": "下载目录不存在,尚未下载任何视频", "videos": [], "total": 0, "page": page, "limit": limit, "pages": 0 } # 获取数据库连接 try: import sqlite3 db_path = os.path.join('output', 'bilibili_history.db') conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row # 将结果转换为字典形式 db_available = True except Exception as e: print(f"无法连接到数据库:{str(e)}") db_available = False conn = None # 递归遍历下载目录查找视频文件 videos = [] for root, dirs, files in os.walk(download_dir): # 过滤仅包含视频文件的目录 video_files = [] dir_name = os.path.basename(root) # 如果指定了搜索关键词,检查目录名 if search_term and search_term.lower() not in dir_name.lower(): # 跳过不匹配的目录,除非发现其中的文件名匹配 file_match = False for file in files: if search_term.lower() in file.lower() and file.endswith(('.mp4', '.flv', '.m4a', '.mp3')): file_match = True break if not file_match: continue # 检查是否存在元数据文件 metadata_file = os.path.join(root, "metadata.json") metadata = None if os.path.exists(metadata_file): try: with open(metadata_file, 'r', encoding='utf-8') as f: import json metadata = json.load(f) print(f"【调试】从元数据文件获取数据:{metadata_file}") # 显示元数据文件内容摘要 if 'title' in metadata: print(f"【调试】元数据标题:{metadata['title']}") if 'id' in metadata: if 'bvid' in metadata['id']: print(f"【调试】元数据 BVID: {metadata['id']['bvid']}") if 'cid' in metadata['id']: print(f"【调试】元数据 CID: {metadata['id']['cid']}") if 'owner' in metadata and 'name' in metadata['owner']: print(f"【调试】元数据作者:{metadata['owner']['name']}") if 'cover_url' in metadata: print(f"【调试】元数据封面:{metadata['cover_url']}") except Exception as e: print(f"读取元数据文件出错:{str(e)}") # 尝试查找.nfo 文件 nfo_files = [f for f in files if f.endswith('.nfo')] nfo_data = None if nfo_files: try: import xml.etree.ElementTree as ET nfo_file = os.path.join(root, nfo_files[0]) tree = ET.parse(nfo_file) nfo_data = tree.getroot() print(f"【调试】从 NFO 文件获取数据:{nfo_file}") except Exception as e: print(f"读取 NFO 文件出错:{str(e)}") for file in files: # 检查是否为视频或音频文件 if file.endswith(('.mp4', '.flv', '.m4a', '.mp3')): # 如果指定了搜索关键词,检查文件名 if search_term and search_term.lower() not in file.lower() and search_term.lower() not in dir_name.lower(): continue file_path = os.path.join(root, file) file_size = os.path.getsize(file_path) file_size_mb = round(file_size / (1024 * 1024), 2) # 从目录名和文件名中提取信息 dir_parts = dir_name.split('_') file_parts = file.split('_') # 尝试提取 CID cid = None try: if len(dir_parts) > 3: cid = dir_parts[-1] # 最后一部分应该是 CID elif len(file_parts) > 1: cid = file_parts[-1].split('.')[0] # 文件名最后一部分的。前部分 except: pass # 尝试从目录名提取标题 title = None try: if len(dir_parts) > 0: # 除去最后 3 个部分(用户名_日期_CID),剩下的应该是标题 title = '_'.join(dir_parts[:-3]) if len(dir_parts) > 3 else dir_name except: title = dir_name # 尝试提取日期时间 date_time = None try: print(f"【调试】处理目录:{dir_name}") # 首先尝试从完整目录名中直接提取 date_time = extract_datetime_from_string(dir_name) # 如果没找到,尝试从目录名的各个部分提取 if not date_time: dir_parts = dir_name.split('_') print(f"【调试】目录名各部分:{dir_parts}") for part in dir_parts: print(f"【调试】检查部分:{part}") extracted_time = extract_datetime_from_string(part) if extracted_time: date_time = extracted_time print(f"【调试】从部分'{part}'提取到时间:{date_time}") break # 如果仍然没找到,尝试使用文件的创建时间 if not date_time: # 使用即将添加到 video_files 的文件创建时间 creation_time = os.path.getctime(file_path) date_time = datetime.fromtimestamp(creation_time).strftime("%Y-%m-%d %H:%M:%S") print(f"【调试】使用文件创建时间作为下载时间:{date_time}") # 额外记录调试信息 print(f"【调试】无法从目录名提取日期时间:{dir_name}") except Exception as e: print(f"提取下载时间出错:{str(e)}") video_files.append({ "file_name": file, "file_path": file_path, "size_bytes": file_size, "size_mb": file_size_mb, "created_time": os.path.getctime(file_path), "modified_time": os.path.getmtime(file_path), "is_audio_only": file.endswith(('.m4a', '.mp3')) }) if video_files: video_info = { "directory": root, "dir_name": dir_name, "title": title, "cid": cid, "bvid": None, # 初始化 bvid 字段为 None "download_date": date_time, "files": video_files, "cover": None, "author_face": None, "author_name": None, "author_mid": None } # 如果存在元数据,优先使用元数据中的信息 if metadata: try: # 提取 bvid 和 cid if 'id' in metadata: video_id = metadata['id'] if 'bvid' in video_id: video_info["bvid"] = video_id['bvid'] if 'cid' in video_id and not video_info["cid"]: video_info["cid"] = str(video_id['cid']) # 提取标题 if 'title' in metadata and metadata['title']: video_info["title"] = metadata['title'] # 提取封面 URL if 'cover_url' in metadata and metadata['cover_url']: video_info["cover"] = metadata['cover_url'] # 提取作者信息 if 'owner' in metadata: owner = metadata['owner'] if 'name' in owner: video_info["author_name"] = owner['name'] if 'face' in owner: video_info["author_face"] = owner['face'] if 'mid' in owner: video_info["author_mid"] = owner['mid'] # 处理图片 URL if _process_image_url: # 使用导入的函数处理图片 URL if video_info["cover"]: video_info["cover"] = _process_image_url(video_info["cover"], 'covers', use_local_images) if video_info["author_face"]: video_info["author_face"] = _process_image_url(video_info["author_face"], 'avatars', use_local_images) elif hasattr(sys.modules.get('routers.history'), '_process_image_url'): # 如果导入失败但模块运行时可访问,再次尝试 process_url = getattr(sys.modules.get('routers.history'), '_process_image_url') if video_info["cover"]: video_info["cover"] = process_url(video_info["cover"], 'covers', use_local_images) if video_info["author_face"]: video_info["author_face"] = process_url(video_info["author_face"], 'avatars', use_local_images) elif use_local_images: # 简单的 URL 处理逻辑,作为后备方案 import hashlib if video_info["cover"]: cover_hash = hashlib.md5(video_info["cover"].encode()).hexdigest() video_info["cover"] = f"/images/local/covers/{cover_hash}" if video_info["author_face"]: avatar_hash = hashlib.md5(video_info["author_face"].encode()).hexdigest() video_info["author_face"] = f"/images/local/avatars/{avatar_hash}" print(f"【调试】从元数据获取到视频信息:{video_info['title']},封面 URL: {video_info['cover'][:50]}...") except Exception as e: print(f"解析元数据时出错:{str(e)}") # 如果有 NFO 数据且信息不完整,尝试从 NFO 提取 if nfo_data and (not video_info["cover"] or not video_info["author_name"] or not video_info["author_face"]): try: # 提取标题 title_elem = nfo_data.find('title') if title_elem is not None and title_elem.text and not video_info["title"]: video_info["title"] = title_elem.text # 提取封面 URL thumb_elem = nfo_data.find('thumb') if thumb_elem is not None and thumb_elem.text and not video_info["cover"]: video_info["cover"] = thumb_elem.text # 提取作者信息 actor_elem = nfo_data.find('actor') if actor_elem is not None: # 作者名 actor_name = actor_elem.find('name') if actor_name is not None and actor_name.text and not video_info["author_name"]: video_info["author_name"] = actor_name.text # 作者头像 actor_thumb = actor_elem.find('thumb') if actor_thumb is not None and actor_thumb.text and not video_info["author_face"]: video_info["author_face"] = actor_thumb.text # 作者 ID/主页 actor_profile = actor_elem.find('profile') if actor_profile is not None and actor_profile.text and not video_info["author_mid"]: profile_url = actor_profile.text # 尝试从 URL 中提取 mid mid_match = re.search(r"space\.bilibili\.com/(\d+)", profile_url) if mid_match: video_info["author_mid"] = int(mid_match.group(1)) # 提取 BV 号 website_elem = nfo_data.find('website') if website_elem is not None and website_elem.text and not video_info["bvid"]: bvid_match = re.search(r"video/(BV\w+)", website_elem.text) if bvid_match: video_info["bvid"] = bvid_match.group(1) # 处理 NFO 文件中的图片 URL if _process_image_url: # 使用导入的函数处理图片 URL if video_info["cover"]: video_info["cover"] = _process_image_url(video_info["cover"], 'covers', use_local_images) if video_info["author_face"]: video_info["author_face"] = _process_image_url(video_info["author_face"], 'avatars', use_local_images) elif hasattr(sys.modules.get('routers.history'), '_process_image_url'): # 如果导入失败但模块运行时可访问,再次尝试 process_url = getattr(sys.modules.get('routers.history'), '_process_image_url') if video_info["cover"]: video_info["cover"] = process_url(video_info["cover"], 'covers', use_local_images) if video_info["author_face"]: video_info["author_face"] = process_url(video_info["author_face"], 'avatars', use_local_images) elif use_local_images: # 简单的 URL 处理逻辑,作为后备方案 import hashlib if video_info["cover"]: cover_hash = hashlib.md5(video_info["cover"].encode()).hexdigest() video_info["cover"] = f"/images/local/covers/{cover_hash}" if video_info["author_face"]: avatar_hash = hashlib.md5(video_info["author_face"].encode()).hexdigest() video_info["author_face"] = f"/images/local/avatars/{avatar_hash}" print(f"【调试】从 NFO 文件获取到视频信息:{video_info['title']},封面 URL: {video_info['cover'][:50] if video_info['cover'] else 'None'}") except Exception as e: print(f"解析 NFO 文件时出错:{str(e)}") # 如果有 CID 但没有其他信息,尝试通过 API 获取 if not metadata and not nfo_data and cid and cid.isdigit() and (not video_info["cover"] or not video_info["author_name"] or not video_info["author_face"]): try: # 仅当没有元数据和 NFO 文件时,才尝试通过 API 或数据库获取 print(f"【调试】没有找到元数据或 NFO 文件,尝试通过 API/数据库获取 CID={cid}的视频信息") # 方式 1: 直接调用 get_video_by_cid 函数(如果已成功导入) if get_video_by_cid: print(f"【调试】使用导入的 get_video_by_cid 函数获取 CID={cid}的视频信息") # 调用 API 函数获取视频信息 api_response = await get_video_by_cid(int(cid), use_local_images) if api_response["status"] == "success" and "data" in api_response: video_data = api_response["data"] video_info["title"] = video_data.get("title") or video_info["title"] video_info["cover"] = video_data.get("cover") video_info["author_face"] = video_data.get("author_face") video_info["author_name"] = video_data.get("author_name") video_info["author_mid"] = video_data.get("author_mid") video_info["bvid"] = video_data.get("bvid") # 添加 bvid 字段 print(f"【调试】成功通过 API 获取到视频信息:{video_data.get('title')}") # 方式 2: 如果 API 函数未导入,则回退到直接查询数据库 elif db_available: print(f"【调试】回退到直接查询数据库获取 CID={cid}的视频信息") cursor = conn.cursor() # 查询所有历史记录表 years = [table_name.split('_')[-1] for (table_name,) in cursor.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'bilibili_history_%'" ).fetchall() if table_name.split('_')[-1].isdigit()] # 构建 UNION ALL 查询所有年份表 if years: queries = [] for year in years: queries.append(f"SELECT title, cover, author_face, author_name, author_mid, bvid FROM bilibili_history_{year} WHERE cid = {cid} LIMIT 1") # 执行联合查询 union_query = " UNION ALL ".join(queries) + " LIMIT 1" result = cursor.execute(union_query).fetchone() if result: # 设置封面和作者信息 video_info["title"] = result["title"] or video_info["title"] video_info["cover"] = result["cover"] video_info["author_face"] = result["author_face"] video_info["author_name"] = result["author_name"] video_info["author_mid"] = result["author_mid"] video_info["bvid"] = result["bvid"] # 添加 bvid 字段 # 处理图片 URL if _process_image_url: # 使用导入的函数处理图片 URL if video_info["cover"]: video_info["cover"] = _process_image_url(video_info["cover"], 'covers', use_local_images) if video_info["author_face"]: video_info["author_face"] = _process_image_url(video_info["author_face"], 'avatars', use_local_images) elif hasattr(sys.modules.get('routers.history'), '_process_image_url'): # 如果导入失败但模块运行时可访问,再次尝试 process_url = getattr(sys.modules.get('routers.history'), '_process_image_url') if video_info["cover"]: video_info["cover"] = process_url(video_info["cover"], 'covers', use_local_images) if video_info["author_face"]: video_info["author_face"] = process_url(video_info["author_face"], 'avatars', use_local_images) else: # 简单的 URL 处理逻辑,作为后备方案 if use_local_images: import hashlib if video_info["cover"]: cover_hash = hashlib.md5(video_info["cover"].encode()).hexdigest() video_info["cover"] = f"/images/local/covers/{cover_hash}" if video_info["author_face"]: avatar_hash = hashlib.md5(video_info["author_face"].encode()).hexdigest() video_info["author_face"] = f"/images/local/avatars/{avatar_hash}" except Exception as e: print(f"获取视频信息时出错:{str(e)}") # 检查是否为合集或多P视频 is_collection = False collection_type = "single" # single, multipart, collection collection_info = None if len(video_files) > 1: # 检查是否为同一个视频的多个文件(不同格式/质量) unique_titles = set() unique_bvids = set() for file_info in video_files: # 从文件名中提取标题部分(去掉CID和扩展名) file_name = file_info["file_name"] # 移除文件扩展名 name_without_ext = os.path.splitext(file_name)[0] # 尝试移除CID部分(假设CID在文件名末尾) if f"_{cid}" in name_without_ext: title_part = name_without_ext.replace(f"_{cid}", "") else: title_part = name_without_ext unique_titles.add(title_part) # 尝试从文件名或目录名中提取BVID bv_match = re.search(r'BV[a-zA-Z0-9]+', file_name) if not bv_match: bv_match = re.search(r'BV[a-zA-Z0-9]+', dir_name) if bv_match: unique_bvids.add(bv_match.group()) if len(unique_titles) > 1 or len(unique_bvids) > 1: is_collection = True collection_type = "collection" # 真正的合集 # 尝试从目录名中提取合集信息 if "_collection" in dir_name: collection_title = dir_name.split("_collection")[0] elif "_multipart" in dir_name: collection_title = dir_name.split("_multipart")[0] collection_type = "multipart" else: collection_title = dir_name collection_info = { "type": collection_type, "title": collection_title, "total_videos": len(unique_titles) if len(unique_titles) > 1 else len(unique_bvids), "video_list": [] } # 构建合集中的视频列表 for file_info in video_files: file_name = file_info["file_name"] name_without_ext = os.path.splitext(file_name)[0] # 提取视频标题 if f"_{cid}" in name_without_ext: video_title = name_without_ext.replace(f"_{cid}", "") else: video_title = name_without_ext # 提取BVID bv_match = re.search(r'BV[a-zA-Z0-9]+', file_name) if not bv_match: bv_match = re.search(r'BV[a-zA-Z0-9]+', dir_name) video_bvid = bv_match.group() if bv_match else "" # 尝试为每个子视频获取独立的封面信息 video_cover = None video_author_face = None video_author_name = None video_author_mid = None # 查找对应的.nfo文件 nfo_file_path = os.path.join(root, f"{name_without_ext}.nfo") if os.path.exists(nfo_file_path): try: import xml.etree.ElementTree as ET tree = ET.parse(nfo_file_path) nfo_root = tree.getroot() # 提取封面 thumb_elem = nfo_root.find('thumb') if thumb_elem is not None and thumb_elem.text: video_cover = thumb_elem.text # 提取作者信息 actor_elem = nfo_root.find('actor') if actor_elem is not None: actor_name = actor_elem.find('name') if actor_name is not None and actor_name.text: video_author_name = actor_name.text actor_thumb = actor_elem.find('thumb') if actor_thumb is not None and actor_thumb.text: video_author_face = actor_thumb.text actor_profile = actor_elem.find('profile') if actor_profile is not None and actor_profile.text: profile_url = actor_profile.text mid_match = re.search(r"space\.bilibili\.com/(\d+)", profile_url) if mid_match: video_author_mid = int(mid_match.group(1)) # 处理图片URL if _process_image_url: if video_cover: video_cover = _process_image_url(video_cover, 'covers', use_local_images) if video_author_face: video_author_face = _process_image_url(video_author_face, 'avatars', use_local_images) elif use_local_images: import hashlib if video_cover: cover_hash = hashlib.md5(video_cover.encode()).hexdigest() video_cover = f"/images/local/covers/{cover_hash}" if video_author_face: avatar_hash = hashlib.md5(video_author_face.encode()).hexdigest() video_author_face = f"/images/local/avatars/{avatar_hash}" except Exception as e: print(f"解析子视频NFO文件时出错:{str(e)}") collection_info["video_list"].append({ "title": video_title, "bvid": video_bvid, "file_info": file_info, "cover": video_cover, "author_face": video_author_face, "author_name": video_author_name, "author_mid": video_author_mid }) else: collection_type = "multipart" # 多P或不同格式的同一视频 # 添加合集信息到video_info video_info["is_collection"] = is_collection video_info["collection_type"] = collection_type video_info["collection_info"] = collection_info videos.append(video_info) # 如果数据库连接已打开,关闭它 if conn: conn.close() # 计算分页 total_videos = len(videos) total_pages = (total_videos + limit - 1) // limit if total_videos > 0 else 0 # 根据修改时间排序,最新的在前面 videos.sort(key=lambda x: max([f["modified_time"] for f in x["files"]]) if x["files"] else 0, reverse=True) # 分页 start_idx = (page - 1) * limit end_idx = min(start_idx + limit, total_videos) paginated_videos = videos[start_idx:end_idx] if start_idx < total_videos else [] return { "status": "success", "message": f"找到{total_videos}个视频" + (f",匹配'{search_term}'" if search_term else ""), "videos": paginated_videos, "total": total_videos, "page": page, "limit": limit, "pages": total_pages } except Exception as e: return { "status": "error", "message": f"获取已下载视频列表时出错:{str(e)}" } @router.get("/stream_video", summary="获取已下载视频的流媒体数据") async def stream_video(file_path: str): """ 返回已下载视频的流媒体数据,用于在线播放 Args: file_path: 视频文件的完整路径 Returns: StreamingResponse: 视频流响应 """ try: # 检查文件是否存在 if not os.path.exists(file_path): raise HTTPException( status_code=404, detail=f"文件不存在:{file_path}" ) # 检查是否是支持的媒体文件 if not file_path.endswith(('.mp4', '.flv', '.m4a', '.mp3')): raise HTTPException( status_code=400, detail="不支持的媒体文件格式,仅支持 mp4、flv、m4a、mp3 格式" ) # 获取文件大小 file_size = os.path.getsize(file_path) # 获取文件名 file_name = os.path.basename(file_path) # 设置适当的媒体类型 if file_path.endswith('.mp4'): media_type = 'video/mp4' elif file_path.endswith('.flv'): media_type = 'video/x-flv' elif file_path.endswith('.m4a'): media_type = 'audio/mp4' elif file_path.endswith('.mp3'): media_type = 'audio/mpeg' else: media_type = 'application/octet-stream' # 返回文件响应 return FileResponse( file_path, media_type=media_type, filename=file_name ) except HTTPException: raise except Exception as e: raise HTTPException( status_code=500, detail=f"获取视频流时出错:{str(e)}" ) @router.delete("/delete_downloaded_video", summary="删除已下载的视频") async def delete_downloaded_video( delete_directory: bool = False, directory: Optional[str] = None, cid: Optional[int] = Query(None, description="视频的 CID,可选项") ): """ 删除已下载的视频文件 Args: delete_directory: 是否删除整个目录,默认为 False(只删除视频文件) directory: 可选,指定要删除文件的目录路径,如果提供则只在该目录中查找和删除文件 cid: 可选,视频的 CID Returns: dict: 包含删除结果信息的字典 """ try: # 获取下载目录路径 download_dir = os.path.normpath(config['yutto']['basic']['dir']) # 确保下载目录存在 if not os.path.exists(download_dir): return { "status": "error", "message": "下载目录不存在" } # 检查参数有效性 if not cid and not directory: return { "status": "error", "message": "必须提供 cid 或 directory 参数中的至少一个" } # 查找匹配 CID 的视频文件和目录 found_files = [] found_directory = directory # 如果提供了目录,则使用它 # 如果提供了 directory 参数,并且它确实存在,只在该目录中查找文件 if directory and os.path.exists(directory): # 根据 directory 直接处理 if delete_directory: # 删除整个目录 import shutil try: shutil.rmtree(directory) return { "status": "success", "message": f"已删除目录:{directory}", "deleted_directory": directory } except Exception as e: return { "status": "error", "message": f"删除目录时出错:{str(e)}", "directory": directory } else: # 查找目录中的视频文件并删除 for file in os.listdir(directory): # 仅查找视频或音频文件 if file.endswith(('.mp4', '.flv', '.m4a', '.mp3')): file_path = os.path.join(directory, file) if cid is None or f"_{cid}" in file: # 如果指定了 CID 则检查文件名是否包含它 found_files.append({ "file_name": file, "file_path": file_path }) elif cid is not None: # 如果没有提供 directory 参数但提供了 cid,执行原来的逻辑 for root, dirs, files in os.walk(download_dir): # 检查目录名是否包含 CID if f"_{cid}" in os.path.basename(root): # 如果没有指定目录,保存找到的第一个匹配目录 if not found_directory: found_directory = root # 检查目录中的文件 for file in files: # 检查文件名是否包含 CID if f"_{cid}" in file: # 检查是否为视频或音频文件 if file.endswith(('.mp4', '.flv', '.m4a', '.mp3')): file_path = os.path.join(root, file) found_files.append({ "file_name": file, "file_path": file_path }) if not found_files and not found_directory: error_message = "未找到匹配的视频文件" if cid is not None: error_message += f", CID: {cid}" if directory: error_message += f",目录:{directory}" return { "status": "error", "message": error_message } # 执行删除操作 deleted_files = [] if delete_directory and found_directory: # 删除整个目录 import shutil try: shutil.rmtree(found_directory) return { "status": "success", "message": f"已删除目录:{found_directory}", "deleted_directory": found_directory } except Exception as e: return { "status": "error", "message": f"删除目录时出错:{str(e)}", "directory": found_directory } else: # 只删除视频文件 for file_info in found_files: try: os.remove(file_info["file_path"]) deleted_files.append(file_info) except Exception as e: return { "status": "error", "message": f"删除文件时出错:{str(e)}", "file": file_info["file_path"] } return { "status": "success", "message": f"已删除{len(deleted_files)}个文件", "deleted_files": deleted_files, "directory": found_directory } except Exception as e: return { "status": "error", "message": f"删除视频文件时出错:{str(e)}" } @router.get("/stream_danmaku", summary="获取视频弹幕文件") async def stream_danmaku(file_path: Optional[str] = None, cid: Optional[int] = None): """ 返回视频弹幕文件 (.ass),用于前端播放时显示弹幕 Args: file_path: 视频文件的完整路径,会自动查找对应的 ass 文件 cid: 可选,如果提供 CID 而不是文件路径,将尝试查找对应 CID 的弹幕文件 Returns: FileResponse: 弹幕文件响应 """ try: if not file_path and not cid: raise HTTPException( status_code=400, detail="必须提供视频文件路径 (file_path) 或视频 CID(cid) 参数" ) danmaku_path = None # 1. 如果提供了文件路径,尝试查找对应的 ass 文件 if file_path: # 检查视频文件是否存在 if not os.path.exists(file_path): raise HTTPException( status_code=404, detail=f"视频文件不存在:{file_path}" ) # 尝试找到同名的.ass 文件 base_path = file_path.rsplit('.', 1)[0] # 移除扩展名 possible_ass_path = f"{base_path}.ass" if os.path.exists(possible_ass_path): danmaku_path = possible_ass_path else: # 尝试在同一目录下查找任何包含相同 CID 的.ass 文件 directory = os.path.dirname(file_path) file_name = os.path.basename(file_path) # 尝试从文件名提取 CID cid_match = None file_parts = file_name.split('_') if len(file_parts) > 1: try: # 尝试获取最后一部分中的 CID (去掉扩展名) last_part = file_parts[-1].split('.')[0] if last_part.isdigit(): cid_match = last_part except: pass if cid_match: # 在同一目录下查找包含相同 CID 的.ass 文件 for file in os.listdir(directory): if file.endswith('.ass') and cid_match in file: danmaku_path = os.path.join(directory, file) break # 2. 如果提供了 CID,在下载目录中查找对应的弹幕文件 elif cid: download_dir = os.path.normpath(config['yutto']['basic']['dir']) # 确保下载目录存在 if not os.path.exists(download_dir): raise HTTPException( status_code=404, detail="下载目录不存在" ) # 递归遍历下载目录查找匹配 CID 的弹幕文件 for root, dirs, files in os.walk(download_dir): # 检查目录名是否包含 CID if f"_{cid}" in os.path.basename(root): # 检查目录中的文件 for file in files: # 检查是否为弹幕文件 if file.endswith('.ass') and f"_{cid}" in file: danmaku_path = os.path.join(root, file) break # 如果在当前目录找到了弹幕文件,就不再继续查找 if danmaku_path: break # 检查是否找到弹幕文件 if not danmaku_path: raise HTTPException( status_code=404, detail=f"未找到匹配的弹幕文件" ) # 返回文件响应 return FileResponse( danmaku_path, media_type='text/plain', filename=os.path.basename(danmaku_path) ) except HTTPException: raise except Exception as e: raise HTTPException( status_code=500, detail=f"获取弹幕文件时出错:{str(e)}" ) @router.post("/download_user_videos", summary="下载用户全部投稿视频") async def download_user_videos(request: UserSpaceDownloadRequest): """ 下载指定用户的全部投稿视频 Args: request: 包含用户 ID 和可选 SESSDATA 的请求对象 """ try: # 检查下载目录和临时目录 download_dir, tmp_dir = check_download_directories() # 构建用户空间 URL user_space_url = f"https://space.bilibili.com/{request.user_id}/video" # 构建基本命令 command = [ user_space_url, '--batch', # 批量下载 '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{{username}}的全部投稿视频/{{title}}_{{download_date@%Y%m%d_%H%M%S}}/{{title}}', '--with-metadata' # 添加元数据文件保存 ] # 添加下载参数 command = add_download_params_to_command(command, request) print(f"执行下载命令:yutto {' '.join(command)}") async def event_stream(): async for chunk in run_yutto(command): yield chunk yield "event: close\ndata: close\n\n" return StreamingResponse(event_stream(), media_type="text/event-stream") except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"下载过程出错:{str(e)}") @router.post("/batch_download", summary="批量下载多个B站视频") async def batch_download(request: BatchDownloadRequest): """ 批量下载多个B站视频 Args: request: 包含多个视频信息和下载选项的请求对象 """ try: # 检查下载目录和临时目录 download_dir, tmp_dir = check_download_directories() # 准备批量下载 total_videos = len(request.videos) current_index = 0 # 创建一个异步生成器来处理批量下载 async def batch_download_generator(): nonlocal current_index # 发送初始信息 yield f"data: 开始批量下载,共 {total_videos} 个视频\n\n" for video in request.videos: current_index += 1 # 发送当前下载信息 yield f"data: 正在下载第 {current_index}/{total_videos} 个视频: {video.title or video.bvid}\n\n" # 构建视频 URL video_url = f"https://www.bilibili.com/video/{video.bvid}" # -------------------- 组装 yutto 参数 -------------------- argv = [ video_url, '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{{title}}_{{username}}_{{download_date@%Y%m%d_%H%M%S}}_{video.cid}/{{title}}_{video.cid}', '--with-metadata' # 保存元数据文件 ] # 注:add_download_params_to_command 内部会按需追加其它参数 argv = add_download_params_to_command(argv, request) # 打印调试信息 print("执行下载命令:yutto " + ' '.join(argv)) # -------------------- 执行下载 -------------------- try: # 进程内调用 yutto,并实时转发输出 async for line in run_yutto(argv): yield line # 发送当前视频下载完成信息 yield f"data: 第 {current_index}/{total_videos} 个视频下载完成: {video.title or video.bvid}\n\n" except Exception as e: error_msg = f"下载视频 {video.bvid} 时出错:{str(e)}" print(error_msg) yield f"data: ERROR: {error_msg}\n\n" # 发送批量下载完成信息 yield f"data: 批量下载完成,共 {total_videos} 个视频\n\n" yield "event: close\ndata: close\n\n" # 返回 SSE 响应 return StreamingResponse( batch_download_generator(), media_type="text/event-stream" ) except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"批量下载过程出错:{str(e)}") @router.post("/download_favorites", summary="下载用户收藏夹视频") async def download_favorites(request: FavoriteDownloadRequest): """ 下载用户的收藏夹视频 Args: request: 包含用户 ID、收藏夹 ID 和可选 SESSDATA 的请求对象 注意:不提供收藏夹 ID 时,将下载所有收藏夹 """ try: # 收藏夹必须登录 sessdata = request.sessdata or config.get('SESSDATA') if not sessdata: raise HTTPException( status_code=401, detail="未登录:下载收藏夹必须提供 SESSDATA" ) # 检查下载目录和临时目录 download_dir, tmp_dir = check_download_directories() # 构建收藏夹 URL if request.fid: # 指定收藏夹 favorite_url = f"https://space.bilibili.com/{request.user_id}/favlist?fid={request.fid}" else: # 所有收藏夹 favorite_url = f"https://space.bilibili.com/{request.user_id}/favlist" # 构建基本命令 command = [ favorite_url, '--batch', # 批量下载 '--dir', download_dir, '--tmp-dir', tmp_dir, '--subpath-template', f'{{username}}的收藏夹/{{title}}_{{download_date@%Y%m%d_%H%M%S}}/{{title}}', '--with-metadata' # 添加元数据文件保存 ] # 添加下载参数 command = add_download_params_to_command(command, request) # 确保添加 SESSDATA (收藏夹必须登录) if '--sessdata' not in command: command.extend(['--sessdata', sessdata]) print(f"执行下载命令:yutto {' '.join(command)}") async def event_stream(): async for chunk in run_yutto(command): yield chunk yield "event: close\ndata: close\n\n" return StreamingResponse(event_stream(), media_type="text/event-stream") except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"下载过程出错:{str(e)}") # 定义响应模型 class VideoInfo(BaseModel): path: str size: int title: str create_time: datetime cover: str = "" cid: str = "" bvid: str = "" author_name: str = "" author_face: str = "" author_mid: int = 0 class VideoSearchResponse(BaseModel): total: int videos: list[VideoInfo] # 视频详细信息响应模型 class VideoDetailResponse(BaseModel): status: str message: str data: Optional[dict] = None @router.get("/video_info", summary="获取 B 站视频详细信息") async def get_video_info(aid: Optional[int] = None, bvid: Optional[str] = None, sessdata: Optional[str] = None, headers: Optional[dict] = None, use_sessdata: bool = True): """ 获取B站视频详细信息 Args: aid: 视频aid bvid: 视频bvid sessdata: B站会话ID headers: 自定义请求头 use_sessdata: 是否使用SESSDATA认证,默认为True """ try: if not aid and not bvid: return VideoDetailResponse( status="error", message="至少需要提供aid或bvid参数", data=None ) # 配置请求信息 default_headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Referer': 'https://www.bilibili.com', } # 合并自定义请求头 if headers: default_headers.update(headers) # 仅在需要使用SESSDATA且提供了SESSDATA时,加入到请求头中 if sessdata and use_sessdata: default_headers['Cookie'] = f'SESSDATA={sessdata};' # 准备请求参数 params = {} if aid: params['aid'] = aid if bvid: params['bvid'] = bvid url = "https://api.bilibili.com/x/web-interface/view" # 使用httpx发送请求 async with httpx.AsyncClient() as client: response = await client.get(url, params=params, headers=default_headers, timeout=20.0) # 首先检查内容类型 content_type = response.headers.get('content-type', '') if 'application/json' not in content_type: return VideoDetailResponse( status="error", message=f"非JSON响应: {content_type},视频可能无法访问", data=None ) # 尝试多种解码方式 content = None for encoding in ['utf-8', 'gbk', 'gb2312', 'utf-16', 'latin1']: try: content = response.content.decode(encoding) break except UnicodeDecodeError: continue # 如果所有解码方式都失败,使用bytes的十六进制表示 if content is None: hex_content = response.content.hex() return VideoDetailResponse( status="error", message=f"无法解码响应内容,可能是非文本数据", data={"raw_hex": hex_content[:100] + "..."} ) # 尝试解析JSON try: response_json = json.loads(content) except json.JSONDecodeError: return VideoDetailResponse( status="error", message=f"无法解析JSON: {content[:200]}...", data=None ) # 检查是否API错误 code = response_json.get('code', 0) if code != 0: error_msg = response_json.get('message', '未知错误') # 特殊处理一些常见错误 if code == -404: error_msg = "视频不存在或已被删除" elif code == 62002: error_msg = "视频不可见(可能是私有或被删除)" return VideoDetailResponse( status="error", message=f"API错误 {code}: {error_msg}", data=response_json ) # 正常返回 return VideoDetailResponse( status="success", message="获取视频信息成功", data=response_json.get('data', {}) ) except httpx.RequestError as e: return VideoDetailResponse( status="error", message=f"请求错误: {str(e)}", data=None ) except Exception as e: return VideoDetailResponse( status="error", message=f"获取视频信息时出错:{str(e)}", data=None ) # 用户投稿视频查询参数模型 class UserVideosQueryParams(BaseModel): mid: int = Field(..., description="目标用户 mid") pn: int = Field(1, description="页码") ps: int = Field(30, description="每页项数") tid: int = Field(0, description="分区筛选,0:全部") keyword: str = Field("", description="关键词筛选") order: str = Field("pubdate", description="排序方式") platform: str = Field("web", description="平台标识") # 用户投稿视频响应模型 class UserVideosResponse(BaseModel): status: str message: str data: Optional[dict] = None @router.get("/user_videos", summary="查询用户投稿视频明细") async def get_user_videos( mid: int, pn: int = 1, ps: int = 30, tid: int = 0, keyword: str = "", order: str = "pubdate", sessdata: Optional[str] = None, use_sessdata: bool = True ): """ 查询用户投稿视频明细 Args: mid: 目标用户 mid pn: 页码,默认为 1 ps: 每页项数,默认为 30 tid: 分区 ID,默认为 0(全部) keyword: 关键词过滤,默认为空 order: 排序方式,默认为 pubdate(发布日期) 可选值:pubdate(发布日期)、click(播放量)、stow(收藏量) sessdata: 可选,用户的 SESSDATA,用于获取限制查看的视频 use_sessdata: 是否使用SESSDATA认证,默认为True Returns: 用户投稿视频列表 """ try: # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'application/json', 'Referer': f'https://space.bilibili.com/{mid}/video', 'Origin': 'https://space.bilibili.com' } # 仅在需要使用SESSDATA且提供了SESSDATA时,加入到请求头中 if sessdata and use_sessdata: headers['Cookie'] = f'SESSDATA={sessdata}' elif config.get('SESSDATA') and use_sessdata: headers['Cookie'] = f'SESSDATA={config["SESSDATA"]}' # 构建请求参数 params = { 'mid': mid, 'pn': pn, 'ps': ps, 'tid': tid, 'keyword': keyword, 'order': order, 'platform': 'web' } # 使用 WBI 签名 from scripts.wbi_sign import get_wbi_sign signed_params = get_wbi_sign(params) # 发送请求获取用户视频列表 response = requests.get( 'https://api.bilibili.com/x/space/wbi/arc/search', params=signed_params, headers=headers, timeout=10 ) # 显式设置响应编码 response.encoding = 'utf-8' # 打印响应状态和内容预览,便于调试 print(f"请求 URL: {response.url}") print(f"响应状态码:{response.status_code}") content_preview = response.text[:100] if len(response.text) > 100 else response.text print(f"响应内容预览:{content_preview}") # 解析响应 response_json = response.json() # 处理可能的错误 if response_json.get('code') != 0: return UserVideosResponse( status="error", message=f"获取用户投稿视频列表失败:{response_json.get('message', '未知错误')}", data=response_json ) # 返回成功响应 return UserVideosResponse( status="success", message="获取用户投稿视频列表成功", data=response_json.get('data') ) except Exception as e: import traceback error_trace = traceback.format_exc() print(f"获取用户投稿视频列表时出错:{str(e)}") print(f"错误堆栈:{error_trace}") return UserVideosResponse( status="error", message=f"获取用户投稿视频列表时出错:{str(e)}", data={"error_trace": error_trace} ) # 合集视频信息响应模型 class SeasonVideoInfo(BaseModel): title: str cover: str duration: int vv: int vt: int bvid: str aid: int cid: int class SeasonInfoResponse(BaseModel): status: str message: str season_id: Optional[int] = None season_title: Optional[str] = None season_cover: Optional[str] = None videos: Optional[List[SeasonVideoInfo]] = None @router.get("/video_season_info", summary="获取视频观看时长信息") async def get_video_season_info(bvid: str, sessdata: Optional[str] = None): """ 获取视频观看时长信息 检查视频是否为合集中的视频,并返回合集信息及其中所有视频的详细信息 Args: bvid: 视频bvid sessdata: B站会话ID,用于获取需要登录才能访问的视频 """ try: # 首先调用现有的获取视频详情接口 video_detail = await get_video_info(bvid=bvid, sessdata=sessdata) # 如果获取视频详情失败,直接返回错误 if video_detail.status != "success": return SeasonInfoResponse( status="error", message=f"获取视频信息失败: {video_detail.message}" ) # 检查视频是否属于某个合集 video_data = video_detail.data if not video_data.get("season_id"): return SeasonInfoResponse( status="info", message="该视频不属于任何合集" ) # 视频属于合集,获取合集信息 season_id = video_data.get("season_id") # 如果有ugc_season字段,从中提取合集信息 season_info = video_data.get("ugc_season", {}) if not season_info: return SeasonInfoResponse( status="error", message="无法获取合集信息", season_id=season_id ) # 提取合集标题和封面 season_title = season_info.get("title", "") season_cover = season_info.get("cover", "") # 提取合集中的所有视频信息 video_list = [] sections = season_info.get("sections", []) for section in sections: episodes = section.get("episodes", []) for episode in episodes: # 提取所需的视频信息 arc = episode.get("arc", {}) page = episode.get("page", {}) video_info = SeasonVideoInfo( title=episode.get("title", ""), cover=arc.get("pic", ""), duration=page.get("duration", 0), vv=arc.get("stat", {}).get("vv", 0), vt=arc.get("stat", {}).get("vt", 0), bvid=episode.get("bvid", ""), aid=arc.get("aid", 0), cid=page.get("cid", 0) ) video_list.append(video_info) return SeasonInfoResponse( status="success", message="获取合集视频信息成功", season_id=season_id, season_title=season_title, season_cover=season_cover, videos=video_list ) except Exception as e: return SeasonInfoResponse( status="error", message=f"获取视频观看时长信息时出错:{str(e)}" )
2929004360/ruoyi-sign
5,581
ruoyi-flowable/src/main/java/com/ruoyi/flowable/base/BaseMapperPlus.java
package com.ruoyi.flowable.base; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.toolkit.Db; import com.ruoyi.flowable.utils.BeanCopyUtils; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; /** * 自定义 Mapper 接口, 实现 自定义扩展 * * @param <M> mapper 泛型 * @param <T> table 泛型 * @param <V> vo 泛型 * @author fengcheng * @since 2021-05-13 */ @SuppressWarnings("unchecked") public interface BaseMapperPlus<M, T, V> extends BaseMapper<T> { Log log = LogFactory.getLog(BaseMapperPlus.class); default Class<V> currentVoClass() { return (Class<V>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 2); } default Class<T> currentModelClass() { return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 1); } default Class<M> currentMapperClass() { return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 0); } default List<T> selectList() { return this.selectList(new QueryWrapper<>()); } /** * 批量插入 */ default boolean insertBatch(Collection<T> entityList) { return Db.saveBatch(entityList); } /** * 批量更新 */ default boolean updateBatchById(Collection<T> entityList) { return Db.updateBatchById(entityList); } /** * 批量插入或更新 */ default boolean insertOrUpdateBatch(Collection<T> entityList) { return Db.saveOrUpdateBatch(entityList); } /** * 批量插入(包含限制条数) */ default boolean insertBatch(Collection<T> entityList, int batchSize) { return Db.saveBatch(entityList, batchSize); } /** * 批量更新(包含限制条数) */ default boolean updateBatchById(Collection<T> entityList, int batchSize) { return Db.updateBatchById(entityList, batchSize); } /** * 批量插入或更新(包含限制条数) */ default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) { return Db.saveOrUpdateBatch(entityList, batchSize); } /** * 插入或更新(包含限制条数) */ default boolean insertOrUpdate(T entity) { return Db.saveOrUpdate(entity); } default V selectVoById(Serializable id) { return selectVoById(id, this.currentVoClass()); } /** * 根据 ID 查询 */ default <C> C selectVoById(Serializable id, Class<C> voClass) { T obj = this.selectById(id); if (ObjectUtil.isNull(obj)) { return null; } return BeanCopyUtils.copy(obj, voClass); } default List<V> selectVoBatchIds(Collection<? extends Serializable> idList) { return selectVoBatchIds(idList, this.currentVoClass()); } /** * 查询(根据ID 批量查询) */ default <C> List<C> selectVoBatchIds(Collection<? extends Serializable> idList, Class<C> voClass) { List<T> list = this.selectBatchIds(idList); if (CollUtil.isEmpty(list)) { return CollUtil.newArrayList(); } return BeanCopyUtils.copyList(list, voClass); } default List<V> selectVoByMap(Map<String, Object> map) { return selectVoByMap(map, this.currentVoClass()); } /** * 查询(根据 columnMap 条件) */ default <C> List<C> selectVoByMap(Map<String, Object> map, Class<C> voClass) { List<T> list = this.selectByMap(map); if (CollUtil.isEmpty(list)) { return CollUtil.newArrayList(); } return BeanCopyUtils.copyList(list, voClass); } default V selectVoOne(Wrapper<T> wrapper) { return selectVoOne(wrapper, this.currentVoClass()); } /** * 根据 entity 条件,查询一条记录 */ default <C> C selectVoOne(Wrapper<T> wrapper, Class<C> voClass) { T obj = this.selectOne(wrapper); if (ObjectUtil.isNull(obj)) { return null; } return BeanCopyUtils.copy(obj, voClass); } default List<V> selectVoList(Wrapper<T> wrapper) { return selectVoList(wrapper, this.currentVoClass()); } /** * 根据 entity 条件,查询全部记录 */ default <C> List<C> selectVoList(Wrapper<T> wrapper, Class<C> voClass) { List<T> list = this.selectList(wrapper); if (CollUtil.isEmpty(list)) { return CollUtil.newArrayList(); } return BeanCopyUtils.copyList(list, voClass); } default <P extends IPage<V>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper) { return selectVoPage(page, wrapper, this.currentVoClass()); } /** * 分页查询VO */ default <C, P extends IPage<C>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper, Class<C> voClass) { IPage<T> pageData = this.selectPage(page, wrapper); IPage<C> voPage = new Page<>(pageData.getCurrent(), pageData.getSize(), pageData.getTotal()); if (CollUtil.isEmpty(pageData.getRecords())) { return (P) voPage; } voPage.setRecords(BeanCopyUtils.copyList(pageData.getRecords(), voClass)); return (P) voPage; } }
2929004360/ruoyi-sign
1,209
ruoyi-flowable/src/main/java/com/ruoyi/flowable/base/BaseEntity.java
package com.ruoyi.flowable.base; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Entity基类 * * @author fengcheng */ @Data public class BaseEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 搜索值 */ @JsonIgnore @TableField(exist = false) private String searchValue; /** * 创建者 */ @TableField(fill = FieldFill.INSERT) private String createBy; /** * 创建时间 */ @TableField(fill = FieldFill.INSERT) private Date createTime; /** * 更新者 */ @TableField(fill = FieldFill.INSERT_UPDATE) private String updateBy; /** * 更新时间 */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; /** * 请求参数 */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @TableField(exist = false) private Map<String, Object> params = new HashMap<>(); }
281677160/openwrt-package
24,195
luci-app-homeproxy/root/etc/homeproxy/scripts/firewall_post.ut
#!/usr/bin/utpl -S {%- import { readfile } from 'fs'; import { cursor } from 'uci'; import { isEmpty } from '/etc/homeproxy/scripts/homeproxy.uc'; const fw4 = require('fw4'); function array_to_nftarr(array) { if (type(array) !== 'array') return null; return `{ ${join(', ', uniq(array))} }`; } function resolve_ipv6(str) { if (isEmpty(str)) return null; let ipv6 = fw4.parse_subnet(str)?.[0]; if (!ipv6 || ipv6.family !== 6) return null; if (ipv6.bits > -1) return `${ipv6.addr}/${ipv6.bits}`; else return `& ${ipv6.mask} == ${ipv6.addr}`; } function resolve_mark(str) { if (isEmpty(str)) return null; let mark = fw4.parse_mark(str); if (isEmpty(mark)) return null; if (mark.mask === 0xffffffff) return fw4.hex(mark.mark); else if (mark.mark === 0) return `mark and ${fw4.hex(~mark.mask & 0xffffffff)}`; else if (mark.mark === mark.mask) return `mark or ${fw4.hex(mark.mark)}`; else if (mark.mask === 0) return `mark xor ${fw4.hex(mark.mark)}`; else return `mark and ${fw4.hex(~mark.mask & 0xffffffff)} xor ${fw4.hex(mark.mark)}`; } /* Misc config */ const resources_dir = '/etc/homeproxy/resources'; /* UCI config start */ const cfgname = 'homeproxy'; const uci = cursor(); uci.load(cfgname); const routing_mode = uci.get(cfgname, 'config', 'routing_mode') || 'bypass_mainland_china'; let outbound_node, outbound_udp_node, china_dns_server, bypass_cn_traffic; if (routing_mode !== 'custom') { outbound_node = uci.get(cfgname, 'config', 'main_node') || 'nil'; outbound_udp_node = uci.get(cfgname, 'config', 'main_udp_node') || 'nil'; china_dns_server = uci.get(cfgname, 'config', 'china_dns_server'); } else { outbound_node = uci.get(cfgname, 'routing', 'default_outbound') || 'nil'; bypass_cn_traffic = uci.get(cfgname, 'routing', 'bypass_cn_traffic') || '0'; } let routing_port = uci.get(cfgname, 'config', 'routing_port'); if (routing_port === 'common') routing_port = uci.get(cfgname, 'infra', 'common_port') || '22,53,80,143,443,465,587,853,873,993,995,8080,8443,9418'; const proxy_mode = uci.get(cfgname, 'config', 'proxy_mode') || 'redirect_tproxy', ipv6_support = uci.get(cfgname, 'config', 'ipv6_support') || '0'; let self_mark, redirect_port, tproxy_port, tproxy_mark, tun_name, tun_mark; if (match(proxy_mode, /redirect/)) { self_mark = uci.get(cfgname, 'infra', 'self_mark') || '100'; redirect_port = uci.get(cfgname, 'infra', 'redirect_port') || '5331'; } if (match(proxy_mode, /tproxy/)) if (outbound_udp_node !== 'nil' || routing_mode === 'custom') { tproxy_port = uci.get(cfgname, 'infra', 'tproxy_port') || '5332'; tproxy_mark = resolve_mark(uci.get(cfgname, 'infra', 'tproxy_mark') || '101'); } if (match(proxy_mode, /tun/)) { tun_name = uci.get(cfgname, 'infra', 'tun_name') || 'singtun0'; tun_mark = resolve_mark(uci.get(cfgname, 'infra', 'tun_mark') || '102'); } const control_options = [ "listen_interfaces", "lan_proxy_mode", "lan_direct_mac_addrs", "lan_direct_ipv4_ips", "lan_direct_ipv6_ips", "lan_proxy_mac_addrs", "lan_proxy_ipv4_ips", "lan_proxy_ipv6_ips", "lan_gaming_mode_mac_addrs", "lan_gaming_mode_ipv4_ips", "lan_gaming_mode_ipv6_ips", "lan_global_proxy_mac_addrs", "lan_global_proxy_ipv4_ips", "lan_global_proxy_ipv6_ips", "wan_proxy_ipv4_ips", "wan_proxy_ipv6_ips", "wan_direct_ipv4_ips", "wan_direct_ipv6_ips" ]; const control_info = {}; for (let i in control_options) control_info[i] = uci.get(cfgname, 'control', i); const dns_hijacked = uci.get('dhcp', '@dnsmasq[0]', 'dns_redirect') || '0', dns_port = uci.get('dhcp', '@dnsmasq[0]', 'port') || '53'; /* UCI config end */ -%} {# Reserved addresses -#} set homeproxy_local_addr_v4 { type ipv4_addr flags interval auto-merge elements = { 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16, 172.16.0.0/12, 192.0.0.0/24, 192.0.2.0/24, 192.31.196.0/24, 192.52.193.0/24, 192.88.99.0/24, 192.168.0.0/16, 192.175.48.0/24, 198.18.0.0/15, 198.51.100.0/24, 203.0.113.0/24, 224.0.0.0/4, 240.0.0.0/4 } } {% if (ipv6_support === '1'): %} set homeproxy_local_addr_v6 { type ipv6_addr flags interval auto-merge elements = { ::/128, ::1/128, ::ffff:0:0/96, 100::/64, 64:ff9b::/96, 2001::/32, 2001:10::/28, 2001:20::/28, 2001:db8::/28, 2002::/16, fc00::/7, fe80::/10, ff00::/8 } } {% endif %} {% if (routing_mode === 'gfwlist'): %} set homeproxy_gfw_list_v4 { type ipv4_addr flags interval auto-merge } {% if (ipv6_support === '1'): %} set homeproxy_gfw_list_v6 { type ipv6_addr flags interval auto-merge } {% endif /* ipv6_support */ %} {% elif (match(routing_mode, /mainland_china/) || bypass_cn_traffic === '1'): %} set homeproxy_mainland_addr_v4 { type ipv4_addr flags interval auto-merge elements = { {% for (let cnip4 in split(trim(readfile(resources_dir + '/china_ip4.txt')), /[\r\n]/)): %} {{ cnip4 }}, {% endfor %} } } {% if ((ipv6_support === '1') || china_dns_server): %} set homeproxy_mainland_addr_v6 { type ipv6_addr flags interval auto-merge elements = { {% for (let cnip6 in split(trim(readfile(resources_dir + '/china_ip6.txt')), /[\r\n]/)): %} {{ cnip6 }}, {% endfor %} } } {% endif /* ipv6_support */ %} {% endif /* routing_mode */ %} {# WAN ACL addresses #} set homeproxy_wan_proxy_addr_v4 { type ipv4_addr flags interval auto-merge {% if (control_info.wan_proxy_ipv4_ips): %} elements = { {{ join(', ', control_info.wan_proxy_ipv4_ips) }} } {% endif %} } {% if (ipv6_support === '1'): %} set homeproxy_wan_proxy_addr_v6 { type ipv6_addr flags interval auto-merge {% if (control_info.wan_proxy_ipv6_ips): %} elements = { {{ join(', ', control_info.wan_proxy_ipv6_ips) }} } {% endif /* wan_proxy_ipv6_ips*/ %} } {% endif /* ipv6_support */ %} set homeproxy_wan_direct_addr_v4 { type ipv4_addr flags interval auto-merge {% if (control_info.wan_direct_ipv4_ips): %} elements = { {{ join(', ', control_info.wan_direct_ipv4_ips) }} } {% endif %} } {% if (ipv6_support === '1'): %} set homeproxy_wan_direct_addr_v6 { type ipv6_addr flags interval auto-merge {% if (control_info.wan_direct_ipv6_ips): %} elements = { {{ join(', ', control_info.wan_direct_ipv6_ips) }} } {% endif /* wan_direct_ipv6_ips */ %} } {% endif /* ipv6_support */ %} {% if (routing_port): %} set homeproxy_routing_port { type inet_service flags interval auto-merge elements = { {{ join(', ', split(routing_port, ',')) }} } } {% endif %} {# DNS hijack & TCP redirect #} chain dstnat { {% if (dns_hijacked !== '1'): %} {% if (control_info.listen_interfaces): %} meta iifname {{ array_to_nftarr(control_info.listen_interfaces) }} {%- endif /* listen_interfaces */ %} meta nfproto { ipv4, ipv6 } udp dport 53 counter redirect to :{{ dns_port }} comment "!{{ cfgname }}: DNS hijack" {% endif /* dns_hijacked */ %} {% if (match(proxy_mode, /redirect/)): %} meta nfproto { {{ (ipv6_support === '1') ? 'ipv4, ipv6' : 'ipv4' }} } meta l4proto tcp jump homeproxy_redirect_lanac {% endif /* proxy_mode */ %} } {# TCP redirect #} {% if (match(proxy_mode, /redirect/)): %} chain homeproxy_redirect_proxy { meta l4proto tcp counter redirect to :{{ redirect_port }} } chain homeproxy_redirect_proxy_port { {% if (routing_port): %} tcp dport != @homeproxy_routing_port counter return {% endif %} goto homeproxy_redirect_proxy } chain homeproxy_redirect_lanac { {% if (control_info.listen_interfaces): %} meta iifname != {{ array_to_nftarr(control_info.listen_interfaces) }} counter return {% endif %} meta mark {{ self_mark }} counter return {% if (control_info.lan_proxy_mode === 'listed_only'): %} {% if (!isEmpty(control_info.lan_proxy_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_proxy_ipv4_ips) }} counter goto homeproxy_redirect {% endif /* lan_proxy_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_proxy_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_redirect {% endfor /* lan_proxy_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_proxy_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_proxy_mac_addrs) }} counter goto homeproxy_redirect {% endif /* lan_proxy_mac_addrs */ %} {% elif (control_info.lan_proxy_mode === 'except_listed'): %} {% if (!isEmpty(control_info.lan_direct_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_direct_ipv4_ips) }} counter return {% endif /* lan_direct_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_direct_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter return {% endfor /* lan_direct_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_direct_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_direct_mac_addrs) }} counter return {% endif /* lan_direct_mac_addrs */ %} {% endif /* lan_proxy_mode */ %} {% if (control_info.lan_proxy_mode !== 'listed_only'): %} counter goto homeproxy_redirect {% endif %} } chain homeproxy_redirect { meta mark {{ self_mark }} counter return ip daddr @homeproxy_wan_proxy_addr_v4 counter goto homeproxy_redirect_proxy_port {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_proxy_addr_v6 counter goto homeproxy_redirect_proxy_port {% endif %} ip daddr @homeproxy_local_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_local_addr_v6 counter return {% endif %} {% if (routing_mode !== 'custom'): %} {% if (!isEmpty(control_info.lan_global_proxy_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_global_proxy_ipv4_ips) }} counter goto homeproxy_redirect_proxy_port {% endif /* lan_global_proxy_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_global_proxy_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_redirect_proxy_port {% endfor /* lan_global_proxy_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_global_proxy_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_global_proxy_mac_addrs) }} counter goto homeproxy_redirect_proxy_port {% endif /* lan_global_proxy_mac_addrs */ %} {% endif /* routing_mode */ %} ip daddr @homeproxy_wan_direct_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_direct_addr_v6 counter return {% endif /* ipv6_support */ %} {% if (routing_mode === 'gfwlist'): %} ip daddr != @homeproxy_gfw_list_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_gfw_list_v6 counter return {% endif /* ipv6_support */ %} {% elif (routing_mode === 'bypass_mainland_china' || bypass_cn_traffic === '1'): %} ip daddr @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% elif (routing_mode === 'proxy_mainland_china'): %} ip daddr != @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% endif /* routing_mode */ %} {% if (!isEmpty(control_info.lan_gaming_mode_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_gaming_mode_ipv4_ips) }} counter goto homeproxy_redirect_proxy {% endif /* lan_gaming_mode_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_gaming_mode_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_redirect_proxy {% endfor /* lan_gaming_mode_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_gaming_mode_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_gaming_mode_mac_addrs) }} counter goto homeproxy_redirect_proxy {% endif /* lan_gaming_mode_mac_addrs */ %} counter goto homeproxy_redirect_proxy_port } chain homeproxy_output_redir { type nat hook output priority filter -105; policy accept meta nfproto { {{ (ipv6_support === '1') ? 'ipv4, ipv6' : 'ipv4' }} } meta l4proto tcp jump homeproxy_redirect } {% endif %} {# UDP tproxy #} {% if (match(proxy_mode, /tproxy/) && (outbound_udp_node !== 'nil' || routing_mode === 'custom')): %} chain homeproxy_mangle_tproxy { meta l4proto udp meta mark set {{ tproxy_mark }} tproxy ip to 127.0.0.1:{{ tproxy_port }} counter accept {% if (ipv6_support === '1'): %} meta l4proto udp meta mark set {{ tproxy_mark }} tproxy ip6 to [::1]:{{ tproxy_port }} counter accept {% endif %} } chain homeproxy_mangle_tproxy_port { {% if (routing_port): %} udp dport != @homeproxy_routing_port counter return {% endif %} goto homeproxy_mangle_tproxy } chain homeproxy_mangle_mark { {% if (routing_port): %} udp dport != @homeproxy_routing_port counter return {% endif %} meta l4proto udp meta mark set {{ tproxy_mark }} counter accept } chain homeproxy_mangle_lanac { {% if (control_info.listen_interfaces): %} meta iifname != {{ array_to_nftarr(uniq([...control_info.listen_interfaces, ...['lo']])) }} counter return {% endif %} meta iifname != lo udp dport 53 counter return meta mark {{ self_mark }} counter return {% if (control_info.lan_proxy_mode === 'listed_only'): %} {% if (!isEmpty(control_info.lan_proxy_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_proxy_ipv4_ips) }} counter goto homeproxy_mangle_prerouting {% endif /* lan_proxy_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_proxy_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_mangle_prerouting {% endfor /* lan_proxy_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_proxy_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_proxy_mac_addrs) }} counter goto homeproxy_mangle_prerouting {% endif /* lan_proxy_mac_addrs */ %} {% elif (control_info.lan_proxy_mode === 'except_listed'): %} {% if (!isEmpty(control_info.lan_direct_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_direct_ipv4_ips) }} counter return {% endif /* lan_direct_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_direct_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter return {% endfor /* lan_direct_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_direct_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_direct_mac_addrs) }} counter return {% endif /* lan_direct_mac_addrs */ %} {% endif /* lan_proxy_mode */ %} {% if (control_info.lan_proxy_mode !== 'listed_only'): %} counter goto homeproxy_mangle_prerouting {% endif %} } chain homeproxy_mangle_prerouting { ip daddr @homeproxy_wan_proxy_addr_v4 counter goto homeproxy_mangle_tproxy_port {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_proxy_addr_v6 counter goto homeproxy_mangle_tproxy_port {% endif %} ip daddr @homeproxy_local_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_local_addr_v6 counter return {% endif %} {% if (routing_mode !== 'custom'): %} {% if (!isEmpty(control_info.lan_global_proxy_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_global_proxy_ipv4_ips) }} counter goto homeproxy_mangle_tproxy_port {% endif /* lan_global_proxy_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_global_proxy_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_mangle_tproxy_port {% endfor /* lan_global_proxy_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_global_proxy_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_global_proxy_mac_addrs) }} counter goto homeproxy_mangle_tproxy_port {% endif /* lan_global_proxy_mac_addrs */ %} {% endif /* routing_mode */ %} ip daddr @homeproxy_wan_direct_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_direct_addr_v6 counter return {% endif /* ipv6_support */ %} {% if (routing_mode === 'gfwlist'): %} ip daddr != @homeproxy_gfw_list_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_gfw_list_v6 counter return {% endif /* ipv6_support */ %} udp dport { 80, 443 } counter reject comment "!{{ cfgname }}: Fuck you QUIC" {% elif (routing_mode === 'bypass_mainland_china' || bypass_cn_traffic === '1'): %} ip daddr @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% if (routing_mode !== 'custom'): %} udp dport { 80, 443 } counter reject comment "!{{ cfgname }}: Fuck you QUIC" {% endif /* routing_mode */ %} {% elif (routing_mode === 'proxy_mainland_china'): %} ip daddr != @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% endif /* routing_mode */ %} {% if (!isEmpty(control_info.lan_gaming_mode_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_gaming_mode_ipv4_ips) }} counter goto homeproxy_mangle_tproxy {% endif /* lan_gaming_mode_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_gaming_mode_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_mangle_tproxy {% endfor /* lan_gaming_mode_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_gaming_mode_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_gaming_mode_mac_addrs) }} counter goto homeproxy_mangle_tproxy {% endif /* lan_gaming_mode_mac_addrs */ %} counter goto homeproxy_mangle_tproxy_port } chain homeproxy_mangle_output { meta mark {{ self_mark }} counter return ip daddr @homeproxy_wan_proxy_addr_v4 counter goto homeproxy_mangle_mark {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_proxy_addr_v6 counter goto homeproxy_mangle_mark {% endif %} ip daddr @homeproxy_local_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_local_addr_v6 counter return {% endif %} ip daddr @homeproxy_wan_direct_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_direct_addr_v6 counter return {% endif /* ipv6_support */ %} {% if (routing_mode === 'gfwlist'): %} ip daddr != @homeproxy_gfw_list_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_gfw_list_v6 counter return {% endif /* ipv6_support */ %} {% elif (routing_mode === 'bypass_mainland_china' || bypass_cn_traffic === '1'): %} ip daddr @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% elif (routing_mode === 'proxy_mainland_china'): %} ip daddr != @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% endif /* routing_mode */ %} counter goto homeproxy_mangle_mark } chain mangle_prerouting { meta nfproto { {{ (ipv6_support === '1') ? 'ipv4, ipv6' : 'ipv4' }} } meta l4proto udp jump homeproxy_mangle_lanac } chain mangle_output { meta nfproto { {{ (ipv6_support === '1') ? 'ipv4, ipv6' : 'ipv4' }} } meta l4proto udp jump homeproxy_mangle_output } {% endif %} {# TUN #} {% if (match(proxy_mode, /tun/)): %} chain homeproxy_mangle_lanac { iifname {{ tun_name }} counter return udp dport 53 counter return {% if (control_info.listen_interfaces): %} meta iifname != {{ array_to_nftarr(control_info.listen_interfaces) }} counter return {% endif %} {% if (control_info.lan_proxy_mode === 'listed_only'): %} {% if (!isEmpty(control_info.lan_proxy_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_proxy_ipv4_ips) }} counter goto homeproxy_mangle_tun {% endif /* lan_proxy_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_proxy_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_mangle_tun {% endfor /* lan_proxy_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_proxy_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_proxy_mac_addrs) }} counter goto homeproxy_mangle_tun {% endif /* lan_proxy_mac_addrs */ %} {% elif (control_info.lan_proxy_mode === 'except_listed'): %} {% if (!isEmpty(control_info.lan_direct_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_direct_ipv4_ips) }} counter return {% endif /* lan_direct_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_direct_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter return {% endfor /* lan_direct_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_direct_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_direct_mac_addrs) }} counter return {% endif /* lan_direct_mac_addrs */ %} {% endif /* lan_proxy_mode */ %} {% if (control_info.lan_proxy_mode !== 'listed_only'): %} counter goto homeproxy_mangle_tun {% endif %} } chain homeproxy_mangle_tun_mark { {% if (routing_port): %} {% if (proxy_mode === 'tun'): %} tcp dport != @homeproxy_routing_port counter return {% endif /* proxy_mode */ %} udp dport != @homeproxy_routing_port counter return {% endif /* routing_port */ %} counter meta mark set {{ tun_mark }} } chain homeproxy_mangle_tun { iifname {{ tun_name }} counter return ip daddr @homeproxy_wan_proxy_addr_v4 counter goto homeproxy_mangle_tun_mark {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_wan_proxy_addr_v6 counter goto homeproxy_mangle_tun_mark {% endif %} ip daddr @homeproxy_local_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_local_addr_v6 counter return {% endif %} {% if (routing_mode !== 'custom'): %} {% if (!isEmpty(control_info.lan_global_proxy_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_global_proxy_ipv4_ips) }} counter goto homeproxy_mangle_tun_mark {% endif /* lan_global_proxy_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_global_proxy_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter goto homeproxy_mangle_tun_mark {% endfor /* lan_global_proxy_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_global_proxy_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_global_proxy_mac_addrs) }} counter goto homeproxy_mangle_tun_mark {% endif /* lan_global_proxy_mac_addrs */ %} {% endif /* routing_mode */ %} {% if (control_info.wan_direct_ipv4_ips): %} ip daddr {{ array_to_nftarr(control_info.wan_direct_ipv4_ips) }} counter return {% endif /* wan_direct_ipv4_ips */ %} {% if (control_info.wan_direct_ipv6_ips): %} ip6 daddr {{ array_to_nftarr(control_info.wan_direct_ipv6_ips) }} counter return {% endif /* wan_direct_ipv6_ips */ %} {% if (routing_mode === 'gfwlist'): %} ip daddr != @homeproxy_gfw_list_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_gfw_list_v6 counter return {% endif /* ipv6_support */ %} udp dport { 80, 443 } counter reject comment "!{{ cfgname }}: Fuck you QUIC" {% elif (routing_mode === 'bypass_mainland_china' || bypass_cn_traffic === '1'): %} ip daddr @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% if (routing_mode !== 'custom'): %} udp dport { 80, 443 } counter reject comment "!{{ cfgname }}: Fuck you QUIC" {% endif /* routing_mode */ %} {% elif (routing_mode === 'proxy_mainland_china'): %} ip daddr != @homeproxy_mainland_addr_v4 counter return {% if (ipv6_support === '1'): %} ip6 daddr != @homeproxy_mainland_addr_v6 counter return {% endif /* ipv6_support */ %} {% endif /* routing_mode */ %} {% if (!isEmpty(control_info.lan_gaming_mode_ipv4_ips)): %} ip saddr {{ array_to_nftarr(control_info.lan_gaming_mode_ipv4_ips) }} counter meta mark set {{ tun_mark }} {% endif /* lan_gaming_mode_ipv4_ips */ %} {% for (let ipv6 in control_info.lan_gaming_mode_ipv6_ips): %} ip6 saddr {{ resolve_ipv6(ipv6) }} counter meta mark set {{ tun_mark }} {% endfor /* lan_gaming_mode_ipv6_ips */ %} {% if (!isEmpty(control_info.lan_gaming_mode_mac_addrs)): %} ether saddr {{ array_to_nftarr(control_info.lan_gaming_mode_mac_addrs) }} counter meta mark set {{ tun_mark }} {% endif /* lan_gaming_mode_mac_addrs */ %} counter goto homeproxy_mangle_tun_mark } chain mangle_prerouting { meta nfproto { {{ (ipv6_support === '1') ? 'ipv4, ipv6' : 'ipv4' }} } meta l4proto { {{ (proxy_mode === 'tun') ? 'tcp, udp' : 'udp' }} } jump homeproxy_mangle_lanac } chain mangle_output { meta nfproto { {{ (ipv6_support === '1') ? 'ipv4, ipv6' : 'ipv4' }} } meta l4proto { {{ (proxy_mode === 'tun') ? 'tcp, udp' : 'udp' }} } jump homeproxy_mangle_tun } {% endif %}
2841952537/cqooc_class
10,214
高等教育平台_Chrome.py
import time import re from DrissionPage import ChromiumPage from DrissionPage import ChromiumOptions from tqdm import tqdm def run_word(): # 阅读文档 - 60秒 for i in tqdm(range(60), mininterval=0.5): time.sleep(1) # time.sleep(60) def run_video(right_box): # 处理开始播放时间 结束播放时间 strat_time = re.findall('(.*):(.*)', right_box.ele('x:.//span[@class="dplayer-ptime"]').text) strat_time = int(strat_time[0][0]) * 60 + int(strat_time[0][1]) end_time = re.findall('(.*):(.*)', right_box.ele('x:.//span[@class="dplayer-dtime"]').text) end_time = int(end_time[0][0]) * 60 + int(end_time[0][1]) # 播放视频秒数 video_time = end_time - strat_time # 点击静音 right_box.ele('x:.//button[@class="dplayer-icon dplayer-volume-icon"]').click() # 点击播放按钮 right_box.ele('x:.//button[@class="dplayer-icon dplayer-play-icon"]').click() # 等待播放时间 for i in tqdm(range(video_time), mininterval=0.5): time.sleep(1) # time.sleep(video_time + 3) def run(): # 直接获取右边ele # 判断类型: 课件 or 视频 right_box = page.ele('x:.//div[@class="video-box"]') is_word = right_box.ele('x:./div[@class="ifrema"]') # 是课件 if is_word: print('识别到课件:等待60秒') time.sleep(0.5) run_word() else: print('识别到视频:点击播放') run_video(right_box) # 获取详细信息 def get_detail_info(x_chapters): detaill_infos = x_chapters.eles('x:.//div[@class="second-level-inner-box"]/div') for detaill_info in detaill_infos: # 判断完成状态 status_s = detaill_info.ele('x:.//div[@class="complate-icon"]//img', timeout=0.2) if not status_s: titile = detaill_info.ele('x:.//p[@class="title"]').text print('>', titile, ' 未定义') # 判断状态是否为 未完成 or 完成了一半 elif status_s.link == 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGPC/xhBQAACklpQ0NQc1JHQiBJRUM2MTk2Ni0yLjEAAEiJnVN3WJP3Fj7f92UPVkLY8LGXbIEAIiOsCMgQWaIQkgBhhBASQMWFiApWFBURnEhVxILVCkidiOKgKLhnQYqIWotVXDjuH9yntX167+3t+9f7vOec5/zOec8PgBESJpHmomoAOVKFPDrYH49PSMTJvYACFUjgBCAQ5svCZwXFAADwA3l4fnSwP/wBr28AAgBw1S4kEsfh/4O6UCZXACCRAOAiEucLAZBSAMguVMgUAMgYALBTs2QKAJQAAGx5fEIiAKoNAOz0ST4FANipk9wXANiiHKkIAI0BAJkoRyQCQLsAYFWBUiwCwMIAoKxAIi4EwK4BgFm2MkcCgL0FAHaOWJAPQGAAgJlCLMwAIDgCAEMeE80DIEwDoDDSv+CpX3CFuEgBAMDLlc2XS9IzFLiV0Bp38vDg4iHiwmyxQmEXKRBmCeQinJebIxNI5wNMzgwAABr50cH+OD+Q5+bk4eZm52zv9MWi/mvwbyI+IfHf/ryMAgQAEE7P79pf5eXWA3DHAbB1v2upWwDaVgBo3/ldM9sJoFoK0Hr5i3k4/EAenqFQyDwdHAoLC+0lYqG9MOOLPv8z4W/gi372/EAe/tt68ABxmkCZrcCjg/1xYW52rlKO58sEQjFu9+cj/seFf/2OKdHiNLFcLBWK8ViJuFAiTcd5uVKRRCHJleIS6X8y8R+W/QmTdw0ArIZPwE62B7XLbMB+7gECiw5Y0nYAQH7zLYwaC5EAEGc0Mnn3AACTv/mPQCsBAM2XpOMAALzoGFyolBdMxggAAESggSqwQQcMwRSswA6cwR28wBcCYQZEQAwkwDwQQgbkgBwKoRiWQRlUwDrYBLWwAxqgEZrhELTBMTgN5+ASXIHrcBcGYBiewhi8hgkEQcgIE2EhOogRYo7YIs4IF5mOBCJhSDSSgKQg6YgUUSLFyHKkAqlCapFdSCPyLXIUOY1cQPqQ28ggMor8irxHMZSBslED1AJ1QLmoHxqKxqBz0XQ0D12AlqJr0Rq0Hj2AtqKn0UvodXQAfYqOY4DRMQ5mjNlhXIyHRWCJWBomxxZj5Vg1Vo81Yx1YN3YVG8CeYe8IJAKLgBPsCF6EEMJsgpCQR1hMWEOoJewjtBK6CFcJg4Qxwicik6hPtCV6EvnEeGI6sZBYRqwm7iEeIZ4lXicOE1+TSCQOyZLkTgohJZAySQtJa0jbSC2kU6Q+0hBpnEwm65Btyd7kCLKArCCXkbeQD5BPkvvJw+S3FDrFiOJMCaIkUqSUEko1ZT/lBKWfMkKZoKpRzame1AiqiDqfWkltoHZQL1OHqRM0dZolzZsWQ8ukLaPV0JppZ2n3aC/pdLoJ3YMeRZfQl9Jr6Afp5+mD9HcMDYYNg8dIYigZaxl7GacYtxkvmUymBdOXmchUMNcyG5lnmA+Yb1VYKvYqfBWRyhKVOpVWlX6V56pUVXNVP9V5qgtUq1UPq15WfaZGVbNQ46kJ1Bar1akdVbupNq7OUndSj1DPUV+jvl/9gvpjDbKGhUaghkijVGO3xhmNIRbGMmXxWELWclYD6yxrmE1iW7L57Ex2Bfsbdi97TFNDc6pmrGaRZp3mcc0BDsax4PA52ZxKziHODc57LQMtPy2x1mqtZq1+rTfaetq+2mLtcu0W7eva73VwnUCdLJ31Om0693UJuja6UbqFutt1z+o+02PreekJ9cr1Dund0Uf1bfSj9Rfq79bv0R83MDQINpAZbDE4Y/DMkGPoa5hpuNHwhOGoEctoupHEaKPRSaMnuCbuh2fjNXgXPmasbxxirDTeZdxrPGFiaTLbpMSkxeS+Kc2Ua5pmutG003TMzMgs3KzYrMnsjjnVnGueYb7ZvNv8jYWlRZzFSos2i8eW2pZ8ywWWTZb3rJhWPlZ5VvVW16xJ1lzrLOtt1ldsUBtXmwybOpvLtqitm63Edptt3xTiFI8p0in1U27aMez87ArsmuwG7Tn2YfYl9m32zx3MHBId1jt0O3xydHXMdmxwvOuk4TTDqcSpw+lXZxtnoXOd8zUXpkuQyxKXdpcXU22niqdun3rLleUa7rrStdP1o5u7m9yt2W3U3cw9xX2r+00umxvJXcM970H08PdY4nHM452nm6fC85DnL152Xlle+70eT7OcJp7WMG3I28Rb4L3Le2A6Pj1l+s7pAz7GPgKfep+Hvqa+It89viN+1n6Zfgf8nvs7+sv9j/i/4XnyFvFOBWABwQHlAb2BGoGzA2sDHwSZBKUHNQWNBbsGLww+FUIMCQ1ZH3KTb8AX8hv5YzPcZyya0RXKCJ0VWhv6MMwmTB7WEY6GzwjfEH5vpvlM6cy2CIjgR2yIuB9pGZkX+X0UKSoyqi7qUbRTdHF09yzWrORZ+2e9jvGPqYy5O9tqtnJ2Z6xqbFJsY+ybuIC4qriBeIf4RfGXEnQTJAntieTE2MQ9ieNzAudsmjOc5JpUlnRjruXcorkX5unOy553PFk1WZB8OIWYEpeyP+WDIEJQLxhP5aduTR0T8oSbhU9FvqKNolGxt7hKPJLmnVaV9jjdO31D+miGT0Z1xjMJT1IreZEZkrkj801WRNberM/ZcdktOZSclJyjUg1plrQr1zC3KLdPZisrkw3keeZtyhuTh8r35CP5c/PbFWyFTNGjtFKuUA4WTC+oK3hbGFt4uEi9SFrUM99m/ur5IwuCFny9kLBQuLCz2Lh4WfHgIr9FuxYji1MXdy4xXVK6ZHhp8NJ9y2jLspb9UOJYUlXyannc8o5Sg9KlpUMrglc0lamUycturvRauWMVYZVkVe9ql9VbVn8qF5VfrHCsqK74sEa45uJXTl/VfPV5bdra3kq3yu3rSOuk626s91m/r0q9akHV0IbwDa0b8Y3lG19tSt50oXpq9Y7NtM3KzQM1YTXtW8y2rNvyoTaj9nqdf13LVv2tq7e+2Sba1r/dd3vzDoMdFTve75TsvLUreFdrvUV99W7S7oLdjxpiG7q/5n7duEd3T8Wej3ulewf2Re/ranRvbNyvv7+yCW1SNo0eSDpw5ZuAb9qb7Zp3tXBaKg7CQeXBJ9+mfHvjUOihzsPcw83fmX+39QjrSHkr0jq/dawto22gPaG97+iMo50dXh1Hvrf/fu8x42N1xzWPV56gnSg98fnkgpPjp2Snnp1OPz3Umdx590z8mWtdUV29Z0PPnj8XdO5Mt1/3yfPe549d8Lxw9CL3Ytslt0utPa49R35w/eFIr1tv62X3y+1XPK509E3rO9Hv03/6asDVc9f41y5dn3m978bsG7duJt0cuCW69fh29u0XdwruTNxdeo94r/y+2v3qB/oP6n+0/rFlwG3g+GDAYM/DWQ/vDgmHnv6U/9OH4dJHzEfVI0YjjY+dHx8bDRq98mTOk+GnsqcTz8p+Vv9563Or59/94vtLz1j82PAL+YvPv655qfNy76uprzrHI8cfvM55PfGm/K3O233vuO+638e9H5ko/ED+UPPR+mPHp9BP9z7nfP78L/eE8/stRzjPAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAJcEhZcwAACxMAAAsTAQCanBgAAADXSURBVBiVjZA7agJRAEXPewHRZViMC5AYZGxN5Sc7mPRJESJoO2JjYdDO2YidWEgI5qMbkIC7mFFHvTYTCBohp7yc5h4jCYBcu3QHPBljbgAkfQL9ZfttRDLg+G63Fnh6/f5QvIsV72JNlzNVh54c3+1IAsd36/XgXuEm0inhJlIt8OT4bsUCjdbtI5lUmlMyqTTN8gPAs72ytlDM5s+kH4rZPMaYawvoogUkX7H7w2E+Wy0uiu+rBZLmFuj3xkOi7fpMCrcRL5MAYPDvPOaP4IWk79fv4Eft841qprSDGwAAAABJRU5ErkJggg==' or status_s.link == 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAbVJREFUSEu9ls8rRFEUx7/nzsjvjWQxSSTPJE1Zv0nUjEiIhRQbxQKTUiSr914pK6mJFWUjlqL8ysbCrJWVIWUh/wBF4R3d18w0zMwzi7nztu/7zuee7zn3nEdweQJGV/2H+BqCzf0gNAPwJeQvYDxC0EmZ7T26ta6ec4WhbC9aDd3HBIsZkwB73A4B0DcRdolhxK3Yy19tBqDV0AcZ2GNwtVd4EPJ3IuzvRLvPj7rqWnSshbPyCPRKwETcih2nC34BWszgPGBvgCFk0OWeOTTU1P8KqJl67oQINiAWHszraFKUAsiT28SHBBKLoRlM6+NZA7kC5BcEWzANJzNxAI7nwJ20ZSk8mzO41P4LcBiOXX5ZEwegmfo2M09JW7bG1lxrmg/ASYRo596MTZNsxXd8PnmF8JxH9jM8/0vLFyC7qxwljaRZwTm27c3etm5ER1fdOzJPi1IFFiJCmqGfMrhvfcTAQKCnsADQGWmmHmdm7SJygKbahsICiO4l4JWZq25WLlFZWlFowFtRAIotUl5k1W2q/KIpHxVFGXYJiLpxnbxdShdOEqJ0ZaZB1C399GFUiN+WH16q+w/WuLNCAAAAAElFTkSuQmCC': titile = detaill_info.ele('x://p[@class="title"]') print('>', titile.text, ' 未完成') # 进行完成操作 titile.click() page.wait.load_start(timeout=1) run() else: titile = detaill_info.ele('x:.//p[@class="title"]').text print('>', titile, ' 已完成') # 获取小章节 def get_x_chapter(chapters): x_chapters = chapters.eles('x:.//div[@class="first-level-inner-box"]/div') for x_chapter in x_chapters: x_chapter_title = x_chapter.ele('x:.//div[@class="p"]//span[@class="title-big"]') # 如果不存在标题 and 只获取课件开头的 if not x_chapter_title: continue print('--------->', x_chapter_title.text) get_detail_info(x_chapter) # 获取大章节信息 def get_chapter(): chapters = page.eles('x:.//div[@class="left-box"]/div[@class="menu-box"]/div')[1:-1] for chapter in chapters: chapter_title = chapter.ele('x:.//p[@class="title-big"]').text print('\n====================', chapter_title, '====================') # 判断是否展开详情 is_open = chapter.ele('x:.//div[@class="first-level-inner-box"]/@style', timeout=0.2) if not is_open or is_open == 'height: 0px;': # 展开详情 chapter.ele('x:.//p[@class="title-big"]').click() time.sleep(0.2) get_x_chapter(chapter) def is_logn(): page.get('https://www.cqooc.com/index/home') page.wait.load_start(timeout=30) while True: page.get('https://www.cqooc.com/index/home') page.wait.load_start(timeout=1) # 查找登录按钮 no_logn_status = page('xpath=//span[@class="login-logo"]', timeout=1) # 未登录 if no_logn_status: print('账号未登录,请先完成登录!') # 执行登录操作 username = input('请输入账号:') password = input('请输入密码:') # 登录操作 page('xpath=//span[@class="login-logo"]', timeout=1).click() time.sleep(0.5) page.ele('xpath=//div[@class="username-box"]//input').input(username) page.ele('xpath=//div[@class="password-box"]//input').input(password) time.sleep(0.5) page.ele('xpath=//div[@class="submit-btn"]').click() time.sleep(1) else: print('账号已登录--->开始运行') break def run_set(): print( '项目说明:本软件只适用于智慧教育平台中《纪录片创作》课程\n\n使用方法:\n\n1.下载Chrome浏览器(如果有就不需要再下载了)\n\n>下载地址:https://www.google.cn/intl/zh-CN/chrome/\n\n2.在Chrome浏览器上登录智慧教育(刷课平台)\n\n>智慧教育:https://www.cqooc.com/index/home\n\n3.完成了以上操作后按任意键运行') chrom_path = input() if __name__ == '__main__': run_set() # 页面设置 co = ChromiumOptions() # 设置启动时最大化 co.set_argument('--start-maximized') # 设置浏览器路径 # co.set_browser_path(path="C:\Program Files\Google\Chrome\Application\chrome.exe") # 设置超时时间 co.set_timeouts(base=0.2) page = ChromiumPage(co) # 宇宙免责声明 print(''' # 免责声明 本软件及其相关文档(以下简称“软件”)仅供教育和学习目的使用。作者提供此软件时,不提供任何形式的明示或暗示的担保,包括但不限于对适销性、特定用途适用性、所有权和非侵权性的任何保证。 在任何情况下,作者均不对任何个人或实体因使用或无法使用本软件而可能遭受的任何直接、间接、偶然、特殊、惩罚性或后果性损失承担责任,无论这些损失是基于合同、侵权行为(包括疏忽)或其他原因造成的,即使作者已被告知此类损失的可能性。 在使用本软件时,用户应自行承担风险。作者不对任何因使用或依赖本软件而产生的损失或损害承担责任。 用户应确保遵守所有适用的法律和法规,并对其使用本软件的行为负责。本软件不得用于任何非法目的,或者以任何非法方式使用。 ## 有任何问题联系:2841952537 ## 开源地址:https://github.com/2841952537/cqooc_class ''') print('等待页面加载中...预计30秒...') # 登录判断 is_logn() # 访问页面 page.get('https://www.cqooc.com/course/detail/courseStudy?id=dc58e3be5d477b79&kkzt=true') # page.get('https://www.cqooc.com/course/detail/courseStudy?id=334572312') page.wait.load_start(timeout=3) # 获取大章节信息 get_chapter()
2977094657/BilibiliHistoryFetcher
10,870
routers/data_sync.py
import json import os import yaml from datetime import datetime from typing import Optional, List from fastapi import APIRouter, BackgroundTasks, Query, HTTPException from pydantic import BaseModel from scripts.check_data_integrity import check_data_integrity from scripts.sync_db_json import sync_data from scripts.utils import load_config, get_output_path router = APIRouter() class SyncedDayInfo(BaseModel): date: str imported_count: int source: str titles: List[str] class SyncDBJsonResponse(BaseModel): success: bool json_to_db_count: int db_to_json_count: int total_synced: int timestamp: str synced_days: Optional[List[SyncedDayInfo]] = None message: Optional[str] = None class CheckDataIntegrityResponse(BaseModel): success: bool total_json_files: int total_json_records: int total_db_records: int missing_records_count: int extra_records_count: int difference: int result_file: str report_file: str timestamp: str class IntegrityCheckConfigRequest(BaseModel): check_on_startup: bool class IntegrityCheckConfigResponse(BaseModel): success: bool message: str check_on_startup: bool def run_sync_data(db_path: Optional[str] = None, json_root_path: Optional[str] = None): """在后台运行数据同步任务""" # 确保输出目录存在 os.makedirs("output/check", exist_ok=True) # 调用同步函数 result = sync_data(db_path, json_root_path) return result def run_check_integrity(db_path: Optional[str] = None, json_root_path: Optional[str] = None): """在后台运行数据完整性检查任务""" # 确保输出目录存在 os.makedirs("output/check", exist_ok=True) # 调用检查函数 result = check_data_integrity(db_path, json_root_path) return result @router.post("/sync", response_model=SyncDBJsonResponse, summary="同步数据库和JSON文件") async def sync_db_json( background_tasks: BackgroundTasks, db_path: Optional[str] = Query(None, description="数据库文件路径,默认为 output/bilibili_history.db"), json_path: Optional[str] = Query(None, description="JSON文件根目录,默认为 output/history_by_date"), async_mode: bool = Query(False, description="是否异步执行(后台任务)") ): """ 同步数据库和JSON文件中的历史记录数据。 - 将JSON文件中的新记录导入到数据库 - 将数据库中的新记录导出到JSON文件 返回: - 导入和导出的记录数量 - 按日期同步的详细信息,包括每天同步的记录数和记录标题 """ if async_mode: # 异步模式下,将任务放入后台执行 background_tasks.add_task(run_sync_data, db_path, json_path) return { "success": True, "json_to_db_count": 0, "db_to_json_count": 0, "total_synced": 0, "timestamp": datetime.now().isoformat(), "message": "同步任务已在后台启动,请稍后查看日志获取结果" } else: # 同步模式下,直接执行并返回结果 result = run_sync_data(db_path, json_path) # 如果result不包含synced_days字段,添加一个空列表 if "synced_days" not in result: result["synced_days"] = [] # 添加timestamp如果不存在 if "timestamp" not in result: result["timestamp"] = datetime.now().isoformat() return result @router.post("/check", response_model=CheckDataIntegrityResponse, summary="检查数据完整性") async def check_integrity( background_tasks: BackgroundTasks, db_path: Optional[str] = Query(None, description="数据库文件路径,默认为 output/bilibili_history.db"), json_path: Optional[str] = Query(None, description="JSON文件根目录,默认为 output/history_by_date"), async_mode: bool = Query(False, description="是否异步执行(后台任务)"), force_check: bool = Query(False, description="是否强制执行检查,忽略配置设置") ): """ 检查数据库和JSON文件之间的数据完整性。 - 检查JSON文件是否都被正确导入到数据库 - 检查数据库中的记录是否都存在于JSON文件中 - 生成详细的差异报告 返回检查结果和报告文件路径。 """ # 检查配置是否允许执行数据完整性校验 if not force_check: config = load_config() check_enabled = config.get('server', {}).get('data_integrity', {}).get('check_on_startup', True) if not check_enabled: return { "success": True, "total_json_files": 0, "total_json_records": 0, "total_db_records": 0, "missing_records_count": 0, "extra_records_count": 0, "difference": 0, "result_file": "", "report_file": "", "timestamp": datetime.now().isoformat(), "message": "数据完整性校验已在配置中禁用,跳过检查。如需强制检查,请使用force_check=true参数。" } if async_mode: # 异步模式下,将任务放入后台执行 background_tasks.add_task(run_check_integrity, db_path, json_path) return { "success": True, "total_json_files": 0, "total_json_records": 0, "total_db_records": 0, "missing_records_count": 0, "extra_records_count": 0, "difference": 0, "result_file": "output/check/data_integrity_results.json", "report_file": "output/check/data_integrity_report.md", "timestamp": datetime.now().isoformat(), "message": "数据完整性检查任务已在后台启动,请稍后查看报告文件获取结果" } else: # 同步模式下,直接执行并返回结果 result = run_check_integrity(db_path, json_path) return { **result, "timestamp": datetime.now().isoformat() } @router.get("/report", summary="获取最新的数据完整性报告") async def get_report(): """ 获取最新的数据完整性检查报告的内容。 返回报告的内容和最后修改时间。 """ # 检查配置是否允许执行数据完整性校验 config = load_config() check_enabled = config.get('server', {}).get('data_integrity', {}).get('check_on_startup', True) report_file = "output/check/data_integrity_report.md" if not os.path.exists(report_file): # 如果报告文件不存在,检查是否是因为配置禁用了校验 if not check_enabled: return { "message": "数据完整性校验已在配置中禁用,无法获取报告。如需查看报告,请先执行数据完整性检查。" } else: raise HTTPException(status_code=404, detail="报告文件不存在,请先执行数据完整性检查") try: with open(report_file, "r", encoding="utf-8") as f: content = f.read() # 获取文件修改时间 mod_time = os.path.getmtime(report_file) mod_time_str = datetime.fromtimestamp(mod_time).isoformat() return { "content": content, "modified_time": mod_time_str, "file_path": report_file } except Exception as e: raise HTTPException(status_code=500, detail=f"读取报告文件时出错: {str(e)}") @router.get("/sync/result", summary="获取最新的同步结果") async def get_sync_result(): """ 获取最新的数据同步结果。 返回同步的详细信息,包括每天同步的记录数量和记录标题。 """ result_file = "output/check/sync_result.json" if not os.path.exists(result_file): raise HTTPException(status_code=404, detail="同步结果文件不存在,请先执行数据同步") try: with open(result_file, "r", encoding="utf-8") as f: result = json.load(f) # 获取文件修改时间 mod_time = os.path.getmtime(result_file) mod_time_str = datetime.fromtimestamp(mod_time).isoformat() # 添加文件修改时间 result["file_modified_time"] = mod_time_str return result except Exception as e: raise HTTPException(status_code=500, detail=f"读取同步结果文件时出错: {str(e)}") @router.get("/config", summary="获取数据完整性校验配置") async def get_integrity_check_config(): """ 获取数据完整性校验配置。 返回当前的数据完整性校验配置,包括是否在启动时进行校验。 """ try: # 加载配置 config = load_config() # 获取数据完整性校验配置 check_on_startup = config.get('server', {}).get('data_integrity', {}).get('check_on_startup', True) return IntegrityCheckConfigResponse( success=True, message="获取配置成功", check_on_startup=check_on_startup ) except Exception as e: raise HTTPException(status_code=500, detail=f"获取数据完整性校验配置时出错: {str(e)}") @router.post("/config", response_model=IntegrityCheckConfigResponse, summary="更新数据完整性校验配置") async def update_integrity_check_config(request: IntegrityCheckConfigRequest): """ 更新数据完整性校验配置。 - 设置是否在启动时进行数据完整性校验 返回更新后的配置。 """ try: # 获取配置文件路径 config_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.yaml") # 读取当前配置文件内容 with open(config_path, 'r', encoding='utf-8') as f: content = f.read() config = yaml.safe_load(content) # 仅用于获取当前配置和检查结构 # 确保server和data_integrity配置存在 if 'server' not in config: config['server'] = {} if 'data_integrity' not in config['server']: config['server']['data_integrity'] = {} # 使用正则表达式精确更新配置值 import re # 检查是否已存在data_integrity配置 data_integrity_exists = False server_exists = False check_on_startup_exists = False lines = content.split('\n') for i, line in enumerate(lines): if re.match(r'^\s*server\s*:', line): server_exists = True elif server_exists and re.match(r'^\s{2}data_integrity\s*:', line): data_integrity_exists = True elif data_integrity_exists and re.match(r'^\s{4}check_on_startup\s*:', line): check_on_startup_exists = True # 更新check_on_startup的值 indent = line[:line.find('check_on_startup')] lines[i] = f"{indent}check_on_startup: {str(request.check_on_startup).lower()}" break # 如果没有找到check_on_startup配置,需要添加 if not check_on_startup_exists: if data_integrity_exists: # 找到data_integrity行,在其后添加check_on_startup for i, line in enumerate(lines): if re.match(r'^\s{2}data_integrity\s*:', line): lines.insert(i + 1, f" check_on_startup: {str(request.check_on_startup).lower()}") break elif server_exists: # 找到server行,在其后添加data_integrity和check_on_startup for i, line in enumerate(lines): if re.match(r'^\s*server\s*:', line): lines.insert(i + 1, f" data_integrity:") lines.insert(i + 2, f" check_on_startup: {str(request.check_on_startup).lower()}") break else: # 如果没有server配置,在文件末尾添加 lines.append("server:") lines.append(" data_integrity:") lines.append(f" check_on_startup: {str(request.check_on_startup).lower()}") # 写回配置文件 with open(config_path, 'w', encoding='utf-8') as f: f.write('\n'.join(lines)) # 更新内存中的配置 config['server']['data_integrity']['check_on_startup'] = request.check_on_startup return IntegrityCheckConfigResponse( success=True, message="配置已更新", check_on_startup=request.check_on_startup ) except Exception as e: raise HTTPException(status_code=500, detail=f"更新数据完整性校验配置时出错: {str(e)}")
2841952537/cqooc_class
892
README.md
# 智慧教育刷课脚本 ## 💯💯💯最新版本V3.0.0已更新 下载`CQOOC重庆高校在线V3.0.0.exe`双击运行即可 最新教学视频: [哔哩哔哩](https://www.bilibili.com/video/BV1e2NUeeE5F/?share_source=copy_web&vd_source=c22c1190086150b28a7ae891c20bb5b0) ## 简介 项目分为两个版本 1. 高等教育平台_Chrome.exe 2. 高等教育平台_Requests.exe Chrome版本基于DrissionPage库开发,是自动化程序(需要浏览器支持) Requests版本基于requests库开发,是协议程序(不需要浏览器支持) ## 使用前提 - Chrome版本确保你已经安装了Chrome浏览器。 - 拥有重庆智慧教育平台账号。 ## 使用方法 --> [视频教程](https://www.bilibili.com/video/BV17By8YvEBU/) - ### Chrome版本 ##### 1. 下载Chrome ​ 下载链接:[Chrome](https://www.google.cn/intl/zh-CN/chrome/) ##### 2. 运行可执行文件 ​ 双击下载的`高等教育平台_Chrome.exe`文件即可运行。 - ### Request版本 ##### 1. 运行可执行文件 ​ 双击下载的`高等教育平台_Requests.exe`文件即可运行。 - ### 能做什么 - [x] 完成课件 - [x] 完成视频 - [ ] 完成作业 - [ ] 完成讨论 ## 安装指南 如果你希望查看源代码或自行打包脚本,请按照以下步骤操作: ### 1. 克隆源代码 使用Git克隆源代码到本地: ```bash git clone https://github.com/2841952537/cqooc_class.git
2977094657/BilibiliHistoryFetcher
1,251
routers/analysis.py
from fastapi import APIRouter, Query from typing import Optional from datetime import datetime from scripts.analyze_bilibili_history import get_daily_and_monthly_counts, get_available_years router = APIRouter() @router.post("/analyze", summary="分析历史数据") async def analyze_history( year: Optional[int] = Query(None, description="要分析的年份,不传则使用当前年份") ): """分析历史数据 Args: year: 要分析的年份,不传则使用当前年份 """ # 获取可用年份列表 available_years = get_available_years() if not available_years: return { "status": "error", "message": "未找到任何历史记录数据" } # 如果未指定年份,使用最新的年份 target_year = year if year is not None else available_years[0] # 检查指定的年份是否可用 if year is not None and year not in available_years: return { "status": "error", "message": f"未找到 {year} 年的历史记录数据。可用的年份有:{', '.join(map(str, available_years))}" } result = get_daily_and_monthly_counts(target_year) if "error" in result: return {"status": "error", "message": result["error"]} return { "status": "success", "message": "分析完成", "data": result, "year": target_year, "available_years": available_years }
2929004360/ruoyi-sign
3,229
ruoyi-flowable/src/main/java/com/ruoyi/flowable/page/PageQuery.java
package com.ruoyi.flowable.page; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.sql.SqlUtil; import com.ruoyi.flowable.utils.StringUtils; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * 分页查询实体类 * * @author fengcheng */ @Data public class PageQuery implements Serializable { private static final long serialVersionUID = 1L; /** * 分页大小 */ private Integer pageSize; /** * 当前页数 */ private Integer pageNum; /** * 排序列 */ private String orderByColumn; /** * 排序的方向desc或者asc */ private String isAsc; /** * 当前记录起始索引 默认值 */ public static final int DEFAULT_PAGE_NUM = 1; /** * 每页显示记录数 默认值 默认查全部 */ public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE; public <T> Page<T> build() { Integer pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM); Integer pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE); if (pageNum <= 0) { pageNum = DEFAULT_PAGE_NUM; } Page<T> page = new Page<>(pageNum, pageSize); List<OrderItem> orderItems = buildOrderItem(); if (CollUtil.isNotEmpty(orderItems)) { page.addOrder(orderItems); } return page; } /** * 构建排序 * * 支持的用法如下: * {isAsc:"asc",orderByColumn:"id"} order by id asc * {isAsc:"asc",orderByColumn:"id,createTime"} order by id asc,create_time asc * {isAsc:"desc",orderByColumn:"id,createTime"} order by id desc,create_time desc * {isAsc:"asc,desc",orderByColumn:"id,createTime"} order by id asc,create_time desc */ private List<OrderItem> buildOrderItem() { if (StringUtils.isBlank(orderByColumn) || StringUtils.isBlank(isAsc)) { return null; } String orderBy = SqlUtil.escapeOrderBySql(orderByColumn); orderBy = StringUtils.toUnderScoreCase(orderBy); // 兼容前端排序类型 isAsc = StringUtils.replaceEach(isAsc, new String[]{"ascending", "descending"}, new String[]{"asc", "desc"}); String[] orderByArr = orderBy.split(StringUtils.SEPARATOR); String[] isAscArr = isAsc.split(StringUtils.SEPARATOR); if (isAscArr.length != 1 && isAscArr.length != orderByArr.length) { throw new ServiceException("排序参数有误"); } List<OrderItem> list = new ArrayList<>(); // 每个字段各自排序 for (int i = 0; i < orderByArr.length; i++) { String orderByStr = orderByArr[i]; String isAscStr = isAscArr.length == 1 ? isAscArr[0] : isAscArr[i]; if ("asc".equals(isAscStr)) { list.add(OrderItem.asc(orderByStr)); } else if ("desc".equals(isAscStr)) { list.add(OrderItem.desc(orderByStr)); } else { throw new ServiceException("排序参数有误"); } } return list; } }
2929004360/ruoyi-sign
1,647
ruoyi-flowable/src/main/java/com/ruoyi/flowable/page/TableDataInfo.java
package com.ruoyi.flowable.page; import cn.hutool.http.HttpStatus; import com.baomidou.mybatisplus.core.metadata.IPage; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; /** * 表格分页数据对象 * * @author fengcheng */ @Data @NoArgsConstructor public class TableDataInfo<T> implements Serializable { private static final long serialVersionUID = 1L; /** * 总记录数 */ private long total; /** * 列表数据 */ private List<T> rows; /** * 消息状态码 */ private int code; /** * 消息内容 */ private String msg; /** * 分页 * * @param list 列表数据 * @param total 总记录数 */ public TableDataInfo(List<T> list, long total) { this.rows = list; this.total = total; } public static <T> TableDataInfo<T> build(IPage<T> page) { TableDataInfo<T> rspData = new TableDataInfo<>(); rspData.setCode(HttpStatus.HTTP_OK); rspData.setMsg("查询成功"); rspData.setRows(page.getRecords()); rspData.setTotal(page.getTotal()); return rspData; } public static <T> TableDataInfo<T> build(List<T> list) { TableDataInfo<T> rspData = new TableDataInfo<>(); rspData.setCode(HttpStatus.HTTP_OK); rspData.setMsg("查询成功"); rspData.setRows(list); rspData.setTotal(list.size()); return rspData; } public static <T> TableDataInfo<T> build() { TableDataInfo<T> rspData = new TableDataInfo<>(); rspData.setCode(HttpStatus.HTTP_OK); rspData.setMsg("查询成功"); return rspData; } }
281677160/openwrt-package
20,243
luci-app-homeproxy/root/etc/homeproxy/scripts/update_subscriptions.uc
#!/usr/bin/ucode /* * SPDX-License-Identifier: GPL-2.0-only * * Copyright (C) 2023 ImmortalWrt.org */ 'use strict'; import { md5 } from 'digest'; import { open } from 'fs'; import { connect } from 'ubus'; import { cursor } from 'uci'; import { urldecode, urlencode } from 'luci.http'; import { init_action } from 'luci.sys'; import { wGET, decodeBase64Str, getTime, isEmpty, parseURL, validation, HP_DIR, RUN_DIR } from 'homeproxy'; /* UCI config start */ const uci = cursor(); const uciconfig = 'homeproxy'; uci.load(uciconfig); const ucimain = 'config', ucinode = 'node', ucisubscription = 'subscription'; const allow_insecure = uci.get(uciconfig, ucisubscription, 'allow_insecure') || '0', filter_mode = uci.get(uciconfig, ucisubscription, 'filter_nodes') || 'disabled', filter_keywords = uci.get(uciconfig, ucisubscription, 'filter_keywords') || [], packet_encoding = uci.get(uciconfig, ucisubscription, 'packet_encoding') || 'xudp', subscription_urls = uci.get(uciconfig, ucisubscription, 'subscription_url') || [], user_agent = uci.get(uciconfig, ucisubscription, 'user_agent'), via_proxy = uci.get(uciconfig, ucisubscription, 'update_via_proxy') || '0'; const routing_mode = uci.get(uciconfig, ucimain, 'routing_mode') || 'bypass_mainalnd_china'; let main_node, main_udp_node; if (routing_mode !== 'custom') { main_node = uci.get(uciconfig, ucimain, 'main_node') || 'nil'; main_udp_node = uci.get(uciconfig, ucimain, 'main_udp_node') || 'nil'; } /* UCI config end */ /* String helper start */ function filter_check(name) { if (isEmpty(name) || filter_mode === 'disabled' || isEmpty(filter_keywords)) return false; let ret = false; for (let i in filter_keywords) { const patten = regexp(i); if (match(name, patten)) ret = true; } if (filter_mode === 'whitelist') ret = !ret; return ret; } /* String helper end */ /* Common var start */ const node_cache = {}, node_result = []; const ubus = connect(); const sing_features = ubus.call('luci.homeproxy', 'singbox_get_features', {}) || {}; /* Common var end */ /* Log */ system(`mkdir -p ${RUN_DIR}`); function log(...args) { const logfile = open(`${RUN_DIR}/homeproxy.log`, 'a'); logfile.write(`${getTime()} [SUBSCRIBE] ${join(' ', args)}\n`); logfile.close(); } function parse_uri(uri) { let config, url, params; if (type(uri) === 'object') { if (uri.nodetype === 'sip008') { /* https://shadowsocks.org/guide/sip008.html */ config = { label: uri.remarks, type: 'shadowsocks', address: uri.server, port: uri.server_port, shadowsocks_encrypt_method: uri.method, password: uri.password, shadowsocks_plugin: uri.plugin, shadowsocks_plugin_opts: uri.plugin_opts }; } } else if (type(uri) === 'string') { uri = split(trim(uri), '://'); switch (uri[0]) { case 'anytls': /* https://github.com/anytls/anytls-go/blob/v0.0.8/docs/uri_scheme.md */ url = parseURL('http://' + uri[1]) || {}; params = url.searchParams || {}; config = { label: url.hash ? urldecode(url.hash) : null, type: 'anytls', address: url.hostname, port: url.port, password: urldecode(url.username), tls: '1', tls_sni: params.sni, tls_insecure: (params.insecure === '1') ? '1' : '0' }; break; case 'http': case 'https': url = parseURL('http://' + uri[1]) || {}; config = { label: url.hash ? urldecode(url.hash) : null, type: 'http', address: url.hostname, port: url.port, username: url.username ? urldecode(url.username) : null, password: url.password ? urldecode(url.password) : null, tls: (uri[0] === 'https') ? '1' : '0' }; break; case 'hysteria': /* https://github.com/HyNetwork/hysteria/wiki/URI-Scheme */ url = parseURL('http://' + uri[1]) || {}; params = url.searchParams; if (!sing_features.with_quic || (params.protocol && params.protocol !== 'udp')) { log(sprintf('Skipping unsupported %s node: %s.', uri[0], urldecode(url.hash) || url.hostname)); if (!sing_features.with_quic) log(sprintf('Please rebuild sing-box with %s support!', 'QUIC')); return null; } config = { label: url.hash ? urldecode(url.hash) : null, type: 'hysteria', address: url.hostname, port: url.port, hysteria_protocol: params.protocol || 'udp', hysteria_auth_type: params.auth ? 'string' : null, hysteria_auth_payload: params.auth, hysteria_obfs_password: params.obfsParam, hysteria_down_mbps: params.downmbps, hysteria_up_mbps: params.upmbps, tls: '1', tls_insecure: (params.insecure in ['true', '1']) ? '1' : '0', tls_sni: params.peer, tls_alpn: params.alpn }; break; case 'hysteria2': case 'hy2': /* https://v2.hysteria.network/docs/developers/URI-Scheme/ */ url = parseURL('http://' + uri[1]) || {}; params = url.searchParams; if (!sing_features.with_quic) { log(sprintf('Skipping unsupported %s node: %s.', uri[0], urldecode(url.hash) || url.hostname)); log(sprintf('Please rebuild sing-box with %s support!', 'QUIC')); return null; } config = { label: url.hash ? urldecode(url.hash) : null, type: 'hysteria2', address: url.hostname, port: url.port, password: url.username ? ( urldecode(url.username + (url.password ? (':' + url.password) : '')) ) : null, hysteria_obfs_type: params.obfs, hysteria_obfs_password: params['obfs-password'], tls: '1', tls_insecure: (params.insecure === '1') ? '1' : '0', tls_sni: params.sni }; break; case 'socks': case 'socks4': case 'socks4a': case 'socsk5': case 'socks5h': url = parseURL('http://' + uri[1]) || {}; config = { label: url.hash ? urldecode(url.hash) : null, type: 'socks', address: url.hostname, port: url.port, username: url.username ? urldecode(url.username) : null, password: url.password ? urldecode(url.password) : null, socks_version: (match(uri[0], /4/)) ? '4' : '5' }; break; case 'ss': /* "Lovely" Shadowrocket format */ const ss_suri = split(uri[1], '#'); let ss_slabel = ''; if (length(ss_suri) <= 2) { if (length(ss_suri) === 2) ss_slabel = '#' + urlencode(ss_suri[1]); if (decodeBase64Str(ss_suri[0])) uri[1] = decodeBase64Str(ss_suri[0]) + ss_slabel; } /* Legacy format is not supported, it should be never appeared in modern subscriptions */ /* https://github.com/shadowsocks/shadowsocks-org/commit/78ca46cd6859a4e9475953ed34a2d301454f579e */ /* SIP002 format https://shadowsocks.org/guide/sip002.html */ url = parseURL('http://' + uri[1]) || {}; let ss_userinfo = {}; if (url.username && url.password) /* User info encoded with URIComponent */ ss_userinfo = [url.username, urldecode(url.password)]; else if (url.username) /* User info encoded with base64 */ ss_userinfo = split(decodeBase64Str(urldecode(url.username)), ':', 2); let ss_plugin, ss_plugin_opts; if (url.search && url.searchParams.plugin) { const ss_plugin_info = split(url.searchParams.plugin, ';', 2); ss_plugin = ss_plugin_info[0]; if (ss_plugin === 'simple-obfs') /* Fix non-standard plugin name */ ss_plugin = 'obfs-local'; ss_plugin_opts = ss_plugin_info[1]; } config = { label: url.hash ? urldecode(url.hash) : null, type: 'shadowsocks', address: url.hostname, port: url.port, shadowsocks_encrypt_method: ss_userinfo[0], password: ss_userinfo[1], shadowsocks_plugin: ss_plugin, shadowsocks_plugin_opts: ss_plugin_opts }; break; case 'trojan': /* https://p4gefau1t.github.io/trojan-go/developer/url/ */ url = parseURL('http://' + uri[1]) || {}; params = url.searchParams || {}; config = { label: url.hash ? urldecode(url.hash) : null, type: 'trojan', address: url.hostname, port: url.port, password: urldecode(url.username), transport: (params.type !== 'tcp') ? params.type : null, tls: '1', tls_sni: params.sni }; switch(params.type) { case 'grpc': config.grpc_servicename = params.serviceName; break; case 'ws': config.ws_host = params.host ? urldecode(params.host) : null; config.ws_path = params.path ? urldecode(params.path) : null; if (config.ws_path && match(config.ws_path, /\?ed=/)) { config.websocket_early_data_header = 'Sec-WebSocket-Protocol'; config.websocket_early_data = split(config.ws_path, '?ed=')[1]; config.ws_path = split(config.ws_path, '?ed=')[0]; } break; } break; case 'tuic': /* https://github.com/daeuniverse/dae/discussions/182 */ url = parseURL('http://' + uri[1]) || {}; params = url.searchParams || {}; if (!sing_features.with_quic) { log(sprintf('Skipping unsupported %s node: %s.', uri[0], urldecode(url.hash) || url.hostname)); log(sprintf('Please rebuild sing-box with %s support!', 'QUIC')); return null; } config = { label: url.hash ? urldecode(url.hash) : null, type: 'tuic', address: url.hostname, port: url.port, uuid: url.username, password: url.password ? urldecode(url.password) : null, tuic_congestion_control: params.congestion_control, tuic_udp_relay_mode: params.udp_relay_mode, tls: '1', tls_sni: params.sni, tls_alpn: params.alpn ? split(urldecode(params.alpn), ',') : null, }; break; case 'vless': /* https://github.com/XTLS/Xray-core/discussions/716 */ url = parseURL('http://' + uri[1]) || {}; params = url.searchParams; /* Unsupported protocol */ if (params.type === 'kcp') { log(sprintf('Skipping sunsupported %s node: %s.', uri[0], urldecode(url.hash) || url.hostname)); return null; } else if (params.type === 'quic' && ((params.quicSecurity && params.quicSecurity !== 'none') || !sing_features.with_quic)) { log(sprintf('Skipping sunsupported %s node: %s.', uri[0], urldecode(url.hash) || url.hostname)); if (!sing_features.with_quic) log(sprintf('Please rebuild sing-box with %s support!', 'QUIC')); return null; } config = { label: url.hash ? urldecode(url.hash) : null, type: 'vless', address: url.hostname, port: url.port, uuid: url.username, transport: (params.type !== 'tcp') ? params.type : null, tls: (params.security in ['tls', 'xtls', 'reality']) ? '1' : '0', tls_sni: params.sni, tls_alpn: params.alpn ? split(urldecode(params.alpn), ',') : null, tls_reality: (params.security === 'reality') ? '1' : '0', tls_reality_public_key: params.pbk ? urldecode(params.pbk) : null, tls_reality_short_id: params.sid, tls_utls: sing_features.with_utls ? params.fp : null, vless_flow: (params.security in ['tls', 'reality']) ? params.flow : null }; switch(params.type) { case 'grpc': config.grpc_servicename = params.serviceName; break; case 'http': case 'tcp': if (params.type === 'http' || params.headerType === 'http') { config.http_host = params.host ? split(urldecode(params.host), ',') : null; config.http_path = params.path ? urldecode(params.path) : null; } break; case 'httpupgrade': config.httpupgrade_host = params.host ? urldecode(params.host) : null; config.http_path = params.path ? urldecode(params.path) : null; break; case 'ws': config.ws_host = params.host ? urldecode(params.host) : null; config.ws_path = params.path ? urldecode(params.path) : null; if (config.ws_path && match(config.ws_path, /\?ed=/)) { config.websocket_early_data_header = 'Sec-WebSocket-Protocol'; config.websocket_early_data = split(config.ws_path, '?ed=')[1]; config.ws_path = split(config.ws_path, '?ed=')[0]; } break; } break; case 'vmess': /* "Lovely" shadowrocket format */ if (match(uri, /&/)) { log(sprintf('Skipping unsupported %s format.', uri[0])); return null; } /* https://github.com/2dust/v2rayN/wiki/Description-of-VMess-share-link */ try { uri = json(decodeBase64Str(uri[1])) || {}; } catch(e) { log(sprintf('Skipping unsupported %s format.', uri[0])); return null; } if (uri.v != '2') { log(sprintf('Skipping unsupported %s format.', uri[0])); return null; /* Unsupported protocol */ } else if (uri.net === 'kcp') { log(sprintf('Skipping unsupported %s node: %s.', uri[0], uri.ps || uri.add)); return null; } else if (uri.net === 'quic' && ((uri.type && uri.type !== 'none') || uri.path || !sing_features.with_quic)) { log(sprintf('Skipping unsupported %s node: %s.', uri[0], uri.ps || uri.add)); if (!sing_features.with_quic) log(sprintf('Please rebuild sing-box with %s support!', 'QUIC')); return null; } /* * https://www.v2fly.org/config/protocols/vmess.html#vmess-md5-%E8%AE%A4%E8%AF%81%E4%BF%A1%E6%81%AF-%E6%B7%98%E6%B1%B0%E6%9C%BA%E5%88%B6 * else if (uri.aid && int(uri.aid) !== 0) { * log(sprintf('Skipping unsupported %s node: %s.', uri[0], uri.ps || uri.add)); * return null; * } */ config = { label: uri.ps ? urldecode(uri.ps) : null, type: 'vmess', address: uri.add, port: uri.port, uuid: uri.id, vmess_alterid: uri.aid, vmess_encrypt: uri.scy || 'auto', vmess_global_padding: '1', transport: (uri.net !== 'tcp') ? uri.net : null, tls: (uri.tls === 'tls') ? '1' : '0', tls_sni: uri.sni || uri.host, tls_alpn: uri.alpn ? split(uri.alpn, ',') : null, tls_utls: sing_features.with_utls ? uri.fp : null }; switch (uri.net) { case 'grpc': config.grpc_servicename = uri.path; break; case 'h2': case 'tcp': if (uri.net === 'h2' || uri.type === 'http') { config.transport = 'http'; config.http_host = uri.host ? split(uri.host, ',') : null; config.http_path = uri.path; } break; case 'httpupgrade': config.httpupgrade_host = uri.host; config.http_path = uri.path; break; case 'ws': config.ws_host = uri.host; config.ws_path = uri.path; if (config.ws_path && match(config.ws_path, /\?ed=/)) { config.websocket_early_data_header = 'Sec-WebSocket-Protocol'; config.websocket_early_data = split(config.ws_path, '?ed=')[1]; config.ws_path = split(config.ws_path, '?ed=')[0]; } break; } break; } } if (!isEmpty(config)) { if (config.address) config.address = replace(config.address, /\[|\]/g, ''); if (!validation('host', config.address) || !validation('port', config.port)) { log(sprintf('Skipping invalid %s node: %s.', config.type, config.label || 'NULL')); return null; } else if (!config.label) config.label = (validation('ip6addr', config.address) ? `[${config.address}]` : config.address) + ':' + config.port; } return config; } function main() { if (via_proxy !== '1') { log('Stopping service...'); init_action('homeproxy', 'stop'); } for (let url in subscription_urls) { url = replace(url, /#.*$/, ''); const groupHash = md5(url); node_cache[groupHash] = {}; const res = wGET(url, user_agent); if (isEmpty(res)) { log(sprintf('Failed to fetch resources from %s.', url)); continue; } let nodes; try { nodes = json(res).servers || json(res); /* Shadowsocks SIP008 format */ if (nodes[0].server && nodes[0].method) map(nodes, (_, i) => nodes[i].nodetype = 'sip008'); } catch(e) { nodes = decodeBase64Str(res); nodes = nodes ? split(trim(replace(nodes, / /g, '_')), '\n') : []; } let count = 0; for (let node in nodes) { let config; if (!isEmpty(node)) config = parse_uri(node); if (isEmpty(config)) continue; const label = config.label; config.label = null; const confHash = md5(sprintf('%J', config)), nameHash = md5(label); config.label = label; if (filter_check(config.label)) log(sprintf('Skipping blacklist node: %s.', config.label)); else if (node_cache[groupHash][confHash] || node_cache[groupHash][nameHash]) log(sprintf('Skipping duplicate node: %s.', config.label)); else { if (config.tls === '1' && allow_insecure === '1') config.tls_insecure = '1'; if (config.type in ['vless', 'vmess']) config.packet_encoding = packet_encoding; config.grouphash = groupHash; push(node_result, []); push(node_result[length(node_result)-1], config); node_cache[groupHash][confHash] = config; node_cache[groupHash][nameHash] = config; count++; } } if (count == 0) log(sprintf('No valid node found in %s.', url)); else log(sprintf('Successfully fetched %s nodes of total %s from %s.', count, length(nodes), url)); } if (isEmpty(node_result)) { log('Failed to update subscriptions: no valid node found.'); if (via_proxy !== '1') { log('Starting service...'); init_action('homeproxy', 'start'); } return false; } let added = 0, removed = 0; uci.foreach(uciconfig, ucinode, (cfg) => { /* Nodes created by the user */ if (!cfg.grouphash) return null; /* Empty object - failed to fetch nodes */ if (length(node_cache[cfg.grouphash]) === 0) return null; if (!node_cache[cfg.grouphash] || !node_cache[cfg.grouphash][cfg['.name']]) { uci.delete(uciconfig, cfg['.name']); removed++; log(sprintf('Removing node: %s.', cfg.label || cfg['name'])); } else { map(keys(cfg), (v) => { if (v in node_cache[cfg.grouphash][cfg['.name']]) uci.set(uciconfig, cfg['.name'], v, node_cache[cfg.grouphash][cfg['.name']][v]); else uci.delete(uciconfig, cfg['.name'], v); }); node_cache[cfg.grouphash][cfg['.name']].isExisting = true; } }); for (let nodes in node_result) map(nodes, (node) => { if (node.isExisting) return null; const nameHash = md5(node.label); uci.set(uciconfig, nameHash, 'node'); map(keys(node), (v) => uci.set(uciconfig, nameHash, v, node[v])); added++; log(sprintf('Adding node: %s.', node.label)); }); uci.commit(uciconfig); let need_restart = (via_proxy !== '1'); if (!isEmpty(main_node)) { const first_server = uci.get_first(uciconfig, ucinode); if (first_server) { let main_urltest_nodes; if (main_node === 'urltest') { main_urltest_nodes = filter(uci.get(uciconfig, ucimain, 'main_urltest_nodes'), (v) => { if (!uci.get(uciconfig, v)) { log(sprintf('Node %s is gone, removing from urltest list.', v)); return false; } return true; }); } if ((main_node === 'urltest') ? !length(main_urltest_nodes) : !uci.get(uciconfig, main_node)) { uci.set(uciconfig, ucimain, 'main_node', first_server); uci.commit(uciconfig); need_restart = true; log('Main node is gone, switching to the first node.'); } if (!isEmpty(main_udp_node) && main_udp_node !== 'same') { let main_udp_urltest_nodes; if (main_udp_node === 'urltest') { main_udp_urltest_nodes = filter(uci.get(uciconfig, ucimain, 'main_udp_urltest_nodes'), (v) => { if (!uci.get(uciconfig, v)) { log(sprintf('Node %s is gone, removing from urltest list.', v)); return false; } return true; }); } if ((main_udp_node === 'urltest') ? !length(main_udp_urltest_nodes) : !uci.get(uciconfig, main_udp_node)) { uci.set(uciconfig, ucimain, 'main_udp_node', first_server); uci.commit(uciconfig); need_restart = true; log('Main UDP node is gone, switching to the first node.'); } } } else { uci.set(uciconfig, ucimain, 'main_node', 'nil'); uci.set(uciconfig, ucimain, 'main_udp_node', 'nil'); uci.commit(uciconfig); need_restart = true; log('No available node, disable tproxy.'); } } if (need_restart) { log('Restarting service...'); init_action('homeproxy', 'stop'); init_action('homeproxy', 'start'); } log(sprintf('%s nodes added, %s removed.', added, removed)); log('Successfully updated subscriptions.'); } if (!isEmpty(subscription_urls)) try { call(main); } catch(e) { log('[FATAL ERROR] An error occurred during updating subscriptions:'); log(sprintf('%s: %s', e.type, e.message)); log(e.stacktrace[0].context); log('Restarting service...'); init_action('homeproxy', 'stop'); init_action('homeproxy', 'start'); }
2977094657/BilibiliHistoryFetcher
7,289
routers/daily_count.py
import sqlite3 from datetime import datetime from typing import Optional from fastapi import APIRouter, HTTPException, Query from scripts.utils import load_config, get_output_path router = APIRouter() config = load_config() def get_db(): """获取数据库连接""" db_path = get_output_path(config['db_file']) return sqlite3.connect(db_path) def get_available_years(): """获取数据库中所有可用的年份""" conn = get_db() try: cursor = conn.cursor() cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'bilibili_history_%' ORDER BY name DESC """) years = [] for (table_name,) in cursor.fetchall(): try: year = int(table_name.split('_')[-1]) years.append(year) except (ValueError, IndexError): continue return sorted(years, reverse=True) except sqlite3.Error as e: print(f"获取年份列表时发生错误: {e}") return [] finally: if conn: conn.close() def get_daily_video_count(cursor, table_name: str, date: str) -> dict: """获取指定日期的视频数量统计 Args: cursor: 数据库游标 table_name: 表名 date: 日期字符串,格式为MMDD Returns: dict: 包含视频数量统计的字典 """ try: # 解析日期 month = int(date[:2]) day = int(date[2:]) # 从表名中获取年份 year = int(table_name.split('_')[-1]) # 构建日期范围 start_timestamp = int(datetime(year, month, day, 0, 0, 0).timestamp()) end_timestamp = int(datetime(year, month, day, 23, 59, 59).timestamp()) # 查询总视频数 cursor.execute(f""" SELECT COUNT(*) as total_count, COUNT(DISTINCT author_mid) as unique_authors, AVG(duration) as avg_duration, AVG(CAST(progress AS FLOAT) / CAST(duration AS FLOAT)) as avg_completion_rate, COUNT(CASE WHEN progress >= duration * 0.9 THEN 1 END) as completed_videos FROM {table_name} WHERE view_at >= ? AND view_at <= ? """, (start_timestamp, end_timestamp)) result = cursor.fetchone() total_count, unique_authors, avg_duration, avg_completion_rate, completed_videos = result # 查询分区分布 cursor.execute(f""" SELECT tag_name, COUNT(*) as count FROM {table_name} WHERE view_at >= ? AND view_at <= ? GROUP BY tag_name ORDER BY count DESC LIMIT 5 """, (start_timestamp, end_timestamp)) tag_distribution = {row[0]: row[1] for row in cursor.fetchall()} # 查询UP主分布 cursor.execute(f""" SELECT author_name, COUNT(*) as count FROM {table_name} WHERE view_at >= ? AND view_at <= ? GROUP BY author_mid ORDER BY count DESC LIMIT 5 """, (start_timestamp, end_timestamp)) author_distribution = {row[0]: row[1] for row in cursor.fetchall()} return { "date": f"{year}-{month:02d}-{day:02d}", "total_videos": total_count, "unique_authors": unique_authors, "avg_duration": round(avg_duration if avg_duration else 0, 2), "avg_completion_rate": round(avg_completion_rate * 100 if avg_completion_rate else 0, 2), "completed_videos": completed_videos, "tag_distribution": tag_distribution, "author_distribution": author_distribution, "insights": [ f"这一天你一共观看了 {total_count} 个视频", f"来自 {unique_authors} 个不同的UP主", f"平均时长 {round(avg_duration/60 if avg_duration else 0, 1)} 分钟", f"平均完成率 {round(avg_completion_rate * 100 if avg_completion_rate else 0, 1)}%", f"完整看完 {completed_videos} 个视频" ] } except ValueError as e: raise HTTPException(status_code=400, detail=f"日期格式错误: {str(e)}") @router.get("/daily-count", summary="获取指定日期的观看记录统计") async def get_daily_count( date: str = Query(..., description="日期,格式为MMDD,例如0113表示1月13日"), year: Optional[int] = Query(None, description="年份,不传则使用当前年份") ): """获取指定日期的所有条目统计 Args: date: 日期,格式为MMDD year: 年份,不传则使用当前年份 """ try: # 如果未指定年份,使用当前年份 if year is None: year = datetime.now().year # 构建完整日期 try: month = int(date[:2]) day = int(date[2:]) target_date = datetime(year, month, day) except ValueError: return { "status": "error", "message": "日期格式无效,应为MMDD格式,例如0113表示1月13日" } # 获取当日起止时间戳 start_timestamp = int(datetime(year, month, day).timestamp()) end_timestamp = start_timestamp + 86400 # 加一天的秒数 conn = get_db() cursor = conn.cursor() # 检查年份表是否存在 table_name = f"bilibili_history_{year}" cursor.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name=? """, (table_name,)) if not cursor.fetchone(): return { "status": "error", "message": f"未找到 {year} 年的历史记录数据" } # 查询所有类型的条目数量 query = f""" SELECT business, COUNT(*) as count FROM {table_name} WHERE view_at >= ? AND view_at < ? GROUP BY business """ cursor.execute(query, (start_timestamp, end_timestamp)) results = cursor.fetchall() # 统计当天观看总时长(秒) cursor.execute(f""" SELECT SUM( CASE WHEN progress = -1 THEN duration WHEN progress IS NULL THEN 0 WHEN progress >= 0 THEN CASE WHEN progress > duration THEN duration ELSE progress END ELSE 0 END ) AS total_watch_seconds FROM {table_name} WHERE view_at >= ? AND view_at < ? """, (start_timestamp, end_timestamp)) watch_row = cursor.fetchone() total_watch_seconds = int(watch_row[0]) if watch_row and watch_row[0] is not None else 0 # 计算总数并按类型分类 total_count = 0 type_counts = {} for business, count in results: total_count += count # 使用实际的business类型作为键,如果为空则使用'other' type_key = business if business else 'other' type_counts[type_key] = count return { "status": "success", "data": { "date": target_date.strftime("%Y-%m-%d"), "total_count": total_count, "type_counts": type_counts, "total_watch_seconds": total_watch_seconds } } except sqlite3.Error as e: return {"status": "error", "message": f"数据库错误: {str(e)}"} finally: if conn: conn.close()
2929004360/ruoyi-sign
1,471
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfCategoryService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfCategory; import com.ruoyi.flowable.domain.vo.WfCategoryVo; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import java.util.Collection; import java.util.List; /** * 流程分类Service接口 * * @author fengcheng * @date 2022-01-15 */ public interface IWfCategoryService { /** * 获取流程分类详细信息 * * @param categoryId 分类主键 * @return */ WfCategoryVo queryById(String categoryId); /** * 查询流程分类列表 * * @param category 流程分类对象 * @param pageQuery 分页参数 * @return */ TableDataInfo<WfCategoryVo> queryPageList(WfCategory category, PageQuery pageQuery); /** * 查询全部的流程分类列表 * * @param category 流程分类对象 * @return */ List<WfCategoryVo> queryList(WfCategory category); /** * 新增流程分类 * * @param category 流程分类信息 * @return 结果 */ int insertCategory(WfCategory category); /** * 修改流程分类 * * @param category 流程分类信息 * @return 结果 */ int updateCategory(WfCategory category); /** * 校验并删除数据 * * @param ids 主键集合 * @param isValid 是否校验,true-删除前校验,false-不校验 * @return 结果 */ int deleteWithValidByIds(Collection<String> ids, Boolean isValid); /** * 校验分类编码是否唯一 * * @param category 流程分类 * @return 结果 */ boolean checkCategoryCodeUnique(WfCategory category); }
2929004360/ruoyi-sign
1,266
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfFlowMenuService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfFlowMenu; import java.util.List; /** * 流程菜单Service接口 * * @author fengcheng * @date 2024-07-12 */ public interface IWfFlowMenuService { /** * 查询流程菜单 * * @param flowMenuId 流程菜单主键 * @return 流程菜单 */ public WfFlowMenu selectWfFlowMenuByFlowMenuId(String flowMenuId); /** * 查询流程菜单列表 * * @param wfFlowMenu 流程菜单 * @return 流程菜单集合 */ public List<WfFlowMenu> selectWfFlowMenuList(WfFlowMenu wfFlowMenu); /** * 新增流程菜单 * * @param wfFlowMenu 流程菜单 * @return 结果 */ public int insertWfFlowMenu(WfFlowMenu wfFlowMenu); /** * 修改流程菜单 * * @param wfFlowMenu 流程菜单 * @return 结果 */ public int updateWfFlowMenu(WfFlowMenu wfFlowMenu); /** * 批量删除流程菜单 * * @param flowMenuIds 需要删除的流程菜单主键集合 * @return 结果 */ public int deleteWfFlowMenuByFlowMenuIds(Long[] flowMenuIds); /** * 删除流程菜单信息 * * @param flowMenuId 流程菜单主键 * @return 结果 */ public int deleteWfFlowMenuByFlowMenuId(Long flowMenuId); /** * 获取流程菜单信息 * * @param menuId * @return */ WfFlowMenu getWfFlowMenuInfo(String menuId); }
2929004360/ruoyi-sign
1,042
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfInstanceService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.api.domain.bo.WfTaskBo; import org.flowable.engine.history.HistoricProcessInstance; import java.util.Map; /** * @author fengcheng * @createTime 2022/3/10 00:12 */ public interface IWfInstanceService { /** * 结束流程实例 * * @param vo */ void stopProcessInstance(WfTaskBo vo); /** * 激活或挂起流程实例 * * @param state 状态 * @param instanceId 流程实例ID */ void updateState(Integer state, String instanceId); /** * 删除流程实例ID * * @param instanceId 流程实例ID * @param deleteReason 删除原因 */ void delete(String instanceId, String deleteReason); /** * 根据实例ID查询历史实例数据 * * @param processInstanceId * @return */ HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId); /** * 查询流程详情信息 * @param procInsId 流程实例ID * @param deployId 流程部署ID */ Map<String, Object> queryDetailProcess(String procInsId, String deployId); }
2929004360/ruoyi-sign
1,623
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfModelService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.bo.WfModelBo; import com.ruoyi.flowable.domain.vo.WfModelVo; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import java.util.Collection; import java.util.List; /** * @author fengcheng * @createTime 2022/6/21 9:11 */ public interface IWfModelService { /** * 查询流程模型列表 */ TableDataInfo<WfModelVo> list(WfModelBo modelBo, PageQuery pageQuery); /** * 查询流程模型列表 */ List<WfModelVo> list(WfModelBo modelBo); /** * 查询流程模型列表 */ TableDataInfo<WfModelVo> historyList(WfModelBo modelBo, PageQuery pageQuery); /** * 查询流程模型详情信息 */ WfModelVo getModel(String modelId); /** * 查询流程表单详细信息 */ String queryBpmnXmlById(String modelId); /** * 新增模型信息 * * @param modelBo 流程模型对象 * @return 模型id */ String insertModel(WfModelBo modelBo); /** * 修改模型信息 */ void updateModel(WfModelBo modelBo); /** * 保存流程模型信息 * * @param modelBo 流程模型对象 */ void saveModel(WfModelBo modelBo); /** * 设为最新流程模型 */ void latestModel(String modelId); /** * 删除流程模型 */ void deleteByIds(Collection<String> ids); /** * 部署流程模型 */ boolean deployModel(String modelId); /** * 查询流程模型列表 * * @param modelBo * @return */ List<WfModelVo> selectList(WfModelBo modelBo); /** * 根据菜单id查询流程模型列表 * * @param menuId 菜单id * @return */ List<WfModelVo> getModelByMenuId(String menuId); }
281677160/openwrt-package
2,091
luci-app-beardropper/luasrc/model/cbi/beardropper/setting.lua
m = Map("beardropper", translate("BearDropper"), translate("luci-app-beardropper, the LuCI app built with the elegant firewall rule generation on-the-fly script bearDropper. <br /> <br /> Should you have any questions, please refer to the repo: ")..[[<a href="https://github.com/NateLol/luci-app-bearDropper" target="_blank">luci-app-beardropper</a>]] ) m:chain("luci") m:section(SimpleSection).template = "beardropper/beardropper_status" s = m:section(TypedSection, "beardropper", translate("")) s.anonymous = true s.addremove = false -- TABS s:tab("options", translate("Options")) s:tab("blocked", translate("Blocked IP")) o = s:taboption("options", Flag, "enabled", translate("Enabled")) o.default = 0 -- OPTIONS o = s:taboption("options", ListValue, "defaultMode", translate("Running Mode")) o.default = "follow" o:value("follow", translate("Follow")) o:value("entire", translate("Entire")) o:value("today", translate("Today")) o:value("wipe", translate("Wipe")) o = s:taboption("options", Value, "attemptCount", translate("Attempt Tolerance"), translate("failure attempts from a given IP required to trigger a ban")) o = s:taboption("options", Value, "attemptPeriod", translate("Attempt Cycle"), translate("time period during which attemptCount must be exceeded in order to trigger a ban <br> Format: 1w2d3h4m5s represents 1week 2days 3hours 4minutes 5 seconds")) o = s:taboption("options", Value, "banLength", translate("Ban Period"), translate("how long a ban exist once the attempt threshold is exceeded")) o = s:taboption("options", ListValue, "logLevel", translate("Log Level")) o.default = "1" o:value("0", translate("Silent")) o:value("1", translate("Default")) o:value("2", translate("Verbose")) o:value("3", translate("Debug")) o = s:taboption("blocked", Value, "blocked", translate("Blocked IP List")) o.template = "cbi/tvalue" o.rows = 40 o.wrap = "off" o.readonly = "true" function o.cfgvalue(e, e) return luci.sys.exec("cat /tmp/beardropper.bddb | awk /'=1/'| awk -F '=' '{print $1}' | awk '{print substr($0,6)}' | awk 'gsub(/_/,\":\",$0)'") end return m
2977094657/BilibiliHistoryFetcher
612
.github/ISSUE_TEMPLATE/问题反馈-功能请求.md
--- name: 问题反馈/功能请求 about: 提交问题反馈或新功能请求 title: '' labels: '' assignees: '' --- ## 问题类型 请在适当的选项前打 [x] - [ ] 🐛 Bug报告 - [ ] ✨ 功能请求 - [ ] 📝 文档改进 - [ ] 🔧 性能优化 - [ ] 🧰 技术支持 ## 功能重要程度 请在适当的选项前打 [x] - [ ] 🔴 核心功能(影响主要使用流程) - [ ] 🟠 主要功能(影响重要使用场景) - [ ] 🟡 次要功能(改善用户体验) - [ ] 🟢 增强功能(锦上添花) ## 问题/请求详情 请尽可能详细描述您遇到的问题或需要的功能 ## 复现步骤(针对Bug) 1. 2. 3. ## 当前行为(针对Bug) 描述目前看到的结果 ## 期望行为 描述您期望看到的结果 ## 运行环境 - 操作系统: Windows 10/11, macOS, Linux等 - Python版本: 例如: 3.10.0 - 应用版本: - 完整版/精简版(附上版本号) - 源码(附上你使用的提交hash) - GPU/CUDA版本(如适用): ## 日志/截图 日志位于项目文件夹下的output/logs/年/月/日 贴上相关日志或截图,帮助我们更好地理解问题 ## 额外信息 其他可能有助于解决问题的信息
2977094657/BilibiliHistoryFetcher
9,339
.github/workflows/multi-platform-build.yml
name: 多平台构建 on: workflow_dispatch: # 允许手动触发 push: tags: - 'v*' # 在推送标签时触发,标签格式如 v1.0.0 jobs: build: name: 构建 ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [windows-latest, macos-latest, ubuntu-latest] python-version: ['3.10'] steps: - name: 检出代码 uses: actions/checkout@v4 - name: 设置Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: 安装依赖 run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install pyinstaller pip install yutto - name: 创建logo文件 run: | if [ "${{ matrix.os }}" == "windows-latest" ]; then cp logo.png logo.ico || true elif [ "${{ matrix.os }}" == "macos-latest" ]; then cp logo.png logo.icns || true fi shell: bash - name: 创建虚拟环境 (Windows) if: matrix.os == 'windows-latest' run: | python -m venv .venv .\.venv\Scripts\pip install -r requirements.txt .\.venv\Scripts\pip install pyinstaller .\.venv\Scripts\pip install yutto shell: cmd - name: 创建虚拟环境 (Unix) if: matrix.os != 'windows-latest' run: | python -m venv .venv source .venv/bin/activate pip install -r requirements.txt pip install pyinstaller pip install yutto shell: bash - name: 使用build.py构建应用 (Windows) if: matrix.os == 'windows-latest' run: | .\.venv\Scripts\python build.py shell: cmd - name: 使用build.py构建应用 (Unix) if: matrix.os != 'windows-latest' run: | .venv/bin/python build.py shell: bash - name: 检查构建结果 (调试) run: | echo "当前目录内容:" ls -la echo "检查dist目录是否存在..." if [ ! -d "./dist" ]; then echo "警告: dist目录不存在,创建空目录" mkdir -p ./dist fi echo "dist目录内容:" ls -la ./dist/ echo "检查可能的构建产物目录:" find . -type d -name "*BilibiliHistory*" -o -name "*bili*" | grep -v "__pycache__" shell: bash - name: 创建构建验证报告 run: | # 创建简单版构建报告,确保在任何平台都能运行 echo "# 构建验证报告 (${{ matrix.os }})" > build_report.md echo "构建时间: $(date)" >> build_report.md echo "" >> build_report.md echo "## 系统信息" >> build_report.md echo "- 操作系统: ${{ matrix.os }}" >> build_report.md echo "- Python版本: ${{ matrix.python-version }}" >> build_report.md echo "" >> build_report.md echo "## 构建产物" >> build_report.md if [ -d "./dist" ]; then echo "### dist目录内容:" >> build_report.md echo '```' >> build_report.md ls -la ./dist/ >> build_report.md echo '```' >> build_report.md # 简单检查,使用ls和通配符列出可能的构建产物 echo "### 可能的产物文件:" >> build_report.md echo '```' >> build_report.md # 使用简单的ls列出文件 find ./dist -type d | sort >> build_report.md echo "" >> build_report.md if [ "${{ matrix.os }}" == "windows-latest" ]; then # Windows特定文件 ls -la ./dist/*.exe 2>/dev/null >> build_report.md || echo "未找到.exe文件" >> build_report.md else # 非Windows平台 ls -la ./dist/**/BilibiliHistoryAnalyzer* 2>/dev/null >> build_report.md || echo "未找到主程序文件" >> build_report.md fi echo '```' >> build_report.md # 添加目录树信息 echo "### 目录结构:" >> build_report.md echo '```' >> build_report.md if [ "${{ matrix.os }}" == "macos-latest" ] || [ "${{ matrix.os }}" == "ubuntu-latest" ]; then # macOS和Linux有ls -R命令 ls -R ./dist/ 2>/dev/null >> build_report.md || find ./dist -type f | sort >> build_report.md else # Windows可能没有ls -R find ./dist -type f | sort >> build_report.md fi echo '```' >> build_report.md else echo "❌ 未找到dist目录" >> build_report.md fi echo "" >> build_report.md echo "## 构建状态" >> build_report.md if [ -d "./dist" ] && [ "$(ls -la ./dist/ | wc -l)" -gt 3 ]; then if [ -d "./dist/empty" ]; then echo "❌ 构建失败 (发现empty目录)" >> build_report.md else echo "✅ 构建可能成功" >> build_report.md fi else echo "❌ 构建失败 (dist目录为空或不存在)" >> build_report.md fi cat build_report.md shell: bash - name: 上传构建报告 uses: actions/upload-artifact@v4 with: name: build-report-${{ matrix.os }} path: build_report.md - name: 打包构建结果 run: | echo "当前平台: ${{ matrix.os }}" # 确保dist目录存在 mkdir -p ./dist if [ "${{ matrix.os }}" == "windows-latest" ]; then # Windows平台特殊处理 if [ -d "./dist/BilibiliHistoryAnalyzer" ]; then echo "使用BilibiliHistoryAnalyzer目录" 7z a -tzip BilibiliHistoryFetcher-windows.zip ./dist/BilibiliHistoryAnalyzer else echo "查找可能的输出目录..." find ./dist -type d -maxdepth 1 -print FIRST_DIR=$(find ./dist -type d -maxdepth 1 | grep -v "^./dist$" | head -1) if [ ! -z "$FIRST_DIR" ]; then echo "使用目录: $FIRST_DIR" 7z a -tzip BilibiliHistoryFetcher-windows.zip "$FIRST_DIR" else echo "未找到构建目录,创建空包" mkdir -p ./dist/empty echo "构建失败,此为空包。请检查构建日志。" > ./dist/empty/README.txt 7z a -tzip BilibiliHistoryFetcher-windows.zip ./dist/empty fi fi elif [ "${{ matrix.os }}" == "macos-latest" ]; then # macOS平台 echo "dist目录内容:" ls -la ./dist/ # 查找dist目录下的子目录 DIST_DIR=$(find ./dist -type d -mindepth 1 -maxdepth 1 | head -1) if [ ! -z "$DIST_DIR" ]; then echo "找到输出目录: $DIST_DIR" cd dist && zip -r ../BilibiliHistoryFetcher-macos.zip $(basename "$DIST_DIR") else echo "未找到构建目录,创建空包" mkdir -p ./dist/empty echo "构建失败,此为空包。请检查构建日志。" > ./dist/empty/README.txt cd dist && zip -r ../BilibiliHistoryFetcher-macos.zip empty fi else # Linux平台 echo "dist目录内容:" ls -la ./dist/ # 查找dist目录下的子目录 DIST_DIR=$(find ./dist -type d -mindepth 1 -maxdepth 1 | head -1) if [ ! -z "$DIST_DIR" ]; then echo "找到输出目录: $DIST_DIR" cd dist && zip -r ../BilibiliHistoryFetcher-linux.zip $(basename "$DIST_DIR") else echo "未找到构建目录,创建空包" mkdir -p ./dist/empty echo "构建失败,此为空包。请检查构建日志。" > ./dist/empty/README.txt cd dist && zip -r ../BilibiliHistoryFetcher-linux.zip empty fi fi shell: bash - name: 上传构建产物 uses: actions/upload-artifact@v4 with: name: BilibiliHistoryFetcher-${{ matrix.os }} path: BilibiliHistoryFetcher-*.zip release: name: 创建发布 needs: build runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') steps: - name: 检出代码 uses: actions/checkout@v4 with: fetch-depth: 0 # 获取完整历史记录 - name: 下载所有构建产物 uses: actions/download-artifact@v4 - name: 列出下载的文件 run: find . -type f -name "*.zip" shell: bash - name: 获取上一个标签 id: get_previous_tag run: | # 获取当前标签排序后的前一个标签 CURRENT_TAG="${{ github.ref_name }}" PREVIOUS_TAG=$(git tag --sort=-version:refname | grep -A 1 "^$CURRENT_TAG$" | tail -n 1) # 如果当前标签就是最早的标签,则使用初始提交 if [ "$CURRENT_TAG" = "$PREVIOUS_TAG" ]; then PREVIOUS_TAG=$(git rev-list --max-parents=0 HEAD) fi echo "previous_tag=$PREVIOUS_TAG" >> $GITHUB_OUTPUT echo "找到上一个标签: $PREVIOUS_TAG" shell: bash - name: 生成提交日志 id: generate_changelog run: | echo "正在生成从 ${{ steps.get_previous_tag.outputs.previous_tag }} 到 ${{ github.ref_name }} 的提交日志" # 使用不同的格式直接生成所需格式的提交日志 { echo "## ${{ github.ref_name }} 更新内容" echo "" # 使用git log直接格式化输出,避免复杂的解析 git log "${{ steps.get_previous_tag.outputs.previous_tag }}..${{ github.ref_name }}" --pretty=format:"* %s in [\`%h\`](https://github.com/${{ github.repository }}/commit/%H)" --reverse } > release_notes.md cat release_notes.md # 将生成的提交日志传递给后续步骤 CHANGELOG=$(cat release_notes.md) echo "changelog<<EOF" >> $GITHUB_OUTPUT echo "$CHANGELOG" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT shell: bash - name: 创建GitHub发布 uses: softprops/action-gh-release@v2 with: files: | ./BilibiliHistoryFetcher-windows-latest/BilibiliHistoryFetcher-windows.zip ./BilibiliHistoryFetcher-macos-latest/BilibiliHistoryFetcher-macos.zip ./BilibiliHistoryFetcher-ubuntu-latest/BilibiliHistoryFetcher-linux.zip name: Release ${{ github.ref_name }} body: ${{ steps.generate_changelog.outputs.changelog }} env: GITHUB_TOKEN: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
2929004360/ruoyi-sign
1,662
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfModelProcdefService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfModelProcdef; import java.util.List; /** * 模型部署Service接口 * * @author fengcheng * @date 2024-07-11 */ public interface IWfModelProcdefService { /** * 查询模型部署 * * @param modelId 模型部署主键 * @return 模型部署 */ public WfModelProcdef selectWfModelProcdefByModelId(String modelId); /** * 查询模型部署列表 * * @param wfModelProcdef 模型部署 * @return 模型部署集合 */ public List<WfModelProcdef> selectWfModelProcdefList(WfModelProcdef wfModelProcdef); /** * 新增模型部署 * * @param wfModelProcdef 模型部署 * @return 结果 */ public int insertWfModelProcdef(WfModelProcdef wfModelProcdef); /** * 修改模型部署 * * @param wfModelProcdef 模型部署 * @return 结果 */ public int updateWfModelProcdef(WfModelProcdef wfModelProcdef); /** * 批量删除模型部署 * * @param modelIds 需要删除的模型部署主键集合 * @return 结果 */ public int deleteWfModelProcdefByModelIds(String[] modelIds); /** * 删除模型部署信息 * * @param modelId 模型部署主键 * @return 结果 */ public int deleteWfModelProcdefByModelId(String modelId); /** * 根据模型id列表查询模型部署id * * @param modelIdList * @return */ List<String> selectWfModelProcdefListByModelIdList(List<String> modelIdList); /** * 根据部署id删除模型部署信息 * * @param deployId * @return */ int deleteWfModelProcdefByProcdefId(String deployId); /** * 根据部署id查询模型部署信息 * * @param procdefId * @return */ WfModelProcdef selectWfModelProcdefByProcdefId(String procdefId); }
281677160/openwrt-package
3,862
luci-app-beardropper/po/zh_Hans/beardropper.po
bearDropper#: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:36 msgid "Attempt Cycle" msgstr "尝试登录时间段" msgid "Setting" msgstr "设置" msgid "Log" msgstr "日志" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:34 msgid "Attempt Tolerance" msgstr "最大尝试登录次数" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:38 msgid "Ban Period" msgstr "封禁IP时长" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/controller/bearDropper.lua:7 #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:7 msgid "BearDropper" msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:20 msgid "Blocked IP" msgstr "屏蔽列表" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:52 msgid "Blocked IP List" msgstr "已屏蔽IP列表" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/view/bearDropper/status.htm:20 msgid "Collecting data..." msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:45 msgid "Debug" msgstr "调试" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:43 msgid "Default" msgstr "默认" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:22 msgid "Enabled" msgstr "启用" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:29 msgid "Entire" msgstr "已有记录" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:28 msgid "Follow" msgstr "后台监控" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:40 msgid "Log Level" msgstr "日志等级" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/view/bearDropper/status.htm:10 msgid "NOT RUNNING" msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:19 msgid "Options" msgstr "选项" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/view/bearDropper/status.htm:7 msgid "RUNNING" msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:26 msgid "Running Mode" msgstr "运行模式" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:42 msgid "Silent" msgstr "安静" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:30 msgid "Today" msgstr "仅今日" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:44 msgid "Verbose" msgstr "详细" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:31 msgid "Wipe" msgstr "清除所有" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:34 msgid "failure attempts from a given IP required to trigger a ban" msgstr "尝试登录超过设定值次数的IP将被封禁" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:38 msgid "how long a ban exist once the attempt threshold is exceeded" msgstr "IP将被封禁设定的时间" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:8 msgid "" "luci-app-beardropper, the LuCI app built with the elegant firewall rule " "generation on-the-fly script bearDropper. <br /> <br /> Should you have any " "questions, please refer to the repo:" msgstr "" "luci-app-beardropper, 是一款能够在开启公网访问之后对潜在的ssh attack进行防御" "的脚本. <br /> <br /> 如果你在使用中有任何问题,请到项目中提问: " #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:36 msgid "" "time period during which attemptCount must be exceeded in order to trigger a " "ban <br> Format: 1w2d3h4m5s represents 1week 2days 3hours 4minutes 5 seconds" msgstr "" "在设定的时间段内连续尝试失败 <br> 格式:1w2d3h4m5s代表1周2天3小时4分5秒"
2929004360/ruoyi-sign
3,660
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfProcessService.java
package com.ruoyi.flowable.service; import com.ruoyi.common.core.domain.R; import com.ruoyi.flowable.core.FormConf; import com.ruoyi.flowable.core.domain.ProcessQuery; import com.ruoyi.flowable.domain.bo.DdToBpmn; import com.ruoyi.flowable.domain.bo.ResubmitProcess; import com.ruoyi.flowable.domain.vo.WfDefinitionVo; import com.ruoyi.flowable.domain.vo.WfDetailVo; import com.ruoyi.flowable.domain.vo.WfTaskVo; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import org.flowable.engine.runtime.ProcessInstance; import java.util.List; import java.util.Map; /** * 流程服务接口 * * @author fengcheng * @createTime 2022/3/24 18:57 */ public interface IWfProcessService { /** * 查询可发起流程列表 * * @param processQuery 查询参数 * @return */ List<WfDefinitionVo> selectPageStartProcessList(ProcessQuery processQuery); /** * 查询可发起流程列表 */ List<WfDefinitionVo> selectStartProcessList(ProcessQuery processQuery); /** * 查询我的流程列表 * * @param pageQuery 分页参数 */ TableDataInfo<WfTaskVo> selectPageOwnProcessList(ProcessQuery processQuery, PageQuery pageQuery); /** * 查询我的流程列表 */ List<WfTaskVo> selectOwnProcessList(ProcessQuery processQuery); /** * 查询代办任务列表 * * @param pageQuery 分页参数 */ TableDataInfo<WfTaskVo> selectPageTodoProcessList(ProcessQuery processQuery, PageQuery pageQuery); /** * 查询代办任务列表 */ List<WfTaskVo> selectTodoProcessList(ProcessQuery processQuery); /** * 查询待签任务列表 * * @param pageQuery 分页参数 */ TableDataInfo<WfTaskVo> selectPageClaimProcessList(ProcessQuery processQuery, PageQuery pageQuery); /** * 查询待签任务列表 */ List<WfTaskVo> selectClaimProcessList(ProcessQuery processQuery); /** * 查询已办任务列表 * * @param pageQuery 分页参数 */ TableDataInfo<WfTaskVo> selectPageFinishedProcessList(ProcessQuery processQuery, PageQuery pageQuery); /** * 查询已办任务列表 */ List<WfTaskVo> selectFinishedProcessList(ProcessQuery processQuery); /** * 查询流程部署关联表单信息 * * @param definitionId 流程定义ID * @param deployId 部署ID */ FormConf selectFormContent(String definitionId, String deployId, String procInsId); /** * 启动流程实例 * * @param procDefId 流程定义ID * @param variables 扩展参数 * @return */ ProcessInstance startProcessByDefId(String procDefId, Map<String, Object> variables); /** * 通过DefinitionKey启动流程 * * @param procDefKey 流程定义Key * @param variables 扩展参数 */ void startProcessByDefKey(String procDefKey, Map<String, Object> variables); /** * 删除流程实例 */ void deleteProcessByIds(String[] instanceIds); /** * 读取xml文件 * * @param processDefId 流程定义ID */ String queryBpmnXmlById(String processDefId); /** * 查询流程任务详情信息 * * @param procInsId 流程实例ID * @param taskId 任务ID * @param formType 表单类型 */ WfDetailVo queryProcessDetail(String procInsId, String taskId, String formType); /** * 根据钉钉流程json转flowable的bpmn的xml格式 * * @param ddToBpmn * @return */ R<String> dingdingToBpmn(DdToBpmn ddToBpmn); /** * 根据菜单id获取可发起列表 * * @param menuId * @return */ List<WfDefinitionVo> getStartList(String menuId); /** * 重新发起流程实例 * * @param resubmitProcess 重新发起 */ void resubmitProcess(ResubmitProcess resubmitProcess); /** * 查询流程是否结束 * * @param procInsId * @param */ boolean processIsCompleted(String procInsId); }
2929004360/ruoyi-sign
1,087
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfIconService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfIcon; import java.util.List; /** * 流程图标Service接口 * * @author fengcheng * @date 2024-07-09 */ public interface IWfIconService { /** * 查询流程图标 * * @param deploymentId 流程图标主键 * @return 流程图标 */ public WfIcon selectWfIconByDeploymentId(String deploymentId); /** * 查询流程图标列表 * * @param wfIcon 流程图标 * @return 流程图标集合 */ public List<WfIcon> selectWfIconList(WfIcon wfIcon); /** * 新增流程图标 * * @param wfIcon 流程图标 * @return 结果 */ public int insertWfIcon(WfIcon wfIcon); /** * 修改流程图标 * * @param wfIcon 流程图标 * @return 结果 */ public int updateWfIcon(WfIcon wfIcon); /** * 批量删除流程图标 * * @param deploymentIds 需要删除的流程图标主键集合 * @return 结果 */ public int deleteWfIconByDeploymentIds(String[] deploymentIds); /** * 删除流程图标信息 * * @param deploymentId 流程图标主键 * @return 结果 */ public int deleteWfIconByDeploymentId(String deploymentId); }
2929004360/ruoyi-sign
2,829
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfTaskService.java
package com.ruoyi.flowable.service; import com.ruoyi.common.core.domain.R; import com.ruoyi.flowable.api.domain.bo.WfTaskBo; import me.chanjar.weixin.common.error.WxErrorException; import org.flowable.bpmn.model.FlowElement; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.task.api.Task; import java.io.InputStream; import java.util.List; import java.util.Map; /** * 工作流任务接口 * * @author fengcheng * @createTime 2022/3/10 00:12 */ public interface IWfTaskService { /** * 审批任务 * * @param task 请求实体参数 */ void complete(WfTaskBo task); /** * 驳回任务 * * @param taskBo */ void taskReject(WfTaskBo taskBo); /** * 退回任务 * * @param bo 请求实体参数 */ void taskReturn(WfTaskBo bo); /** * 获取所有可回退的节点 * * @param bo * @return */ List<FlowElement> findReturnTaskList(WfTaskBo bo); /** * 删除任务 * * @param bo 请求实体参数 */ void deleteTask(WfTaskBo bo); /** * 认领/签收任务 * * @param bo 请求实体参数 */ void claim(WfTaskBo bo); /** * 取消认领/签收任务 * * @param bo 请求实体参数 */ void unClaim(WfTaskBo bo); /** * 委派任务 * * @param bo 请求实体参数 */ void delegateTask(WfTaskBo bo); /** * 转办任务 * * @param bo 请求实体参数 */ void transferTask(WfTaskBo bo); /** * 取消申请 * * @param bo * @return */ void stopProcess(WfTaskBo bo); /** * 撤回流程 * * @param bo * @return */ void revokeProcess(WfTaskBo bo); /** * 获取流程过程图 * * @param processId * @return */ InputStream diagram(String processId); /** * 获取流程变量 * * @param taskId 任务ID * @return 流程变量 */ Map<String, Object> getProcessVariables(String taskId); /** * 启动第一个任务 * * @param processInstance 流程实例 * @param variables 流程参数 */ void startFirstTask(ProcessInstance processInstance, Map<String, Object> variables); /** * 加签任务 * * @param bo * @return */ void addSignTask(WfTaskBo bo); /** * 多实例加签任务 * * @param bo */ void multiInstanceAddSign(WfTaskBo bo); /** * 收回流程,收回后发起人可以重新编辑表单发起流程,对于自定义业务就是原有任务都删除,重新进行申请 * * @param bo * @return */ R recallProcess(WfTaskBo bo); /** * 拒绝任务 * * @param taskBo */ void taskRefuse(WfTaskBo taskBo); /** * 跳转任务 * * @param bo */ void taskJump(WfTaskBo bo); /** * 用户任务列表,作为跳转任务使用 * * @param bo * @return */ R userTaskList(WfTaskBo bo); /** * 监听任务创建事件 * * @param task 任务实体 */ void updateTaskStatusWhenCreated(Task task) throws WxErrorException; }
281677160/openwrt-package
3,862
luci-app-beardropper/po/zh_Hant/beardropper.po
bearDropper#: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:36 msgid "Attempt Cycle" msgstr "嘗試登錄時間段" msgid "Setting" msgstr "設置" msgid "Log" msgstr "日誌" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:34 msgid "Attempt Tolerance" msgstr "最大嘗試登錄次數" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:38 msgid "Ban Period" msgstr "封禁IP時長" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/controller/bearDropper.lua:7 #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:7 msgid "BearDropper" msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:20 msgid "Blocked IP" msgstr "屏蔽列表" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:52 msgid "Blocked IP List" msgstr "已屏蔽IP列表" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/view/bearDropper/status.htm:20 msgid "Collecting data..." msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:45 msgid "Debug" msgstr "調試" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:43 msgid "Default" msgstr "默認" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:22 msgid "Enabled" msgstr "啟用" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:29 msgid "Entire" msgstr "已有記錄" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:28 msgid "Follow" msgstr "後臺監控" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:40 msgid "Log Level" msgstr "日誌等級" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/view/bearDropper/status.htm:10 msgid "NOT RUNNING" msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:19 msgid "Options" msgstr "選項" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/view/bearDropper/status.htm:7 msgid "RUNNING" msgstr "" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:26 msgid "Running Mode" msgstr "運行模式" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:42 msgid "Silent" msgstr "安靜" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:30 msgid "Today" msgstr "僅今日" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:44 msgid "Verbose" msgstr "詳細" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:31 msgid "Wipe" msgstr "清除所有" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:34 msgid "failure attempts from a given IP required to trigger a ban" msgstr "嘗試登錄超過設定值次數的IP將被封禁" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:38 msgid "how long a ban exist once the attempt threshold is exceeded" msgstr "IP將被封禁設定的時間" #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:8 msgid "" "luci-app-beardropper, the LuCI app built with the elegant firewall rule " "generation on-the-fly script bearDropper. <br /> <br /> Should you have any " "questions, please refer to the repo:" msgstr "" "luci-app-beardropper, 是壹款能夠在開啟公網訪問之後對潛在的ssh attack進行防禦" "的腳本. <br /> <br /> 如果妳在使用中有任何問題,請到項目中提問: " #: ../../package/feeds/luci/luci-app-beardropper/luasrc/model/cbi/bearDropper/setting.lua:36 msgid "" "time period during which attemptCount must be exceeded in order to trigger a " "ban <br> Format: 1w2d3h4m5s represents 1week 2days 3hours 4minutes 5 seconds" msgstr "" "在設定的時間段內連續嘗試失敗 <br> 格式:1w2d3h4m5s代表1周2天3小時4分5秒"
2929004360/ruoyi-sign
1,047
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfCopyService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.bo.WfCopyBo; import com.ruoyi.flowable.api.domain.bo.WfTaskBo; import com.ruoyi.flowable.domain.vo.WfCopyVo; import com.ruoyi.flowable.page.PageQuery; import com.ruoyi.flowable.page.TableDataInfo; import java.util.List; /** * 流程抄送Service接口 * * @author fengcheng * @date 2022-05-19 */ public interface IWfCopyService { /** * 查询流程抄送 * * @param copyId 流程抄送主键 * @return 流程抄送 */ WfCopyVo queryById(Long copyId); /** * 查询流程抄送列表 * * @param wfCopy 流程抄送 * @return 流程抄送集合 */ TableDataInfo<WfCopyVo> selectPageList(WfCopyBo wfCopy, PageQuery pageQuery); /** * 查询流程抄送列表 * * @param wfCopy 流程抄送 * @return 流程抄送集合 */ List<WfCopyVo> selectList(WfCopyBo wfCopy); /** * 抄送 * @param taskBo * @return */ Boolean makeCopy(WfTaskBo taskBo); /** * 删除抄送列表 * * @param copyIds 抄送id * @return */ void deleteCopy(String[] copyIds); }
2929004360/ruoyi-sign
1,045
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfFormService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.bo.WfFormBo; import com.ruoyi.flowable.domain.vo.WfFormVo; import java.util.Collection; import java.util.List; /** * 表单 * * @author fengcheng * @createTime 2022/3/7 22:07 */ public interface IWfFormService { /** * 查询流程表单 * * @param formId 流程表单ID * @return 流程表单 */ WfFormVo queryById(String formId); /** * 查询流程表单列表 * * @param bo 流程表单 * @return 流程表单集合 */ List<WfFormVo> queryPageList(WfFormBo bo); /** * 查询流程表单列表 * * @param bo 流程表单 * @return 流程表单集合 */ List<WfFormVo> queryList(WfFormBo bo); /** * 新增流程表单 * * @param bo 流程表单 * @return 结果 */ int insertForm(WfFormBo bo); /** * 修改流程表单 * * @param bo 流程表单 * @return 结果 */ int updateForm(WfFormBo bo); /** * 批量删除流程表单 * * @param formIds 需要删除的流程表单ID * @return 结果 */ Boolean deleteWithValidByIds(Collection<String> formIds); }
2929004360/ruoyi-sign
1,704
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfModelAssociationTemplateService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfModelAssociationTemplate; import java.util.List; /** * 模型关联模板Service接口 * * @author fengcheng * @date 2024-07-23 */ public interface IWfModelAssociationTemplateService { /** * 查询模型关联模板 * * @param modelTemplateId 模型关联模板主键 * @return 模型关联模板 */ public WfModelAssociationTemplate selectWfModelAssociationTemplateByModelTemplateId(String modelTemplateId); /** * 查询模型关联模板列表 * * @param wfModelAssociationTemplate 模型关联模板 * @return 模型关联模板集合 */ public List<WfModelAssociationTemplate> selectWfModelAssociationTemplateList(WfModelAssociationTemplate wfModelAssociationTemplate); /** * 新增模型关联模板 * * @param wfModelAssociationTemplate 模型关联模板 * @return 结果 */ public int insertWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate); /** * 修改模型关联模板 * * @param wfModelAssociationTemplate 模型关联模板 * @return 结果 */ public int updateWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate); /** * 批量删除模型关联模板 * * @param modelTemplateIds 需要删除的模型关联模板主键集合 * @return 结果 */ public int deleteWfModelAssociationTemplateByModelTemplateIds(String[] modelTemplateIds); /** * 删除模型关联模板信息 * * @param modelTemplateId 模型关联模板主键 * @return 结果 */ public int deleteWfModelAssociationTemplateByModelTemplateId(String modelTemplateId); /** * 删除模型关联模板信息 * * @param wfModelAssociationTemplate */ int deleteWfModelAssociationTemplate(WfModelAssociationTemplate wfModelAssociationTemplate); }
281677160/openwrt-package
19,149
luci-app-beardropper/root/usr/sbin/beardropper
#!/bin/ash # # beardropper - dropbear log parsing ban agent for OpenWRT (Chaos Calmer rewrite of dropBrute.sh) # http://github.com/robzr/bearDropper -- Rob Zwissler 11/2015 # # - lightweight, no dependencies, busybox ash + native OpenWRT commands # - uses uci for configuration, overrideable via command line arguments # - runs continuously in background (via init script) or periodically (via cron) # - uses BIND time shorthand, ex: 1w5d3h1m8s is 1 week, 5 days, 3 hours, 1 minute, 8 seconds # - Whitelist IP or CIDR entries (TBD) in uci config file # - Records state file to tmpfs and intelligently syncs to persistent storage (can disable) # - Persistent sync routines are optimized to avoid excessive writes (persistentStateWritePeriod) # - Every run occurs in one of the following modes. If not specified, interval mode (24 hours) is # the default when not specified (the init script specifies follow mode via command line) # # "follow" mode follows syslog to process entries as they happen; generally launched via init # script. Responds the fastest, runs the most efficiently, but is always in memory. # "interval" mode only processes entries going back the specified interval; requires # more processing than today mode, but responds more accurately. Use with cron. # "today" mode looks at log entries from the day it is being run, simple and lightweight, # generally run from cron periodically (same simplistic behavior as dropBrute.sh) # "entire" mode runs through entire contents of the syslog ring buffer # "wipe" mode tears down the firewall rules and removes the state files # Load UCI config variable, or use default if not set # Args: $1 = variable name (also uci option name), $2 = default_value uciSection='beardropper.@[0]' uciLoadVar () { local getUci getUci=`uci -q get ${uciSection}."$1"` || getUci="$2" eval $1=\'$getUci\'; } uciLoad() { local tFile=`mktemp` delim=" " [ "$1" = -d ] && { delim="$2"; shift 2; } uci -q -d"$delim" get "$uciSection.$1" 2>/dev/null >$tFile if [ $? = 0 ] ; then sed -e s/^\'// -e s/\'$// <$tFile else while [ -n "$2" ]; do echo $2; shift; done fi rm -f $tFile } # Common config variables - edit these in /etc/config/beardropper # or they can be overridden at runtime with command line options # uciLoadVar defaultMode entire uciLoadVar enabled 0 uciLoadVar attemptCount 10 uciLoadVar attemptPeriod 12h uciLoadVar banLength 1w uciLoadVar logLevel 1 uciLoadVar logFacility authpriv.notice uciLoadVar persistentStateWritePeriod -1 uciLoadVar fileStateType bddb uciLoadVar fileStateTempPrefix /tmp/beardropper uciLoadVar fileStatePersistPrefix /etc/beardropper firewallHookChains="`uciLoad -d \ firewallHookChain input_wan_rule:1 forwarding_wan_rule:1`" uciLoadVar firewallTarget DROP # Not commonly changed, but changeable via uci or cmdline (primarily # to enable multiple parallel runs with different parameters) uciLoadVar firewallChain beardropper # Advanced variables, changeable via uci only (no cmdline), it is # unlikely that these will need to be changed, but just in case... # uciLoadVar syslogTag "beardropper[$$]" # how often to attempt to expire bans when in follow mode uciLoadVar followModeCheckInterval 30m uciLoadVar cmdLogread 'logread' # for tuning, ex: "logread -l250" uciLoadVar cmdLogreadEba 'logread' # for "Exit before auth:" backscanning uciLoadVar formatLogDate '%b %e %H:%M:%S %Y' # used to convert syslog dates uciLoadVar formatTodayLogDateRegex '^%a %b %e ..:..:.. %Y' # filter for today mode # Begin functions # # Clear bddb entries from environment bddbClear () { local bddbVar for bddbVar in `set | egrep '^bddb_[0-9_]*=' | cut -f1 -d= | xargs echo -n` ; do eval unset $bddbVar ; done bddbStateChange=1 } # Returns count of unique IP entries in environment bddbCount () { set | egrep '^bddb_[0-9_]*=' | wc -l ; } # Loads existing bddb file into environment # Arg: $1 = file, $2 = type (bddb/bddbz), $3 = bddbLoad () { local loadFile="$1.$2" fileType="$2" if [ "$fileType" = bddb -a -f "$loadFile" ] ; then . "$loadFile" elif [ "$fileType" = bddbz -a -f "$loadFile" ] ; then local tmpFile="`mktemp`" zcat $loadFile > "$tmpFile" . "$tmpFile" rm -f "$tmpFile" fi bddbStateChange=0 } # Saves environment bddb entries to file, Arg: $1 = file to save in bddbSave () { local saveFile="$1.$2" fileType="$2" if [ "$fileType" = bddb ] ; then set | egrep '^bddb_[0-9_]*=' | sed s/\'//g > "$saveFile" elif [ "$fileType" = bddbz ] ; then set | egrep '^bddb_[0-9_]*=' | sed s/\'//g | gzip -c > "$saveFile" fi bddbStateChange=0 } # Set bddb record status=1, update ban time flag with newest # Args: $1=IP Address $2=timeFlag bddbEnableStatus () { local record=`echo $1 | sed -e 's/\./_/g' -e 's/^/bddb_/'` local newestTime=`bddbGetTimes $1 | sed 's/.* //' | xargs echo $2 | tr \ '\n' | sort -n | tail -1 ` eval $record="1,$newestTime" bddbStateChange=1 } # Args: $1=IP Address bddbGetStatus () { bddbGetRecord $1 | cut -d, -f1 } # Args: $1=IP Address bddbGetTimes () { bddbGetRecord $1 | cut -d, -f2- } # Args: $1 = IP address, $2 [$3 ...] = timestamp (seconds since epoch) bddbAddRecord () { local ip="`echo "$1" | tr . _`" ; shift local newEpochList="$@" status="`eval echo \\\$bddb_$ip | cut -f1 -d,`" local oldEpochList="`eval echo \\\$bddb_$ip | cut -f2- -d, | tr , \ `" local epochList=`echo $oldEpochList $newEpochList | xargs -n 1 echo | sort -un | xargs echo -n | tr \ ,` [ -z "$status" ] && status=0 eval "bddb_$ip"\=\"$status,$epochList\" bddbStateChange=1 } # Args: $1 = IP address bddbRemoveRecord () { local ip="`echo "$1" | tr . _`" eval unset bddb_$ip bddbStateChange=1 } # Returns all IPs (not CIDR) present in records bddbGetAllIPs () { local ipRaw record set | egrep '^bddb_[0-9_]*=' | tr \' \ | while read record ; do ipRaw=`echo $record | cut -f1 -d= | sed 's/^bddb_//'` if [ `echo $ipRaw | tr _ \ | wc -w` -eq 4 ] ; then echo $ipRaw | tr _ . fi done } # retrieve single IP record, Args: $1=IP bddbGetRecord () { local record record=`echo $1 | sed -e 's/\./_/g' -e 's/^/bddb_/'` eval echo \$$record } isValidBindTime () { echo "$1" | egrep -q '^[0-9]+$|^([0-9]+[wdhms]?)+$' ; } # expands Bind time syntax into seconds (ex: 3w6d23h59m59s), Arg: $1=time string expandBindTime () { isValidBindTime "$1" || { logLine 0 "Error: Invalid time specified ($1)" >&2 ; exit 254 ; } echo $((`echo "$1" | sed -e 's/w+*/*7d+/g' -e 's/d+*/*24h+/g' -e 's/h+*/*60m+/g' -e 's/m+*/*60+/g' \ -e s/s//g -e s/+\$//`)) } # Args: $1 = loglevel, $2 = info to log logLine () { [ $1 -gt $logLevel ] && return shift if [ "$logFacility" = "stdout" ] ; then echo "$@" elif [ "$logFacility" = "stderr" ] ; then echo "$@" >&2 else logger -t "$syslogTag" -p "$logFacility" "$@" fi } # extra validation, fails safe. Args: $1=log line getLogTime () { local logDateString=`echo "$1" | sed -n \ 's/^[A-Z][a-z]* \([A-Z][a-z]* *[0-9][0-9]* *[0-9][0-9]*:[0-9][0-9]:[0-9][0-9] [0-9][0-9]*\) .*$/\1/p'` date -d"$logDateString" -D"$formatLogDate" +%s || logLine 1 \ "Error: logDateString($logDateString) malformed line ($1)" } # extra validation, fails safe. Args: $1=log line getLogIP () { local logLine="$1" local ebaPID=`echo "$logLine" | sed -n 's/^.*authpriv.info \(dropbear\[[0-9]*\]:\) Exit before auth:.*/\1/p'` [ -n "$ebaPID" ] && logLine=`$cmdLogreadEba | fgrep "${ebaPID} Child connection from "` echo "$logLine" | sed -n 's/^.*[^0-9]\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*$/\1/p' } # Args: $1=IP unBanIP () { if iptables -C $firewallChain -s $ip -j "$firewallTarget" 2>/dev/null ; then logLine 1 "Removing ban rule for IP $ip from iptables" iptables -D $firewallChain -s $ip -j "$firewallTarget" else logLine 3 "unBanIP() Ban rule for $ip not present in iptables" fi } # Args: $1=IP banIP () { local ip="$1" x chain position if ! iptables -nL $firewallChain >/dev/null 2>/dev/null ; then logLine 1 "Creating iptables chain $firewallChain" iptables -N $firewallChain fi for x in $firewallHookChains ; do chain="${x%:*}" ; position="${x#*:}" if [ $position -ge 0 ] && ! iptables -C $chain -j $firewallChain 2>/dev/null ; then logLine 1 "Inserting hook into iptables chain $chain" if [ $position = 0 ] ; then iptables -A $chain -j $firewallChain else iptables -I $chain $position -j $firewallChain fi ; fi done if ! iptables -C $firewallChain -s $ip -j "$firewallTarget" 2>/dev/null ; then logLine 1 "Inserting ban rule for IP $ip into iptables chain $firewallChain" iptables -A $firewallChain -s $ip -j "$firewallTarget" else logLine 3 "banIP() rule for $ip already present in iptables chain" fi } wipeFirewall () { local x chain position for x in $firewallHookChains ; do chain="${x%:*}" ; position="${x#*:}" if [ $position -ge 0 ] ; then if iptables -C $chain -j $firewallChain 2>/dev/null ; then logLine 1 "Removing hook from iptables chain $chain" iptables -D $chain -j $firewallChain fi ; fi done if iptables -nL $firewallChain >/dev/null 2>/dev/null ; then logLine 1 "Flushing and removing iptables chain $firewallChain" iptables -F $firewallChain 2>/dev/null iptables -X $firewallChain 2>/dev/null fi } # review state file for expired records - we could add the bantime to # the rule via --comment but I can't think of a reason why that would # be necessary unless there is a bug in the expiration logic. The # state db should be more resiliant than the firewall in practice. # bddbCheckStatusAll () { local now=`date +%s` bddbGetAllIPs | while read ip ; do if [ `bddbGetStatus $ip` -eq 1 ] ; then logLine 3 "bddbCheckStatusAll($ip) testing banLength:$banLength + bddbGetTimes:`bddbGetTimes $ip` vs. now:$now" if [ $((banLength + `bddbGetTimes $ip`)) -lt $now ] ; then logLine 1 "Ban expired for $ip, removing from iptables" unBanIP $ip bddbRemoveRecord $ip else logLine 3 "bddbCheckStatusAll($ip) not expired yet" banIP $ip fi elif [ `bddbGetStatus $ip` -eq 0 ] ; then local times=`bddbGetTimes $ip | tr , \ ` local timeCount=`echo $times | wc -w` local lastTime=`echo $times | cut -d\ -f$timeCount` if [ $((lastTime + attemptPeriod)) -lt $now ] ; then bddbRemoveRecord $ip fi ; fi saveState done loadState } # Only used when status is already 0 and possibly going to 1, Args: $1=IP bddbEvaluateRecord () { local ip=$1 firstTime lastTime local times=`bddbGetRecord $1 | cut -d, -f2- | tr , \ ` local timeCount=`echo $times | wc -w` local didBan=0 # 1: not enough attempts => do nothing and exit # 2: attempts exceed threshold in time period => ban # 3: attempts exceed threshold but time period is too long => trim oldest time, recalculate while [ $timeCount -ge $attemptCount ] ; do firstTime=`echo $times | cut -d\ -f1` lastTime=`echo $times | cut -d\ -f$timeCount` timeDiff=$((lastTime - firstTime)) logLine 3 "bddbEvaluateRecord($ip) count=$timeCount timeDiff=$timeDiff/$attemptPeriod" if [ $timeDiff -le $attemptPeriod ] ; then bddbEnableStatus $ip $lastTime logLine 2 "bddbEvaluateRecord($ip) exceeded ban threshold, adding to iptables" banIP $ip didBan=1 fi times=`echo $times | cut -d\ -f2-` timeCount=`echo $times | wc -w` done [ $didBan = 0 ] && logLine 2 "bddbEvaluateRecord($ip) does not exceed threshhold, skipping" } # Reads filtered log line and evaluates for action Args: $1=log line processLogLine () { local time=`getLogTime "$1"` local ip=`getLogIP "$1"` local status="`bddbGetStatus $ip`" if [ "$status" = -1 ] ; then logLine 2 "processLogLine($ip,$time) IP is whitelisted" elif [ "$status" = 1 ] ; then if [ "`bddbGetTimes $ip`" -ge $time ] ; then logLine 2 "processLogLine($ip,$time) already banned, ban timestamp already equal or newer" else logLine 2 "processLogLine($ip,$time) already banned, updating ban timestamp" bddbEnableStatus $ip $time fi banIP $ip elif [ -n "$ip" -a -n "$time" ] ; then bddbAddRecord $ip $time logLine 2 "processLogLine($ip,$time) Added record, comparing" bddbEvaluateRecord $ip else logLine 1 "processLogLine($ip,$time) malformed line ($1)" fi } # Args, $1=-f to force a persistent write (unless lastPersistentStateWrite=-1) saveState () { local forcePersistent=0 [ "$1" = "-f" ] && forcePersistent=1 if [ $bddbStateChange -gt 0 ] ; then logLine 3 "saveState() saving to temp state file" bddbSave "$fileStateTempPrefix" "$fileStateType" logLine 3 "saveState() now=`date +%s` lPSW=$lastPersistentStateWrite pSWP=$persistentStateWritePeriod fP=$forcePersistent" fi if [ $persistentStateWritePeriod -gt 1 ] || [ $persistentStateWritePeriod -eq 0 -a $forcePersistent -eq 1 ] ; then if [ $((`date +%s` - lastPersistentStateWrite)) -ge $persistentStateWritePeriod ] || [ $forcePersistent -eq 1 ] ; then if [ ! -f "$fileStatePersist" ] || ! cmp -s "$fileStateTemp" "$fileStatePersist" ; then logLine 2 "saveState() writing to persistent state file" bddbSave "$fileStatePersistPrefix" "$fileStateType" lastPersistentStateWrite="`date +%s`" fi ; fi ; fi } loadState () { bddbClear bddbLoad "$fileStatePersistPrefix" "$fileStateType" bddbLoad "$fileStateTempPrefix" "$fileStateType" logLine 2 "loadState() loaded `bddbCount` entries" } printUsage () { cat <<-_EOF_ Usage: beardropper [-m mode] [-a #] [-b #] [-c ...] [-C ...] [-f ...] [-l #] [-j ...] [-p #] [-P #] [-s ...] Running Modes (-m) (def: $defaultMode) follow constantly monitors log entire processes entire log contents today processes log entries from same day only # interval mode, specify time string or seconds wipe wipe state files, unhook and remove firewall chain Options -a # attempt count before banning (def: $attemptCount) -b # ban length once attempts hit threshold (def: $banLength) -c ... firewall chain to record bans (def: $firewallChain) -C ... firewall chains/positions to hook into (def: $firewallHookChains) -f ... log facility (syslog facility or stdout/stderr) (def: $logFacility) -j ... firewall target (def: $firewallTarget) -l # log level - 0=off, 1=standard, 2=verbose (def: $logLevel) -p # attempt period which attempt counts must happen in (def: $attemptPeriod) -P # persistent state file write period (def: $persistentStateWritePeriod) -s ... persistent state file prefix (def: $fileStatePersistPrefix) -t ... temporary state file prefix (def: $fileStateTempPrefix) All time strings can be specified in seconds, or using BIND style time strings, ex: 1w2d3h5m30s is 1 week, 2 days, 3 hours, etc... _EOF_ } # Begin main logic # unset logMode while getopts a:b:c:C:f:hj:l:m:p:P:s:t: arg ; do case "$arg" in a) attemptCount="$OPTARG" ;; b) banLength="$OPTARG" ;; c) firewallChain="$OPTARG" ;; C) firewallHookChains="$OPTARG" ;; f) logFacility="$OPTARG" ;; j) firewallTarget="$OPTARG" ;; l) logLevel="$OPTARG" ;; m) logMode="$OPTARG" ;; p) attemptPeriod="$OPTARG" ;; P) persistentStateWritePeriod="$OPTARG" ;; s) fileStatePersistPrefix="$OPTARG" ;; s) fileStatePersistPrefix="$OPTARG" ;; *) printUsage exit 254 esac shift `expr $OPTIND - 1` done [ -z $logMode ] && logMode="$defaultMode" fileStateTemp="$fileStateTempPrefix.$fileStateType" fileStatePersist="$fileStatePersistPrefix.$fileStateType" attemptPeriod=`expandBindTime $attemptPeriod` banLength=`expandBindTime $banLength` [ $persistentStateWritePeriod != -1 ] && persistentStateWritePeriod=`expandBindTime $persistentStateWritePeriod` followModeCheckInterval=`expandBindTime $followModeCheckInterval` exitStatus=0 # Here we convert the logRegex list into a sed -f file fileRegex="/tmp/beardropper.$$.regex" uciLoad logRegex 's/[`$"'\\\'']//g' '/has invalid shell, rejected$/d' \ '/^[A-Za-z ]+[0-9: ]+authpriv.warn dropbear\[.+([0-9]+\.){3}[0-9]+/p' \ '/^[A-Za-z ]+[0-9: ]+authpriv.info dropbear\[.+:\ Exit before auth:.*/p' > "$fileRegex" lastPersistentStateWrite="`date +%s`" loadState bddbCheckStatusAll # main event loops if [ "$logMode" = follow ] ; then logLine 1 "Running in follow mode" readsSinceSave=0 lastCheckAll=0 worstCaseReads=1 tmpFile="/tmp/beardropper.$$.1" # Verify if these do any good - try saving to a temp. Scope may make saveState useless. trap "rm -f "$tmpFile" "$fileRegex" ; exit " SIGINT [ $persistentStateWritePeriod -gt 1 ] && worstCaseReads=$((persistentStateWritePeriod / followModeCheckInterval)) firstRun=1 $cmdLogread -f | while read -t $followModeCheckInterval line || true ; do if [ $firstRun -eq 1 ] ; then trap "saveState -f" SIGHUP trap "saveState -f; exit" SIGINT firstRun=0 fi sed -nEf "$fileRegex" > "$tmpFile" <<-_EOF_ $line _EOF_ line="`cat $tmpFile`" [ -n "$line" ] && processLogLine "$line" logLine 3 "ReadComp:$readsSinceSave/$worstCaseReads" if [ $((++readsSinceSave)) -ge $worstCaseReads ] ; then now="`date +%s`" if [ $((now - lastCheckAll)) -ge $followModeCheckInterval ] ; then bddbCheckStatusAll lastCheckAll="$now" saveState readsSinceSave=0 fi fi done elif [ "$logMode" = entire ] ; then logLine 1 "Running in entire mode" $cmdLogread | sed -nEf "$fileRegex" | while read line ; do processLogLine "$line" saveState done loadState bddbCheckStatusAll saveState -f elif [ "$logMode" = today ] ; then logLine 1 "Running in today mode" # merge the egrep into sed with -e /^$formatTodayLogDateRegex/!d $cmdLogread | egrep "`date +\'$formatTodayLogDateRegex\'`" | sed -nEf "$fileRegex" | while read line ; do processLogLine "$line" saveState done loadState bddbCheckStatusAll saveState -f elif isValidBindTime "$logMode" ; then logInterval=`expandBindTime $logMode` logLine 1 "Running in interval mode (reviewing $logInterval seconds of log entries)..." timeStart=$((`date +%s` - logInterval)) $cmdLogread | sed -nEf "$fileRegex" | while read line ; do timeWhen=`getLogTime "$line"` [ $timeWhen -ge $timeStart ] && processLogLine "$line" saveState done loadState bddbCheckStatusAll saveState -f elif [ "$logMode" = wipe ] ; then logLine 2 "Wiping state files, unhooking and removing iptables chains" wipeFirewall if [ -f "$fileStateTemp" ] ; then logLine 1 "Removing non-persistent statefile ($fileStateTemp)" rm -f "$fileStateTemp" fi if [ -f "$fileStatePersist" ] ; then logLine 1 "Removing persistent statefile ($fileStatePersist)" rm -f "$fileStatePersist" fi else logLine 0 "Error: invalid log mode ($logMode)" exitStatus=254 fi rm -f "$fileRegex" exit $exitStatus
2929004360/ruoyi-sign
1,760
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfModelPermissionService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfModelPermission; import java.util.List; /** * 流程模型权限Service接口 * * @author fengcheng * @date 2024-07-10 */ public interface IWfModelPermissionService { /** * 查询流程模型权限 * * @param modelPermissionId 流程模型权限主键 * @return 流程模型权限 */ public WfModelPermission selectWfModelPermissionByModelPermissionId(String modelPermissionId); /** * 查询流程模型权限列表 * * @param wfModelPermission 流程模型权限 * @param permissionIdList 业务id列表 * @return 流程模型权限集合 */ public List<WfModelPermission> selectWfModelPermissionList( WfModelPermission wfModelPermission, List<Long> permissionIdList ); /** * 新增流程模型权限 * * @param wfModelPermission 流程模型权限 * @return 结果 */ public int insertWfModelPermission(WfModelPermission wfModelPermission); /** * 修改流程模型权限 * * @param wfModelPermission 流程模型权限 * @return 结果 */ public int updateWfModelPermission(WfModelPermission wfModelPermission); /** * 批量删除流程模型权限 * * @param modelPermissionIds 需要删除的流程模型权限主键集合 * @return 结果 */ public int deleteWfModelPermissionByModelPermissionIds(String[] modelPermissionIds); /** * 删除流程模型权限信息 * * @param modelPermissionId 流程模型权限主键 * @return 结果 */ public int deleteWfModelPermissionByModelPermissionId(String modelPermissionId); /** * 批量新增流程模型权限 * * @param permissionsList */ int insertWfModelPermissionList(List<WfModelPermission> permissionsList); /** * 根据模型ID删除流程模型权限 * * @param modelId * @return */ int deleteWfModelPermissionByModelId(String modelId); }
2929004360/ruoyi-sign
1,343
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfRoamHistoricalService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfRoamHistorical; import java.util.List; /** * 历史流转记录Service接口 * * @author fengcheng * @date 2024-08-16 */ public interface IWfRoamHistoricalService { /** * 查询历史流转记录 * * @param roamHistoricalId 历史流转记录主键 * @return 历史流转记录 */ public WfRoamHistorical selectWfRoamHistoricalByRoamHistoricalId(String roamHistoricalId); /** * 查询历史流转记录列表 * * @param wfRoamHistorical 历史流转记录 * @return 历史流转记录集合 */ public List<WfRoamHistorical> selectWfRoamHistoricalList(WfRoamHistorical wfRoamHistorical); /** * 新增历史流转记录 * * @param wfRoamHistorical 历史流转记录 * @return 结果 */ public int insertWfRoamHistorical(WfRoamHistorical wfRoamHistorical); /** * 修改历史流转记录 * * @param wfRoamHistorical 历史流转记录 * @return 结果 */ public int updateWfRoamHistorical(WfRoamHistorical wfRoamHistorical); /** * 批量删除历史流转记录 * * @param roamHistoricalIds 需要删除的历史流转记录主键集合 * @return 结果 */ public int deleteWfRoamHistoricalByRoamHistoricalIds(String[] roamHistoricalIds); /** * 删除历史流转记录信息 * * @param roamHistoricalId 历史流转记录主键 * @return 结果 */ public int deleteWfRoamHistoricalByRoamHistoricalId(String roamHistoricalId); }
2929004360/ruoyi-sign
1,649
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfBusinessProcessService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import java.util.List; /** * 业务流程Service接口 * * @author fengcheng * @date 2024-07-15 */ public interface IWfBusinessProcessService { /** * 查询业务流程 * * @param businessId 业务流程主键 * @return 业务流程 */ public WfBusinessProcess selectWfBusinessProcessByBusinessId(String businessId); /** * 查询业务流程列表 * * @param wfBusinessProcess 业务流程 * @return 业务流程集合 */ public List<WfBusinessProcess> selectWfBusinessProcessList(WfBusinessProcess wfBusinessProcess); /** * 新增业务流程 * * @param wfBusinessProcess 业务流程 * @return 结果 */ public int insertWfBusinessProcess(WfBusinessProcess wfBusinessProcess); /** * 修改业务流程 * * @param wfBusinessProcess 业务流程 * @return 结果 */ public int updateWfBusinessProcess(WfBusinessProcess wfBusinessProcess); /** * 批量删除业务流程 * * @param businessIds 需要删除的业务流程主键集合 * @return 结果 */ public int deleteWfBusinessProcessByBusinessIds(String[] businessIds); /** * 删除业务流程信息 * * @param businessId 业务流程主键 * @param type 业务类型 * @return 结果 */ public int deleteWfBusinessProcessByBusinessId(String businessId, String type); /** * 根据流程ID查询业务流程 * * @param processId * @return */ WfBusinessProcess selectWfBusinessProcessByProcessId(String processId); /** * 根据流程ID查询业务流程列表 * * @param ids * @return */ List<WfBusinessProcess> selectWfBusinessProcessListByProcessId(List<String> ids); }
2929004360/ruoyi-sign
1,433
ruoyi-flowable/src/main/java/com/ruoyi/flowable/service/IWfModelTemplateService.java
package com.ruoyi.flowable.service; import com.ruoyi.flowable.domain.WfModelTemplate; import java.util.List; /** * 模型模板Service接口 * * @author fengcheng * @date 2024-07-17 */ public interface IWfModelTemplateService { /** * 查询模型模板 * * @param modelTemplateId 模型模板主键 * @return 模型模板 */ public WfModelTemplate selectWfModelTemplateByModelTemplateId(String modelTemplateId); /** * 查询模型模板列表 * * @param wfModelTemplate 模型模板 * @return 模型模板集合 */ public List<WfModelTemplate> selectWfModelTemplateList(WfModelTemplate wfModelTemplate); /** * 新增模型模板 * * @param wfModelTemplate 模型模板 * @return 结果 */ public int insertWfModelTemplate(WfModelTemplate wfModelTemplate); /** * 修改模型模板 * * @param wfModelTemplate 模型模板 * @return 结果 */ public int updateWfModelTemplate(WfModelTemplate wfModelTemplate); /** * 批量删除模型模板 * * @param modelTemplateIds 需要删除的模型模板主键集合 * @return 结果 */ public int deleteWfModelTemplateByModelTemplateIds(String[] modelTemplateIds); /** * 删除模型模板信息 * * @param modelTemplateId 模型模板主键 * @return 结果 */ public int deleteWfModelTemplateByModelTemplateId(String modelTemplateId); /** * 修改模型模板xml * * @param wfModelTemplate 模型模板 * @return 结果 */ int editBpmnXml(WfModelTemplate wfModelTemplate); }
2929004360/ruoyi-sign
2,431
ruoyi-flowable/src/main/java/com/ruoyi/flowable/config/WxMaConfiguration.java
package com.ruoyi.flowable.config; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage; import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; import cn.binarywang.wx.miniapp.message.WxMaMessageHandler; import cn.binarywang.wx.miniapp.message.WxMaMessageRouter; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxRuntimeException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.File; import java.util.List; import java.util.stream.Collectors; /** * 微信小程序配置 * * @author fengcheng */ @Slf4j @Configuration @EnableConfigurationProperties(WxMaProperties.class) public class WxMaConfiguration { private final WxMaProperties properties; @Autowired public WxMaConfiguration(WxMaProperties properties) { this.properties = properties; } @Bean public WxMaService wxMaService() { List<WxMaProperties.Config> configs = this.properties.getConfigs(); if (configs == null) { throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!"); } WxMaService maService = new WxMaServiceImpl(); maService.setMultiConfigs( configs.stream() .map(a -> { WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); // WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool()); // 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常 config.setAppid(a.getAppid()); config.setSecret(a.getSecret()); config.setToken(a.getToken()); config.setAesKey(a.getAesKey()); config.setMsgDataFormat(a.getMsgDataFormat()); return config; }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o))); return maService; } }
2929004360/ruoyi-sign
1,702
ruoyi-flowable/src/main/java/com/ruoyi/flowable/config/GlobalEventListenerConfig.java
package com.ruoyi.flowable.config; import com.ruoyi.flowable.listener.GlobalEventListener; import com.ruoyi.flowable.listener.TaskCreateListener; import lombok.AllArgsConstructor; import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType; import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher; import org.flowable.engine.RuntimeService; import org.flowable.spring.SpringProcessEngineConfiguration; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextRefreshedEvent; /** * flowable全局监听配置 * * @author ssc */ @Configuration @AllArgsConstructor public class GlobalEventListenerConfig implements ApplicationListener<ContextRefreshedEvent> { private final GlobalEventListener globalEventListener; private final RuntimeService runtimeService; private final TaskCreateListener taskCreateListener; private final SpringProcessEngineConfiguration configuration; @Override public void onApplicationEvent(ContextRefreshedEvent event) { FlowableEventDispatcher dispatcher = configuration.getEventDispatcher(); // 任务创建全局监听-待办消息发送 dispatcher.addEventListener(taskCreateListener, FlowableEngineEventType.TASK_ASSIGNED); // 流程正常结束 runtimeService.addEventListener(globalEventListener, FlowableEngineEventType.PROCESS_COMPLETED, FlowableEngineEventType.TASK_CREATED, FlowableEngineEventType.ACTIVITY_CANCELLED ); // FlowableEngineEventType.TASK_CREATED, // FlowableEngineEventType.TASK_ASSIGNED, } }
2929004360/ruoyi-sign
2,925
ruoyi-flowable/src/main/java/com/ruoyi/flowable/handler/MultiInstanceHandler.java
package com.ruoyi.flowable.handler; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.system.api.domain.SysUserRole; import lombok.AllArgsConstructor; import org.flowable.bpmn.model.FlowElement; import org.flowable.bpmn.model.UserTask; import org.flowable.engine.delegate.DelegateExecution; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * 多实例处理类 * * @author fengcheng */ @AllArgsConstructor @Component("multiInstanceHandler") public class MultiInstanceHandler { /** * 获取多实例用户id集合 * * @param execution * @return */ public Set<String> getUserNames(DelegateExecution execution) { Set<String> candidateUserIds = new LinkedHashSet<>(); FlowElement flowElement = execution.getCurrentFlowElement(); if (ObjectUtil.isNotEmpty(flowElement) && flowElement instanceof UserTask) { UserTask userTask = (UserTask) flowElement; String dataType = userTask.getAttributeValue(ProcessConstants.NAMASPASE, ProcessConstants.PROCESS_CUSTOM_DATA_TYPE); if ("USERS".equals(dataType) && CollUtil.isNotEmpty(userTask.getCandidateUsers())) { // 添加候选用户id candidateUserIds.addAll(userTask.getCandidateUsers()); } else if (CollUtil.isNotEmpty(userTask.getCandidateGroups())) { // 获取组的ID,角色ID集合或部门ID集合 List<Long> groups = userTask.getCandidateGroups().stream() .map(item -> Long.parseLong(item.substring(4))) .collect(Collectors.toList()); List<Long> userIds = new ArrayList<>(); if ("ROLES".equals(dataType)) { // 通过角色id,获取所有用户id集合 LambdaQueryWrapper<SysUserRole> lqw = Wrappers.lambdaQuery(SysUserRole.class).select(SysUserRole::getUserId).in(SysUserRole::getRoleId, groups); userIds = SimpleQuery.list(lqw, SysUserRole::getUserId); } else if ("DEPTS".equals(dataType)) { // 通过部门id,获取所有用户id集合 LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId).in(SysUser::getDeptId, groups); userIds = SimpleQuery.list(lqw, SysUser::getUserId); } // 添加候选用户id userIds.forEach(id -> candidateUserIds.add(String.valueOf(id))); } } return candidateUserIds; } }
2929004360/ruoyi-sign
3,386
ruoyi-flowable/src/main/java/com/ruoyi/flowable/handler/ResubmitProcessHandler.java
package com.ruoyi.flowable.handler; import cn.hutool.core.bean.BeanUtil; import com.ruoyi.common.enums.FlowMenuEnum; import com.ruoyi.common.enums.ProcessStatus; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.api.domain.vo.WorkSignVo; import com.ruoyi.flowable.api.service.IWorkSignServiceApi; import com.ruoyi.flowable.service.IWfBusinessProcessService; import com.ruoyi.flowable.service.IWfProcessService; import org.flowable.engine.HistoryService; import org.flowable.engine.runtime.ProcessInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * 重新发起流程处理类 * * @author fengcheng */ @Component("resubmitProcessHandler") public class ResubmitProcessHandler { @Autowired @Lazy private IWfBusinessProcessService wfBusinessProcessService; @Autowired @Lazy private IWfProcessService wfProcessService; @Autowired @Lazy protected HistoryService historyService; @Autowired @Lazy private IWorkSignServiceApi workSignServiceApi; /** * 重新发起流程 * * @param wfBusinessProcess 重新发起 */ @Transactional(rollbackFor = Exception.class) public void resubmit(WfBusinessProcess wfBusinessProcess) { // 电子签章 if (FlowMenuEnum.SIGN_FLOW_MENU.getCode().equals(wfBusinessProcess.getBusinessProcessType())) { updateSign(wfBusinessProcess); return; } } /** * 修改签署 * * @param wfBusinessProcess 重新发起 */ private void updateSign(WfBusinessProcess wfBusinessProcess) { // 删除流程实例 List<String> ids = Collections.singletonList(wfBusinessProcess.getProcessId()); // 删除历史流程实例 historyService.bulkDeleteHistoricProcessInstances(ids); // 删除业务流程信息 wfBusinessProcessService.deleteWfBusinessProcessByBusinessId(wfBusinessProcess.getBusinessId(), wfBusinessProcess.getBusinessProcessType()); WorkSignVo workSignVo = workSignServiceApi.selectWorkSignBySignId(wfBusinessProcess.getBusinessId()); // 发起流程 workSignVo.setBusinessId(String.valueOf(workSignVo.getSignId())); workSignVo.setBusinessProcessType(FlowMenuEnum.SIGN_FLOW_MENU.getCode()); workSignVo.setSignFileList(null); ProcessInstance processInstance = wfProcessService.startProcessByDefId(workSignVo.getDefinitionId(), BeanUtil.beanToMap(workSignVo, new HashMap<>(16), false, false)); String processInstanceId = processInstance.getProcessInstanceId(); // 添加业务流程 WfBusinessProcess process = new WfBusinessProcess(); process.setProcessId(processInstanceId); process.setBusinessId(String.valueOf(workSignVo.getSignId())); process.setBusinessProcessType(FlowMenuEnum.SIGN_FLOW_MENU.getCode()); wfBusinessProcessService.insertWfBusinessProcess(process); // 修改对应流程 WorkSignVo workSign = new WorkSignVo(); workSign.setProcessId(processInstanceId); workSign.setSchedule(ProcessStatus.RUNNING.getStatus()); workSign.setSignId(workSignVo.getSignId()); workSignServiceApi.updateWorkSign(workSign); } }
281677160/openwrt-package
5,238
luci-app-mentohust/luasrc/model/cbi/mentohust/general.lua
local function is_running(name) if luci.sys.call("pidof %s >/dev/null" %{name}) == 0 then return translate("RUNNING") else return translate("NOT RUNNING") end end local function is_online(ipaddr) if ipaddr == "0.0.0.0" then return translate("Pinghost not set") end if luci.sys.call("ping -c1 -w1 %s >/dev/null 2>&1" %{ipaddr}) == 0 then return translate("ONLINE") else return translate("NOT ONLINE") end end require("luci.sys") m = Map("mentohust", translate("MentoHUST")) m.description = translate("Configure MentoHUST 802.11x.") s = m:section(TypedSection, "mentohust", translate("Status")) s.anonymous = true status = s:option(DummyValue,"_mentohust_status", "MentoHUST") status.value = "<span id=\"_mentohust_status\">%s</span>" %{is_running("mentohust")} status.rawhtml = true t = io.popen('uci get mentohust.@mentohust[0].pinghost') netstat = is_online(tostring(t:read("*line"))) t:close() if netstat ~= "" then netstatus = s:option(DummyValue,"_network_status", translate("Network Status")) netstatus.value = "<span id=\"_network_status\">%s</span>" %{netstat} netstatus.rawhtml = true end o = m:section(TypedSection, "mentohust", translate("Settings")) o.addremove = false o.anonymous = true o:tab("base", translate("Normal Settings")) o:tab("advanced", translate("Advanced Settings")) enable = o:taboption("base", Flag, "enable", translate("Enable")) name = o:taboption("base", Value, "username", translate("Username")) name.description = translate("The username given to you by your network administrator") pass = o:taboption("base", Value, "password", translate("Password")) pass.description = translate("The password you set or given to you by your network administrator") pass.password = true ifname = o:taboption("base", ListValue, "ifname", translate("Interfaces")) ifname.description = translate("Physical interface of WAN") for k, v in ipairs(luci.sys.net.devices()) do if v ~= "lo" then ifname:value(v) end end pinghost = o:taboption("base", Value, "pinghost", translate("PingHost")) pinghost.description = translate("Ping host for drop detection, 0.0.0.0 to turn off this feature") pinghost.default = "0.0.0.0" ipaddr = o:taboption("advanced", Value, "ipaddr", translate("IP Address")) ipaddr.description = translate("Your IPv4 Address. (DHCP users can set to 0.0.0.0)") ipaddr.default = "0.0.0.0" mask = o:taboption("advanced", Value, "mask", translate("NetMask")) mask.description = translate("NetMask, it doesn't matter") mask.default = "0.0.0.0" gateway = o:taboption("advanced", Value, "gateway", translate("Gateway")) gateway.description = translate("Gateway, if specified, will monitor gateway ARP information") gateway.default = "0.0.0.0" dnsserver = o:taboption("advanced", Value, "dns", translate("DNS server")) dnsserver.description = translate("DNS server, it doesn't matter") dnsserver.default = "0.0.0.0" timeout = o:taboption("advanced", Value, "timeout", translate("Timeout")) timeout.description = translate("Each timeout of the package (seconds)") timeout.default = "8" echointerval = o:taboption("advanced", Value, "echointerval", translate("EchoInterval")) echointerval.description = translate("Interval for sending Echo packets (seconds)") echointerval.default = "30" restartwait = o:taboption("advanced", Value, "restartwait", translate("RestartWait")) restartwait.description = translate("Failed Wait (seconds) Wait for seconds after authentication failed or restart authentication after server request") restartwait.default = "15" startmode = o:taboption("advanced", ListValue, "startmode", translate("StartMode")) startmode.description = translate("Multicast address type when searching for servers") startmode:value(0, translate("Standard")) startmode:value(1, translate("Ruijie")) startmode:value(2, translate("Uses MentoHUST for Xaar certification")) startmode.default = "0" dhcpmode = o:taboption("advanced", ListValue, "dhcpmode", translate("DhcpMode")) dhcpmode.description = translate("DHCP method") dhcpmode:value(0, translate("None")) dhcpmode:value(1, translate("secondary authentication")) dhcpmode:value(2, translate("after certification")) dhcpmode:value(3, translate("before certification")) dhcpmode.default = "2" shownotify = o:taboption("advanced", Value, "shownotify", translate("ShowNotify")) shownotify.description = translate("Whether to display notifications 0 (no) 1 to 20 (yes)") shownotify.default = "5" version = o:taboption("advanced", Value, "version", translate("Client Version")) version.description = translate("Client version number. If client verification is not enabled but the version number is required, it can be specified here. The format is 3.30.") version.default = "0.00" datafile = o:taboption("advanced", Value, "datafile", translate("DataFile")) datafile.description = translate("Authentication data file, if you need to verify the client, you need to set correctly") datafile.default = "/etc/mentohust/" dhcpscript = o:taboption("advanced", Value, "dhcpscript", translate("DhcpScript")) dhcpscript.description = translate("DHCP script") dhcpscript.default = "udhcpc -i" local apply = luci.http.formvalue("cbi.apply") if apply then io.popen("/etc/init.d/mentohust restart") end return m
2929004360/ruoyi-sign
1,661
ruoyi-flowable/src/main/java/com/ruoyi/flowable/handler/BusinessProcessDetailsHandler.java
package com.ruoyi.flowable.handler; import cn.hutool.core.bean.BeanUtil; import com.ruoyi.common.enums.FlowMenuEnum; import com.ruoyi.flowable.api.service.IWorkSignServiceApi; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.domain.vo.WfDetailVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * 业务流程详情处理类 * * @author fengcheng */ @Component("businessProcessDetailsHandler") public class BusinessProcessDetailsHandler { @Autowired @Lazy private IWorkSignServiceApi workSignServiceApi; /** * 设置业务流程 * * @param detailVo * @param processVariables */ public void setBusinessProcess(WfDetailVo detailVo, Map<String, Object> processVariables) { // 流程状态 // String processStatus = processVariables.get(ProcessConstants.PROCESS_STATUS_KEY).toString(); // 业务ID String businessId = processVariables.get(ProcessConstants.BUSINESS_ID).toString(); // 启动流程的人 // String initiator = processVariables.get(BpmnXMLConstants.ATTRIBUTE_EVENT_START_INITIATOR).toString(); // 业务流程类型 String businessProcessType = processVariables.get(ProcessConstants.BUSINESS_PROCESS_TYPE).toString(); // 电子签章 if (FlowMenuEnum.SIGN_FLOW_MENU.getCode().equals(businessProcessType)) { detailVo.setBusinessProcess(BeanUtil.beanToMap(workSignServiceApi.selectWorkSignBySignId(businessId), new HashMap<>(16), false, false)); return; } } }
2929004360/ruoyi-sign
1,888
ruoyi-flowable/src/main/java/com/ruoyi/flowable/handler/DeleteProcessBusinessHandler.java
package com.ruoyi.flowable.handler; import com.ruoyi.common.enums.FlowMenuEnum; import com.ruoyi.common.enums.ProcessStatus; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.api.domain.vo.WorkSignVo; import com.ruoyi.flowable.api.service.IWorkSignServiceApi; import com.ruoyi.flowable.service.IWfBusinessProcessService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 删除业务流程处理类 * * @author fengcheng */ @RequiredArgsConstructor @Component("deleteProcessBusinessHandler") public class DeleteProcessBusinessHandler { @Autowired @Lazy private IWfBusinessProcessService wfBusinessProcessService; @Autowired @Lazy private IWorkSignServiceApi workSignServiceApi; /** * 删除业务流程 * * @param ids */ @Transactional(rollbackFor = Exception.class) public void delete(List<String> ids) { List<WfBusinessProcess> list = wfBusinessProcessService.selectWfBusinessProcessListByProcessId(ids); for (WfBusinessProcess wfBusinessProcess : list) { // 电子签章 if (FlowMenuEnum.SIGN_FLOW_MENU.getCode().equals(wfBusinessProcess.getBusinessProcessType())) { WorkSignVo workSignVo = new WorkSignVo(); workSignVo.setSignId(Long.valueOf(wfBusinessProcess.getBusinessId())); workSignVo.setSchedule(ProcessStatus.UNAPPROVED.getStatus()); workSignServiceApi.updateWorkSign(workSignVo); } wfBusinessProcessService.deleteWfBusinessProcessByBusinessId(wfBusinessProcess.getBusinessId(), wfBusinessProcess.getBusinessProcessType()); } } }
281677160/openwrt-package
2,925
luci-app-mentohust/po/zh_Hans/mentohust.po
msgid "" msgstr "Content-Type: text/plain; charset=UTF-8\n" msgid "MentoHUST Settings" msgstr "MentoHUST 设置" msgid "MentoHUST LOG" msgstr "MentoHUST 日志" msgid "Log file:/tmp/mentohust.log" msgstr "日志文件:/tmp/mentohust.log" msgid "Configure MentoHUST 802.11x." msgstr "配置MentoHUST 802.11x验证。" msgid "Normal Settings" msgstr "常规设置" msgid "The username given to you by your network administrator" msgstr "您的用户名(或管理员分配的用户名)" msgid "The password you set or given to you by your network administrator" msgstr "您的密码(或管理员分配的密码)" msgid "Physical interface of WAN" msgstr "WAN口的物理接口" msgid "PingHost" msgstr "Ping主机" msgid "Ping host for drop detection, 0.0.0.0 to turn off this feature" msgstr "Ping主机,用于掉线检测,0.0.0.0表示关闭该功能" msgid "IP Address" msgstr "IP地址" msgid "Your IPv4 Address. (DHCP users can set to 0.0.0.0)" msgstr "你的IPV4地址,DHCP用户可设为0.0.0.0" msgid "NetMask" msgstr "子网掩码" msgid "NetMask, it doesn't matter" msgstr "掩码,无关紧要" msgid "Gateway, if specified, will monitor gateway ARP information" msgstr "网关,如果指定了就会监视网关ARP信息" msgid "DNS server" msgstr "DNS服务器" msgid "DNS server, it doesn't matter" msgstr "DNS服务器,无关紧要" msgid "Timeout" msgstr "验证超时" msgid "Each timeout of the package (seconds)" msgstr "每次发包超时时间(秒)" msgid "EchoInterval" msgstr "Echo包间隔" msgid "Interval for sending Echo packets (seconds)" msgstr "发送Echo包的间隔(秒)" msgid "RestartWait" msgstr "验证失败等待时间" msgid "Failed Wait (seconds) Wait for seconds after authentication failed or restart authentication after server request" msgstr "失败等待(秒)认证失败后等待多少秒或者服务器请求后重启认证" msgid "StartMode" msgstr "组播地址类型" msgid "Multicast address type when searching for servers" msgstr "寻找服务器时的组播地址类型(某些交换机可能会丢弃标准包)" msgid "Standard" msgstr "标准" msgid "Ruijie" msgstr "锐捷" msgid "Uses MentoHUST for Xaar certification" msgstr "将MentoHUST用于赛尔认证" msgid "DhcpMode" msgstr "DHCP设置" msgid "DHCP method" msgstr "DHCP方式" msgid "None" msgstr "无" msgid "secondary authentication" msgstr "二次认证" msgid "after certification" msgstr "认证后" msgid "before certification" msgstr "认证前" msgid "ShowNotify" msgstr "通知级别" msgid "Whether to display notifications 0 (no) 1 to 20 (yes)" msgstr "是否显示通知: 0(否) 1~20(是)" msgid "Client Version" msgstr "客户端版本号" msgid "Client version number. If client verification is not enabled but the version number is required, it can be specified here. The format is 3.30." msgstr "客户端版本号,如果未开启客户端校验但对版本号有要求,可以在此指定,形如3.30" msgid "DataFile" msgstr "数据文件" msgid "Authentication data file, if you need to verify the client, you need to set correctly" msgstr "认证数据文件,如果需要校验客户端,就需要正确设置" msgid "DhcpScript" msgstr "DHCP的脚本" msgid "DHCP script" msgstr "进行DHCP的脚本" msgid "RUNNING" msgstr "运行中" msgid "NOT RUNNING" msgstr "未运行" msgid "ONLINE" msgstr "能访问互联网" msgid "NOT ONLINE" msgstr "不能访问互联网" msgid "Settings" msgstr "设置" msgid "Network Status" msgstr "网络状态" msgid "Pinghost not set" msgstr "没有设置Ping主机" msgid "Clear log" msgstr "清除日志"
2929004360/ruoyi-sign
13,168
ruoyi-flowable/src/main/java/com/ruoyi/flowable/listener/GlobalEventListener.java
package com.ruoyi.flowable.listener; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.BetweenFormatter; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.enums.FlowMenuEnum; import com.ruoyi.common.enums.ProcessStatus; import com.ruoyi.flowable.api.domain.WfBusinessProcess; import com.ruoyi.flowable.api.domain.vo.WorkSignVo; import com.ruoyi.flowable.api.service.IWorkSignServiceApi; import com.ruoyi.flowable.constant.ProcessConstants; import com.ruoyi.flowable.constant.TaskConstants; import com.ruoyi.flowable.domain.WfRoamHistorical; import com.ruoyi.flowable.domain.vo.WfProcNodeVo; import com.ruoyi.flowable.service.IWfBusinessProcessService; import com.ruoyi.flowable.service.IWfRoamHistoricalService; import com.ruoyi.flowable.service.IWfTaskService; import com.ruoyi.flowable.utils.IdWorker; import com.ruoyi.flowable.utils.StringUtils; import com.ruoyi.system.api.service.ISysConfigServiceApi; import com.ruoyi.system.api.service.ISysDeptServiceApi; import com.ruoyi.system.api.service.ISysRoleServiceApi; import com.ruoyi.system.api.service.ISysUserServiceApi; import me.chanjar.weixin.common.error.WxErrorException; import org.flowable.bpmn.constants.BpmnXMLConstants; import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent; import org.flowable.engine.HistoryService; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener; import org.flowable.engine.delegate.event.FlowableActivityCancelledEvent; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.task.Comment; import org.flowable.identitylink.api.history.HistoricIdentityLink; import org.flowable.task.api.Task; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * Flowable 全局监听器 * * @author fengcheng * @since 2023/3/8 22:45 */ @Component @Transactional(rollbackFor = Exception.class) public class GlobalEventListener extends AbstractFlowableEngineEventListener { @Autowired @Lazy private IWfRoamHistoricalService wfRoamHistoricalService; @Autowired @Lazy private IdWorker idWorker; @Autowired @Lazy protected TaskService taskService; @Autowired @Lazy protected IWfTaskService wfTaskService; @Autowired @Lazy protected HistoryService historyService; @Lazy @Autowired private ISysUserServiceApi userServiceApi; @Lazy @Autowired private ISysRoleServiceApi roleServiceApi; @Lazy @Autowired private ISysDeptServiceApi deptServiceApi; @Autowired @Lazy private RuntimeService runtimeService; @Autowired @Lazy private IWfBusinessProcessService wfBusinessProcessService; @Autowired @Lazy private ISysConfigServiceApi sysConfigServiceApi; @Autowired @Lazy private IWorkSignServiceApi workSignServiceApi; /** * 监听活动取消事件 * * @param event */ @Override protected void activityCancelled(FlowableActivityCancelledEvent event) { System.out.println("监听活动取消事件" + event.getActivityId()); } /** * 监听任务创建事件 * * @param event */ @Override protected void taskCreated(FlowableEngineEntityEvent event) { System.out.println("监听任务创建事件" + event.getEntity()); try { String key = sysConfigServiceApi.selectConfigByKey("sys.wechat.notice"); if (Boolean.parseBoolean(key)) { wfTaskService.updateTaskStatusWhenCreated((Task) event.getEntity()); } } catch (WxErrorException e) { throw new RuntimeException(e); } } /** * 流程结束监听器 */ @Override @Transactional(rollbackFor = Exception.class) protected void processCompleted(FlowableEngineEntityEvent event) { System.out.println("流程结束监听器" + event.getProcessInstanceId()); String processInstanceId = event.getProcessInstanceId(); Object variable = runtimeService.getVariable(processInstanceId, ProcessConstants.PROCESS_STATUS_KEY); ProcessStatus status = ProcessStatus.getProcessStatus(Convert.toStr(variable)); if (ObjectUtil.isNotNull(status) && ProcessStatus.RUNNING == status) { runtimeService.setVariable(processInstanceId, ProcessConstants.PROCESS_STATUS_KEY, ProcessStatus.COMPLETED.getStatus()); } // 修改业务流程 try { updateBusiness(processInstanceId, status); } catch (Exception e) { throw new RuntimeException("修改业务流程失败" + e.getMessage()); } super.processCompleted(event); } /** * 修改业务流程 * * @param processInstanceId 流程id * @param status 流程状态 */ private void updateBusiness(String processInstanceId, ProcessStatus status) throws Exception { WfBusinessProcess wfBusinessProcess = wfBusinessProcessService.selectWfBusinessProcessByProcessId(processInstanceId); if (ObjectUtil.isNotNull(wfBusinessProcess)) { // 电子签章 if (FlowMenuEnum.SIGN_FLOW_MENU.getCode().equals(wfBusinessProcess.getBusinessProcessType())) { updateWorkSign(wfBusinessProcess, status); return; } } } /** * 修改电子签章 * * @param wfBusinessProcess 业务流程 * @param status 流程状态 */ private void updateWorkSign(WfBusinessProcess wfBusinessProcess, ProcessStatus status) throws JsonProcessingException { String businessId = wfBusinessProcess.getBusinessId(); WorkSignVo workSignVo = workSignServiceApi.selectWorkSignBySignId(businessId); workSignVo.setSignId(Long.valueOf(businessId)); // 流程取消 if (ProcessStatus.CANCELED.getStatus().equals(status.getStatus())) { workSignVo.setSchedule(ProcessStatus.CANCELED.getStatus()); } // 流程终止 if (ProcessStatus.TERMINATED.getStatus().equals(status.getStatus())) { workSignVo.setSchedule(ProcessStatus.TERMINATED.getStatus()); // 插入流程流转历史 insertWfRoamHistorical(wfBusinessProcess); } // 流程完成 if (ProcessStatus.RUNNING.getStatus().equals(status.getStatus())) { workSignVo.setSchedule(ProcessStatus.COMPLETED.getStatus()); } workSignServiceApi.updateWorkSign(workSignVo); } /** * 插入流程流转历史 * * @param wfBusinessProcess */ private void insertWfRoamHistorical(WfBusinessProcess wfBusinessProcess) throws JsonProcessingException { // 获取流程实例 HistoricProcessInstance historicProcIns = historyService.createHistoricProcessInstanceQuery() .processInstanceId(wfBusinessProcess.getProcessId()).includeProcessVariables().singleResult(); List<WfProcNodeVo> wfProcNodeVos = historyProcNodeList(historicProcIns); wfRoamHistoricalService.insertWfRoamHistorical( new WfRoamHistorical(String.valueOf(idWorker.nextId()), wfBusinessProcess.getBusinessId(), wfBusinessProcess.getProcessId(), wfBusinessProcess.getBusinessProcessType(), new ObjectMapper().writeValueAsString(wfProcNodeVos)) ); } /** * 获取历史任务信息列表 */ private List<WfProcNodeVo> historyProcNodeList(HistoricProcessInstance historicProcIns) { String procInsId = historicProcIns.getId(); List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInsId).activityTypes(CollUtil.newHashSet(BpmnXMLConstants.ELEMENT_EVENT_START, BpmnXMLConstants.ELEMENT_EVENT_END, BpmnXMLConstants.ELEMENT_TASK_USER)).orderByHistoricActivityInstanceStartTime().desc().orderByHistoricActivityInstanceEndTime().desc().list(); List<Comment> commentList = taskService.getProcessInstanceComments(procInsId); List<WfProcNodeVo> elementVoList = new ArrayList<>(); for (HistoricActivityInstance activityInstance : historicActivityInstanceList) { WfProcNodeVo elementVo = new WfProcNodeVo(); elementVo.setProcDefId(activityInstance.getProcessDefinitionId()); elementVo.setActivityId(activityInstance.getActivityId()); elementVo.setActivityName(activityInstance.getActivityName()); elementVo.setActivityType(activityInstance.getActivityType()); elementVo.setCreateTime(activityInstance.getStartTime()); elementVo.setEndTime(activityInstance.getEndTime()); if (ObjectUtil.isNotNull(activityInstance.getDurationInMillis())) { elementVo.setDuration(DateUtil.formatBetween(activityInstance.getDurationInMillis(), BetweenFormatter.Level.SECOND)); } if (BpmnXMLConstants.ELEMENT_EVENT_START.equals(activityInstance.getActivityType())) { if (ObjectUtil.isNotNull(historicProcIns)) { Long userId = Long.parseLong(historicProcIns.getStartUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); if (nickName != null) { elementVo.setAssigneeId(userId); elementVo.setAssigneeName(nickName); } } } else if (BpmnXMLConstants.ELEMENT_TASK_USER.equals(activityInstance.getActivityType())) { if (StringUtils.isNotBlank(activityInstance.getAssignee())) { Long userId = Long.parseLong(activityInstance.getAssignee()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); elementVo.setAssigneeId(userId); elementVo.setAssigneeName(nickName); } // 展示审批人员 List<HistoricIdentityLink> linksForTask = historyService.getHistoricIdentityLinksForTask(activityInstance.getTaskId()); StringBuilder stringBuilder = new StringBuilder(); for (HistoricIdentityLink identityLink : linksForTask) { if ("candidate".equals(identityLink.getType())) { if (StringUtils.isNotBlank(identityLink.getUserId())) { Long userId = Long.parseLong(identityLink.getUserId()); SysUser sysUser = userServiceApi.selectUserById(userId); String nickName = sysUser.getNickName(); stringBuilder.append(nickName).append(","); } if (StringUtils.isNotBlank(identityLink.getGroupId())) { if (identityLink.getGroupId().startsWith(TaskConstants.ROLE_GROUP_PREFIX)) { Long roleId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.ROLE_GROUP_PREFIX)); SysRole role = roleServiceApi.selectRoleById(roleId); stringBuilder.append(role.getRoleName()).append(","); } else if (identityLink.getGroupId().startsWith(TaskConstants.DEPT_GROUP_PREFIX)) { Long deptId = Long.parseLong(StringUtils.stripStart(identityLink.getGroupId(), TaskConstants.DEPT_GROUP_PREFIX)); SysDept dept = deptServiceApi.selectDeptById(deptId); stringBuilder.append(dept.getDeptName()).append(","); } } } } if (StringUtils.isNotBlank(stringBuilder)) { elementVo.setCandidate(stringBuilder.substring(0, stringBuilder.length() - 1)); } // 获取意见评论内容 if (CollUtil.isNotEmpty(commentList)) { List<Comment> comments = new ArrayList<>(); for (Comment comment : commentList) { if (comment.getTaskId().equals(activityInstance.getTaskId())) { comments.add(comment); } } elementVo.setCommentList(comments); } } elementVoList.add(elementVo); } return elementVoList; } }
2929004360/ruoyi-sign
4,124
ruoyi-flowable/src/main/java/com/ruoyi/flowable/listener/TaskCreateListener.java
package com.ruoyi.flowable.listener; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.flowable.subscription.PendingApprovalTemplate; import com.ruoyi.flowable.utils.DateUtils; import com.ruoyi.flowable.utils.RiskAreaUtils; import com.ruoyi.system.api.service.ISysUserServiceApi; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.error.WxErrorException; import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType; import org.flowable.common.engine.api.delegate.event.FlowableEvent; import org.flowable.common.engine.api.delegate.event.FlowableEventListener; import org.flowable.common.engine.api.delegate.event.FlowableEventType; import org.flowable.engine.HistoryService; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.task.service.impl.persistence.entity.TaskEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import java.util.Date; import java.util.Map; /** * 全局监听-工作流待办消息提醒 * * @author fengcheng */ @Component @RequiredArgsConstructor public class TaskCreateListener implements FlowableEventListener { @Autowired @Lazy protected HistoryService historyService; @Autowired @Lazy protected RuntimeService runtimeService; @Lazy @Autowired private ISysUserServiceApi userServiceApi; @Lazy @Autowired private PendingApprovalTemplate pendingApprovalTemplate; @Lazy @Autowired protected TaskService taskService; /** * 监听类型 * * @param flowableEvent */ @Override public void onEvent(FlowableEvent flowableEvent) { // FlowableEventType type = flowableEvent.getType(); // if (type == FlowableEngineEventType.TASK_ASSIGNED) { // System.out.println("任务分配事件"); // if (flowableEvent instanceof org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl) { // TaskEntity taskEntity = (TaskEntity) ((org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl) flowableEvent).getEntity(); // String procInsId = taskEntity.getProcessInstanceId(); // HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).singleResult(); // String startUserId = historicProcessInstance.getStartUserId(); // // //获取任务接收人 // String receiverUserId = taskEntity.getAssignee(); // // Map<String, Object> variables = taskService.getVariables(taskEntity.getId()); // // //发起人或登录人自己不发送 // if (!(startUserId.equals(receiverUserId) && SecurityUtils.getUserId().toString().equals(receiverUserId))) { // SysUser receiverUser = userServiceApi.selectUserById(Long.valueOf(receiverUserId)); // // // 发送微信订阅消息 // try { // pendingApprovalTemplate.sending(receiverUser.getOpenid(), // variables.get("deptName").toString(), // variables.get("userName").toString(), // RiskAreaUtils.getHazardAreaNameByData(variables.get("riskArea").toString()), // DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, (Date) variables.get("createTime")), // "进行中" // ); // } catch (WxErrorException e) { // System.out.println(e.getMessage()); // } // } // } // } } @Override public boolean isFailOnException() { return false; } @Override public boolean isFireOnTransactionLifecycleEvent() { return false; } @Override public String getOnTransaction() { return null; } }
2929004360/ruoyi-sign
920
ruoyi-flowable/src/main/java/com/ruoyi/flowable/core/FormConf.java
package com.ruoyi.flowable.core; import lombok.Data; import java.util.List; import java.util.Map; /** * 表单属性类 * * @author fengcheng * @createTime 2022/8/6 18:54 */ @Data public class FormConf { /** * 标题 */ private String title; /** * 表单名 */ private String formRef; /** * 表单模型 */ private String formModel; /** * 表单尺寸 */ private String size; /** * 标签对齐 */ private String labelPosition; /** * 标签宽度 */ private Integer labelWidth; /** * 校验模型 */ private String formRules; /** * 栅格间隔 */ private Integer gutter; /** * 禁用表单 */ private Boolean disabled = false; /** * 栅格占据的列数 */ private Integer span; /** * 表单按钮 */ private Boolean formBtns = true; /** * 表单项 */ private List<Map<String, Object>> fields; }