File size: 10,547 Bytes
18b952c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
"""
Example Client for Telegram Multi-Part File Streamer
Demonstrates how to upload and download files programmatically
"""

import asyncio
import os
import time
from pathlib import Path

import httpx


class TelegramStreamerClient:
    """Client for interacting with Telegram File Streamer API"""
    
    def __init__(self, base_url: str = "http://localhost:8000"):
        self.base_url = base_url
        self.client = httpx.AsyncClient(timeout=300.0)
    
    async def close(self):
        """Close the HTTP client"""
        await self.client.aclose()
    
    async def upload_file(
        self,
        file_path: str,
        filename: str = None,
        chunk_size: int = 1024 * 1024  # 1MB chunks
    ) -> dict:
        """
        Upload a file to the streamer
        
        Args:
            file_path: Path to the file to upload
            filename: Optional custom filename
            chunk_size: Size of chunks for streaming upload
        
        Returns:
            Upload response with unique_id and download_url
        """
        file_path = Path(file_path)
        
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")
        
        if filename is None:
            filename = file_path.name
        
        file_size = file_path.stat().st_size
        
        print(f"πŸ“€ Uploading: {filename}")
        print(f"   Size: {self._format_size(file_size)}")
        
        async def file_stream():
            """Stream file in chunks"""
            with open(file_path, "rb") as f:
                uploaded = 0
                start_time = time.time()
                
                while True:
                    chunk = f.read(chunk_size)
                    if not chunk:
                        break
                    
                    uploaded += len(chunk)
                    
                    # Progress
                    elapsed = time.time() - start_time
                    if elapsed > 0:
                        speed = uploaded / elapsed
                        progress = (uploaded / file_size) * 100
                        print(
                            f"\r   Progress: {progress:.1f}% "
                            f"({self._format_size(uploaded)}/{self._format_size(file_size)}) "
                            f"Speed: {self._format_size(speed)}/s",
                            end="",
                            flush=True
                        )
                    
                    yield chunk
                
                print()  # New line after progress
        
        start_time = time.time()
        
        response = await self.client.post(
            f"{self.base_url}/upload",
            params={"filename": filename},
            content=file_stream()
        )
        
        elapsed = time.time() - start_time
        
        response.raise_for_status()
        result = response.json()
        
        print(f"βœ… Upload completed in {elapsed:.2f}s")
        print(f"   Unique ID: {result['unique_id']}")
        print(f"   Parts: {result['parts']}")
        print(f"   Download URL: {self.base_url}{result['download_url']}")
        
        return result
    
    async def download_file(
        self,
        unique_id: str,
        output_path: str,
        chunk_size: int = 1024 * 1024  # 1MB chunks
    ):
        """
        Download a file from the streamer
        
        Args:
            unique_id: Unique ID of the file
            output_path: Path to save the downloaded file
            chunk_size: Size of chunks for streaming download
        """
        output_path = Path(output_path)
        
        # Get file info first
        info = await self.get_file_info(unique_id)
        total_size = info["total_size"]
        
        print(f"πŸ“₯ Downloading: {info['filename']}")
        print(f"   Size: {self._format_size(total_size)}")
        
        start_time = time.time()
        downloaded = 0
        
        async with self.client.stream(
            "GET",
            f"{self.base_url}/dl/{unique_id}"
        ) as response:
            response.raise_for_status()
            
            with open(output_path, "wb") as f:
                async for chunk in response.aiter_bytes(chunk_size):
                    f.write(chunk)
                    downloaded += len(chunk)
                    
                    # Progress
                    elapsed = time.time() - start_time
                    if elapsed > 0:
                        speed = downloaded / elapsed
                        progress = (downloaded / total_size) * 100
                        print(
                            f"\r   Progress: {progress:.1f}% "
                            f"({self._format_size(downloaded)}/{self._format_size(total_size)}) "
                            f"Speed: {self._format_size(speed)}/s",
                            end="",
                            flush=True
                        )
        
        print()  # New line after progress
        elapsed = time.time() - start_time
        
        print(f"βœ… Download completed in {elapsed:.2f}s")
        print(f"   Saved to: {output_path}")
    
    async def download_range(
        self,
        unique_id: str,
        start: int,
        end: int,
        output_path: str
    ):
        """
        Download a specific byte range from a file
        
        Args:
            unique_id: Unique ID of the file
            start: Start byte position
            end: End byte position (inclusive)
            output_path: Path to save the downloaded chunk
        """
        output_path = Path(output_path)
        
        print(f"πŸ“₯ Downloading range: bytes {start}-{end}")
        
        response = await self.client.get(
            f"{self.base_url}/dl/{unique_id}",
            headers={"Range": f"bytes={start}-{end}"}
        )
        
        response.raise_for_status()
        
        if response.status_code != 206:
            print(f"⚠️  Warning: Expected 206 Partial Content, got {response.status_code}")
        
        with open(output_path, "wb") as f:
            f.write(response.content)
        
        print(f"βœ… Downloaded {len(response.content)} bytes to {output_path}")
    
    async def get_file_info(self, unique_id: str) -> dict:
        """Get file metadata"""
        response = await self.client.get(f"{self.base_url}/info/{unique_id}")
        response.raise_for_status()
        return response.json()
    
    async def delete_file(self, unique_id: str) -> dict:
        """Delete a file"""
        response = await self.client.delete(f"{self.base_url}/delete/{unique_id}")
        response.raise_for_status()
        return response.json()
    
    async def health_check(self) -> dict:
        """Check server health"""
        response = await self.client.get(f"{self.base_url}/health")
        response.raise_for_status()
        return response.json()
    
    @staticmethod
    def _format_size(size_bytes: int) -> str:
        """Format byte size to human-readable string"""
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size_bytes < 1024.0:
                return f"{size_bytes:.2f} {unit}"
            size_bytes /= 1024.0
        return f"{size_bytes:.2f} PB"


