File size: 7,202 Bytes
b5df735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
Download tools using local service architecture
Updated to use PodcastDownloadService for local execution only
"""

import asyncio
import os
import json
import time
from pathlib import Path
from typing import Dict, Any

from ..services import PodcastDownloadService, FileManagementService
from ..models.services import PodcastDownloadRequest


# Global service instances for reuse
_podcast_download_service = None
_file_management_service = None


def get_podcast_download_service() -> PodcastDownloadService:
    """Get or create global PodcastDownloadService instance for local downloads"""
    global _podcast_download_service
    if _podcast_download_service is None:
        # Use storage config for download folder
        _podcast_download_service = PodcastDownloadService()  # Will use storage config defaults
    return _podcast_download_service


def get_file_management_service() -> FileManagementService:
    """Get or create global FileManagementService instance"""
    global _file_management_service
    if _file_management_service is None:
        _file_management_service = FileManagementService()
    return _file_management_service


async def download_apple_podcast_tool(url: str) -> Dict[str, Any]:
    """
    Download Apple Podcast audio files and save to specified directory (LOCAL EXECUTION).
    
    Args:
        url: Complete URL of Apple Podcast page
    
    Returns:
        Download result dictionary containing the following key fields:
            - "status" (str): Download status, "success" or "failed"
            - "original_url" (str): Input original podcast URL
            - "audio_file_path" (str|None): Complete MP3 file path when successful, None when failed
            - "error_message" (str): Only exists when failed, contains specific error description
    """
    try:
        print(f"๐Ÿ  Downloading Apple Podcast locally: {url}")
        service = get_podcast_download_service()
        
        # Use local download service
        result = await service.download_podcast(
            url=url,
            output_folder="downloads",
            convert_to_mp3=True,
            keep_original=False
        )
        
        if result.success:
            return {
                "status": "success",
                "original_url": url,
                "audio_file_path": result.file_path,
                "podcast_info": {
                    "title": result.podcast_info.title if result.podcast_info else "Unknown",
                    "platform": "Apple Podcasts"
                }
            }
        else:
            return {
                "status": "failed",
                "original_url": url,
                "audio_file_path": None,
                "error_message": result.error_message
            }
        
    except Exception as e:
        return {
            "status": "failed",
            "original_url": url,
            "audio_file_path": None,
            "error_message": f"Local download tool error: {str(e)}"
        }


async def download_xyz_podcast_tool(url: str) -> Dict[str, Any]:
    """
    Download XiaoYuZhou podcast audio files and save to specified directory (LOCAL EXECUTION).
    
    Args:
        url: Complete URL of XiaoYuZhou podcast page, format: https://www.xiaoyuzhoufm.com/episode/xxxxx
    
    Returns:
        Download result dictionary containing the following key fields:
            - "status" (str): Download status, "success" or "failed"
            - "original_url" (str): Input original podcast URL
            - "audio_file_path" (str|None): Complete MP3 file path when successful, None when failed
            - "error_message" (str): Only exists when failed, contains specific error description
    """
    try:
        print(f"๐Ÿ  Downloading XiaoYuZhou Podcast locally: {url}")
        service = get_podcast_download_service()
        
        # Use local download service
        result = await service.download_podcast(
            url=url,
            output_folder="downloads",
            convert_to_mp3=True,
            keep_original=False
        )
        
        if result.success:
            return {
                "status": "success",
                "original_url": url,
                "audio_file_path": result.file_path,
                "podcast_info": {
                    "title": result.podcast_info.title if result.podcast_info else "Unknown",
                    "platform": "XiaoYuZhou"
                }
            }
        else:
            return {
                "status": "failed",
                "original_url": url,
                "audio_file_path": None,
                "error_message": result.error_message
            }
        
    except Exception as e:
        return {
            "status": "failed",
            "original_url": url,
            "audio_file_path": None,
            "error_message": f"Local download tool error: {str(e)}"
        }


async def get_mp3_files_tool(directory: str) -> Dict[str, Any]:
    """
    Scan specified directory to get detailed information list of all MP3 audio files (LOCAL EXECUTION).
    
    Args:
        directory: Absolute or relative path of directory to scan
    
    Returns:
        Dictionary containing MP3 file information
    """
    try:
        service = get_file_management_service()
        return await service.scan_mp3_files(directory)
        
    except Exception as e:
        return {
            "total_files": 0,
            "scanned_directory": directory,
            "file_list": [],
            "error_message": f"Local file scan tool error: {str(e)}"
        }


async def get_file_info_tool(file_path: str) -> Dict[str, Any]:
    """
    Get basic file information including size, modification time, etc (LOCAL EXECUTION).
    
    Args:
        file_path: File path to query
    
    Returns:
        File information dictionary
    """
    try:
        service = get_file_management_service()
        return await service.get_file_info(file_path)
        
    except Exception as e:
        return {
            "status": "failed",
            "file_path": file_path,
            "file_exists": False,
            "error_message": f"Local file info tool error: {str(e)}"
        }


async def read_text_file_segments_tool(
    file_path: str,
    chunk_size: int = 65536,
    start_position: int = 0
) -> Dict[str, Any]:
    """
    Read text file content in segments, intelligently handling text boundaries (LOCAL EXECUTION).
    
    Args:
        file_path: Path to file to read (supports TXT, SRT and other text files)
        chunk_size: Byte size to read each time, default 64KB
        start_position: Starting position to read from (byte offset), default 0
    
    Returns:
        Read result dictionary
    """
    try:
        service = get_file_management_service()
        return await service.read_text_file_segments(
            file_path=file_path,
            chunk_size=chunk_size,
            start_position=start_position
        )
        
    except Exception as e:
        return {
            "status": "failed",
            "file_path": file_path,
            "error_message": f"Local file read tool error: {str(e)}"
        }