rspx 0.1.0

Pixiv client writen in Rust
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# HTTP Client Architecture

## Overview

PixivPy's HTTP client is built around Python's `requests` library with enhancements for Cloudflare bypass and specialized network handling. This document details the HTTP client architecture, configuration, and implementation patterns for porting to Rust.

## Core HTTP Components

### 1. BasePixivAPI HTTP Configuration

```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

class BasePixivAPI:
    USER_AGENT = "PixivIOSApp/7.13.3 (iOS 14.6; iPhone13,2)"
    CLIENT_ID = "MOBrBDS8blbauoSck0ZfDbtuzpyT"
    CLIENT_SECRET = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"
    HASH_SECRET = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"

    def __init__(self, **kwargs):
        self.session = requests.Session()
        self._setup_session(**kwargs)
        self.access_token = None
        self.refresh_token = None
```

### 2. Session Configuration

```python
def _setup_session(self, proxies=None, timeout=10, verify_ssl=True):
    """Configure the HTTP session with retry strategy"""

    # Retry strategy
    retry_strategy = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET", "POST", "DELETE"]
    )

    # HTTP adapter with retry
    adapter = HTTPAdapter(
        max_retries=retry_strategy,
        pool_connections=10,
        pool_maxsize=10
    )

    # Mount adapters
    self.session.mount("http://", adapter)
    self.session.mount("https://", adapter)

    # Default headers
    self.session.headers.update({
        "User-Agent": self.USER_AGENT,
        "Accept-Language": "en-us"
    })

    # Proxy configuration
    if proxies:
        self.session.proxies.update(proxies)

    # SSL verification
    if not verify_ssl:
        self.session.verify = False
        import urllib3
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    # Timeout
    self.timeout = timeout
```

## Request Methods Implementation

### 1. Generic GET Request

```python
def requests_call(
    self,
    method,
    url,
    params=None,
    data=None,
    headers=None,
    json_data=None,
    stream=False
):
    """Generic request method with error handling"""

    # Prepare request
    req_headers = self.session.headers.copy()
    if headers:
        req_headers.update(headers)

    # Add authentication if available
    if self.access_token:
        req_headers["Authorization"] = f"Bearer {self.access_token}"

    try:
        # Execute request
        response = self.session.request(
            method=method,
            url=url,
            params=params,
            data=data,
            json=json_data,
            headers=req_headers,
            stream=stream,
            timeout=self.timeout
        )

        # Check for errors
        if response.status_code >= 400:
            self._handle_error(response)

        # Return based on response type
        if stream:
            return response
        else:
            return response.json()

    except requests.exceptions.Timeout:
        raise PixivError("Request timeout")
    except requests.exceptions.ConnectionError:
        raise PixivError("Connection error")
    except requests.exceptions.RequestException as e:
        raise PixivError(f"Request failed: {str(e)}")
```

### 2. Simplified Methods

```python
def get(self, url, params=None, **kwargs):
    """Simplified GET request"""
    return self.requests_call("GET", url, params=params, **kwargs)

def post(self, url, data=None, **kwargs):
    """Simplified POST request"""
    return self.requests_call("POST", url, data=data, **kwargs)

def delete(self, url, **kwargs):
    """Simplified DELETE request"""
    return self.requests_call("DELETE", url, **kwargs)
```

## Cloudflare Bypass Integration

### 1. Cloudscraper Integration

```python
import cloudscraper

class BasePixivAPI:
    def __init__(self, **kwargs):
        self.use_cloudscraper = kwargs.get("cloudflare_bypass", True)
        if self.use_cloudscraper:
            self._setup_cloudscraper_session(**kwargs)
        else:
            self._setup_session(**kwargs)

    def _setup_cloudscraper_session(self, **kwargs):
        """Setup session with Cloudflare bypass"""
        self.session = cloudscraper.create_scraper(
            browser={
                'browser': 'chrome',
                'platform': 'ios',
                'desktop': False
            }
        )

        # Apply additional configuration
        self._apply_session_config(**kwargs)
```