async def example_upload():
    """Example: Upload a file"""
    client = TelegramStreamerClient()
    
    try:
        # Create a test file
        test_file = "test_upload.bin"
        print(f"Creating test file: {test_file} (10MB)")
        with open(test_file, "wb") as f:
            f.write(os.urandom(10 * 1024 * 1024))  # 10MB
        
        # Upload
        result = await client.upload_file(test_file)
        unique_id = result["unique_id"]
        
        # Get info
        print("\nπŸ“Š File Info:")
        info = await client.get_file_info(unique_id)
        for key, value in info.items():
            print(f"   {key}: {value}")
        
        # Cleanup
        os.remove(test_file)
        
        return unique_id
    
    finally:
        await client.close()


async def example_download(unique_id: str):
    """Example: Download a file"""
    client = TelegramStreamerClient()
    
    try:
        output_file = "downloaded_file.bin"
        await client.download_file(unique_id, output_file)
        
        # Cleanup
        if os.path.exists(output_file):
            os.remove(output_file)
    
    finally:
        await client.close()


async def example_range_request(unique_id: str):
    """Example: Download a specific range"""
    client = TelegramStreamerClient()
    
    try:
        # Download first 1MB
        output_file = "range_chunk.bin"
        await client.download_range(unique_id, 0, 1024 * 1024 - 1, output_file)
        
        # Cleanup
        if os.path.exists(output_file):
            os.remove(output_file)
    
    finally:
        await client.close()


async def main():
    """Main example"""
    print("=" * 60)
    print("Telegram Multi-Part File Streamer - Example Client")
    print("=" * 60)
    print()
    
    # Check server health
    client = TelegramStreamerClient()
    try:
        health = await client.health_check()
        print(f"πŸ₯ Server Status: {health['status']}")
        print(f"   Sessions: {health['sessions']}")
        print(f"   Database: {health['database']}")
        print()
    except Exception as e:
        print(f"❌ Server not available: {str(e)}")
        print("   Make sure the server is running!")
        return
    finally:
        await client.close()
    
    # Example 1: Upload
    print("\n" + "=" * 60)
    print("Example 1: Upload")
    print("=" * 60)
    unique_id = await example_upload()
    
    # Example 2: Download
    print("\n" + "=" * 60)
    print("Example 2: Download")
    print("=" * 60)
    await example_download(unique_id)
    
    # Example 3: Range Request
    print("\n" + "=" * 60)
    print("Example 3: Range Request")
    print("=" * 60)
    await example_range_request(unique_id)
    
    # Cleanup: Delete the file
    print("\n" + "=" * 60)
    print("Cleanup")
    print("=" * 60)
    client = TelegramStreamerClient()
    try:
        result = await client.delete_file(unique_id)
        print(f"πŸ—‘οΈ  Deleted file: {unique_id}")
        print(f"   Deleted parts: {result['deleted_parts']}/{result['total_parts']}")
    finally:
        await client.close()
    
    print("\nβœ… All examples completed!")


if __name__ == "__main__":
    asyncio.run(main())