### 2. Fallback Mechanism

```python
def _make_request_with_fallback(self, method, url, **kwargs):
    """Make request with fallback to regular requests"""
    try:
        # Try with cloudscraper first
        if self.use_cloudscraper:
            return self.requests_call(method, url, **kwargs)
        else:
            raise requests.RequestException("Cloudscraper disabled")

    except (requests.RequestException, Exception) as e:
        if self.use_cloudscraper:
            # Fallback to regular requests
            self._setup_regular_session()
            return self.requests_call(method, url, **kwargs)
        else:
            raise
```

## File Download Implementation

### 1. Download Method

```python
import os
import urllib.parse
from pathlib import Path

def download(
    self,
    url,
    path=None,
    prefix=None,
    ext=None,
    replace=False,
    referer="https://app-api.pixiv.net/"
):
    """Download file with proper referer and progress"""

    # Parse URL for filename
    parsed_url = urllib.parse.urlparse(url)
    filename = os.path.basename(parsed_url.path)

    # Determine file path
    if path:
        path_obj = Path(path)
        if path_obj.is_dir():
            filename = path_obj / filename
        else:
            filename = path_obj

    # Add prefix
    if prefix:
        filename = Path(filename).with_name(f"{prefix}{Path(filename).name}")

    # Override extension
    if ext and not ext.startswith('.'):
        ext = f".{ext}"
    if ext:
        filename = Path(filename).with_suffix(ext)

    # Check if file exists
    if not replace and Path(filename).exists():
        print(f"File already exists: {filename}")
        return str(filename)

    # Create directory if needed
    Path(filename).parent.mkdir(parents=True, exist_ok=True)

    # Download with streaming
    headers = {"Referer": referer}

    try:
        response = self.requests_call(
            "GET",
            url,
            headers=headers,
            stream=True
        )

        # Save file
        with open(filename, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)

        print(f"Downloaded: {filename}")
        return str(filename)

    except Exception as e:
        raise PixivError(f"Download failed: {str(e)}")
```

### 2. Batch Download

```python
def download_batch(
    self,
    urls,
    directory=None,
    max_workers=5,
    **kwargs
):
    """Download multiple files concurrently"""

    from concurrent.futures import ThreadPoolExecutor, as_completed

    if directory:
        Path(directory).mkdir(parents=True, exist_ok=True)

    results = []

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # Submit all download tasks
        future_to_url = {
            executor.submit(self.download, url, **kwargs): url
            for url in urls
        }

        # Collect results
        for future in as_completed(future_to_url):
            url = future_to_url[future]
            try:
                result = future.result()
                results.append((url, result, None))
            except Exception as e:
                results.append((url, None, str(e)))

    return results
```

## Connection Pooling and Performance

### 1. Connection Management

```python
def _optimize_connection_pool(self):
    """Optimize connection pool for performance"""

    # Increase pool size for concurrent requests
    adapter = HTTPAdapter(
        pool_connections=20,
        pool_maxsize=20,
        max_retries=Retry(
            total=3,
            backoff_factor=0.5,
            status_forcelist=[429, 503]
        )
    )

    self.session.mount("http://", adapter)
    self.session.mount("https://", adapter)
```

### 2. Keep-Alive Configuration

```python
def _enable_keep_alive(self):
    """Enable HTTP keep-alive for better performance"""

    from requests.packages.urllib3.connection import HTTPConnection

    # Patch connection class to add keep-alive
    class KeepAliveHTTPConnection(HTTPConnection):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

    # Use the patched connection
    self.session.mount('http://', HTTPAdapter())
```

## Rate Limiting

### 1. Built-in Rate Limiting

```python
import time
import threading
from collections import deque

class RateLimiter:
    def __init__(self, calls=100, period=60):
        self.calls = calls
        self.period = period
        self.times = deque()
        self.lock = threading.Lock()

    def wait(self):
        with self.lock:
            now = time.time()

            # Remove old timestamps
            while self.times and self.times[0] < now - self.period:
                self.times.popleft()

            # Check if we've exceeded the limit
            if len(self.times) >= self.calls:
                sleep_time = self.period - (now - self.times[0])
                if sleep_time > 0:
                    time.sleep(sleep_time)

            # Add current timestamp
            self.times.append(now)

# Usage in HTTP client
class BasePixivAPI:
    def __init__(self, **kwargs):
        self.rate_limiter = RateLimiter(calls=100, period=60)

    def requests_call(self, method, url, **kwargs):
        self.rate_limiter.wait()
        # ... proceed with request
```

## Error Handling in HTTP Layer

### 1. HTTP Error Types

```python
class PixivError(Exception):
    def __init__(self, reason, header=None, body=None):
        self.reason = reason
        self.header = header
        self.body = body
        super().__init__(reason)

class PixivHTTPError(PixivError):
    def __init__(self, status_code, message, response):
        self.status_code = status_code
        self.response = response
        super().__init__(f"HTTP {status_code}: {message}")

class PixivRateLimitError(PixivHTTPError):
    def __init__(self, retry_after=None, **kwargs):
        self.retry_after = retry_after
        super().__init__(status_code=429, message="Rate limited", **kwargs)

class PixivAuthError(PixivHTTPError):
    def __init__(self, **kwargs):
        super().__init__(status_code=401, message="Authentication failed", **kwargs)
```

### 2. Error Response Handling

```python
def _handle_error(self, response):
    """Handle HTTP error responses"""

    status_code = response.status_code
    message = response.reason

    # Try to get error details from body
    try:
        body = response.json()
        if body.get("error"):
            message = body["error"]["message"]
    except:
        body = response.text

    # Specific error handling
    if status_code == 401:
        raise PixivAuthError(
            header=response.headers,
            body=body
        )
    elif status_code == 429:
        retry_after = response.headers.get("Retry-After")
        raise PixivRateLimitError(
            retry_after=retry_after,
            header=response.headers,
            body=body
        )
    else:
        raise PixivHTTPError(
            status_code=status_code,
            message=message,
            response=response
        )
```

## Proxy Support

### 1. Proxy Configuration

```python
def setup_proxies(self, proxies=None):
    """Configure proxy settings"""

    if proxies is None:
        # Read from environment
        import os
        proxies = {
            'http': os.getenv('HTTP_PROXY'),
            'https': os.getenv('HTTPS_PROXY'),
            'no_proxy': os.getenv('NO_PROXY')
        }

    # Remove None values
    proxies = {k: v for k, v in proxies.items() if v}

    if proxies:
        self.session.proxies.update(proxies)
```

### 2. Proxy Authentication

```python
def setup_proxy_auth(self, proxy_user=None, proxy_pass=None):
    """Configure proxy authentication"""

    if proxy_user and proxy_pass:
        from requests.auth import HTTPProxyAuth

        self.session.auth = HTTPProxyAuth(
            proxy_user,
            proxy_pass
        )
```

## Rust Implementation Considerations

### 1. HTTP Client Selection
```rust
use reqwest::{Client, Response, RequestBuilder};
use std::time::Duration;

#[derive(Debug, Clone)]
pub struct PixivHttpClient {
    client: Client,
    access_token: Option<String>,
    rate_limiter: RateLimiter,
}

impl PixivHttpClient {
    pub fn new() -> Result<Self, PixivError> {
        let client = Client::builder()
            .user_agent("PixivIOSApp/7.13.3 (iOS 14.6; iPhone13,2)")
            .default_headers(self.default_headers())
            .timeout(Duration::from_secs(10))
            .pool_max_idle_per_host(20)
            .pool_idle_timeout(Duration::from_secs(60))
            .build()?;

        Ok(Self {
            client,
            access_token: None,
            rate_limiter: RateLimiter::new(100, Duration::from_secs(60)),
        })
    }
}
```

### 2. Custom Cloudflare Bypass
```rust
#[cfg(feature = "cloudflare-bypass")]
use cloudflare_bypass::{CloudflareBypass, BypassConfig};

#[derive(Debug, Clone)]
pub struct PixivHttpClient {
    #[cfg(feature = "cloudflare-bypass")]
    cf_bypass: Option<CloudflareBypass>,
    // ... other fields
}

impl PixivHttpClient {
    pub async fn request_with_bypass(
        &self,
        method: reqwest::Method,
        url: &str,
    ) -> Result<Response, PixivError> {
        // Try regular request first
        let result = self.make_request(&method, url).await;

        // If it fails with Cloudflare error, try bypass
        if let Err(PixivError::CloudflareProtected) = result {
            if let Some(bypass) = &self.cf_bypass {
                let real_ip = bypass.resolve_ip(url).await?;
                return self.make_request_to_ip(&method, url, &real_ip).await;
            }
        }

        result
    }
}
```

### 3. Async Download Implementation
```rust
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use futures_util::StreamExt;

impl PixivHttpClient {
    pub async fn download(
        &self,
        url: &str,
        path: &Path,
        referer: Option<&str>,
    ) -> Result<PathBuf, PixivError> {
        let mut headers = HeaderMap::new();
        if let Some(r) = referer {
            headers.insert("Referer", r.parse()?);
        }

        let response = self
            .client
            .get(url)
            .headers(headers)
            .send()
            .await?;

        if !response.status().is_success() {
            return Err(PixivError::HttpError(response.status().as_u16()));
        }

        // Ensure directory exists
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }

        // Stream download
        let mut file = File::create(path).await?;
        let mut stream = response.bytes_stream();

        use futures_util::StreamExt;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            file.write_all(&chunk).await?;
        }

        file.flush().await?;
        Ok(path.to_path_buf())
    }
}
```

### 4. Connection Pool Configuration
```rust
use reqwest::redirect::Policy;

impl PixivHttpClient {
    fn configure_client() -> ClientBuilder {
        Client::builder()
            .connection_verbose(true)
            .pool_idle_timeout(Duration::from_secs(60))
            .pool_max_idle_per_host(20)
            .tcp_keepalive(Duration::from_secs(30))
            .http2_keep_alive_interval(Duration::from_secs(15))
            .http2_keep_alive_timeout(Duration::from_secs(10))
            .http2_keep_alive_while_idle(true)
            .redirect(Policy::limited(5))
    }
}
```

### 5. Rate Limiting Implementation
```rust
use std::time::{Duration, Instant};
use tokio::time::sleep;

#[derive(Debug)]
pub struct RateLimiter {
    max_requests: u32,
    window: Duration,
    requests: Vec<Instant>,
}

impl RateLimiter {
    pub fn new(max_requests: u32, window: Duration) -> Self {
        Self {
            max_requests,
            window,
            requests: Vec::new(),
        }
    }

    pub async fn acquire(&mut self) {
        let now = Instant::now();

        // Remove old requests outside window
        self.requests.retain(|&t| now.duration_since(t) < self.window);

        // Check if we need to wait
        if self.requests.len() >= self.max_requests as usize {
            let oldest = self.requests[0];
            let wait_time = self.window - now.duration_since(oldest);
            sleep(wait_time).await;
        }

        self.requests.push(now);
    }
}
```

## Best Practices

1. **Use connection pooling** for performance
2. **Implement proper timeouts** to prevent hanging
3. **Handle rate limits gracefully** with backoff
4. **Use streaming for large downloads** to manage memory
5. **Maintain proper headers** including referer for images
6. **Implement retry logic** for transient errors
7. **Log request/response details** for debugging
8. **Validate SSL certificates** unless bypass is needed
9. **Use async/await** for non-blocking operations
10. **Monitor connection metrics** for performance optimization