dx-driven 0.1.0

Professional AI-assisted development orchestrator with binary-first architecture
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
//! # GIF Integration
//!
//! GIF search and creation via Giphy/Tenor APIs.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::gif::{GifClient, GifConfig};
//!
//! let config = GifConfig::from_file("~/.dx/config/gif.sr")?;
//! let client = GifClient::new(&config)?;
//!
//! // Search for GIFs
//! let gifs = client.search("happy cat").await?;
//!
//! // Get trending GIFs
//! let trending = client.trending(10).await?;
//! ```

use crate::error::{DrivenError, Result};
use serde::{Deserialize, Serialize};

/// GIF configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GifConfig {
    /// Whether GIF integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Giphy API key
    #[serde(default)]
    pub giphy_api_key: String,
    /// Tenor API key
    #[serde(default)]
    pub tenor_api_key: String,
    /// Preferred provider
    #[serde(default)]
    pub preferred_provider: GifProvider,
    /// Default limit for search results
    #[serde(default = "default_limit")]
    pub default_limit: u32,
    /// Content rating filter
    #[serde(default)]
    pub rating: ContentRating,
}

fn default_true() -> bool {
    true
}

fn default_limit() -> u32 {
    25
}

impl Default for GifConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            giphy_api_key: String::new(),
            tenor_api_key: String::new(),
            preferred_provider: GifProvider::Giphy,
            default_limit: default_limit(),
            rating: ContentRating::G,
        }
    }
}

impl GifConfig {
    /// Load from .sr config file
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| DrivenError::Io(e))?;
        Self::parse_sr(&content)
    }

    fn parse_sr(_content: &str) -> Result<Self> {
        Ok(Self::default())
    }

    /// Resolve environment variables
    pub fn resolve_env_vars(&mut self) {
        if self.giphy_api_key.is_empty() || self.giphy_api_key.starts_with('$') {
            self.giphy_api_key = std::env::var("GIPHY_API_KEY").unwrap_or_default();
        }
        if self.tenor_api_key.is_empty() || self.tenor_api_key.starts_with('$') {
            self.tenor_api_key = std::env::var("TENOR_API_KEY").unwrap_or_default();
        }
    }
}

/// GIF provider
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum GifProvider {
    #[default]
    Giphy,
    Tenor,
}

/// Content rating
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ContentRating {
    /// General audiences
    #[default]
    G,
    /// Parental guidance suggested
    PG,
    /// Parents strongly cautioned
    PG13,
    /// Restricted (Giphy only)
    R,
}

impl ContentRating {
    fn to_giphy_string(&self) -> &str {
        match self {
            ContentRating::G => "g",
            ContentRating::PG => "pg",
            ContentRating::PG13 => "pg-13",
            ContentRating::R => "r",
        }
    }

    fn to_tenor_string(&self) -> &str {
        match self {
            ContentRating::G => "off",
            ContentRating::PG => "low",
            ContentRating::PG13 => "medium",
            ContentRating::R => "high",
        }
    }
}

/// GIF result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Gif {
    /// Unique ID
    pub id: String,
    /// Title
    pub title: String,
    /// Original URL
    pub url: String,
    /// Source URL (webpage)
    pub source_url: String,
    /// GIF images in various formats
    pub images: GifImages,
    /// Username of uploader
    pub username: Option<String>,
    /// Import datetime
    pub import_datetime: Option<String>,
    /// Provider
    pub provider: GifProvider,
}

/// GIF images in various formats
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GifImages {
    /// Original size
    pub original: GifImage,
    /// Fixed height (200px)
    pub fixed_height: GifImage,
    /// Fixed width (200px)
    pub fixed_width: GifImage,
    /// Thumbnail/preview
    pub preview: Option<GifImage>,
    /// Still image
    pub still: Option<GifImage>,
}

/// Single GIF image
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GifImage {
    /// URL
    pub url: String,
    /// Width
    pub width: u32,
    /// Height
    pub height: u32,
    /// File size in bytes
    pub size: Option<u64>,
    /// MP4 URL (if available)
    pub mp4: Option<String>,
    /// WebP URL (if available)
    pub webp: Option<String>,
}

/// GIF client
pub struct GifClient {
    config: GifConfig,
}

impl GifClient {
    /// Create a new GIF client
    pub fn new(config: &GifConfig) -> Result<Self> {
        let mut config = config.clone();
        config.resolve_env_vars();

        Ok(Self { config })
    }

    /// Check if client is configured
    pub fn is_configured(&self) -> bool {
        self.config.enabled
            && (!self.config.giphy_api_key.is_empty()
                || !self.config.tenor_api_key.is_empty())
    }

    /// Search for GIFs
    pub async fn search(&self, query: &str) -> Result<Vec<Gif>> {
        self.search_with_limit(query, self.config.default_limit).await
    }

    /// Search for GIFs with limit
    pub async fn search_with_limit(&self, query: &str, limit: u32) -> Result<Vec<Gif>> {
        match self.config.preferred_provider {
            GifProvider::Giphy => self.search_giphy(query, limit).await,
            GifProvider::Tenor => self.search_tenor(query, limit).await,
        }
    }

    /// Get trending GIFs
    pub async fn trending(&self, limit: u32) -> Result<Vec<Gif>> {
        match self.config.preferred_provider {
            GifProvider::Giphy => self.trending_giphy(limit).await,
            GifProvider::Tenor => self.trending_tenor(limit).await,
        }
    }

    /// Get a random GIF
    pub async fn random(&self, tag: Option<&str>) -> Result<Gif> {
        match self.config.preferred_provider {
            GifProvider::Giphy => self.random_giphy(tag).await,
            GifProvider::Tenor => {
                // Tenor doesn't have random, so search and pick first
                let query = tag.unwrap_or("funny");
                let results = self.search_tenor(query, 1).await?;
                results.into_iter().next().ok_or_else(|| {
                    DrivenError::NotFound("No GIF found".into())
                })
            }
        }
    }

    /// Get GIF by ID
    pub async fn get_by_id(&self, id: &str) -> Result<Gif> {
        self.get_giphy_by_id(id).await
    }

    // Giphy API

    async fn search_giphy(&self, query: &str, limit: u32) -> Result<Vec<Gif>> {
        let url = format!(
            "https://api.giphy.com/v1/gifs/search?api_key={}&q={}&limit={}&rating={}",
            self.config.giphy_api_key,
            urlencoding::encode(query),
            limit,
            self.config.rating.to_giphy_string()
        );

        let response: serde_json::Value = self.api_get(&url).await?;
        self.parse_giphy_results(response)
    }

    async fn trending_giphy(&self, limit: u32) -> Result<Vec<Gif>> {
        let url = format!(
            "https://api.giphy.com/v1/gifs/trending?api_key={}&limit={}&rating={}",
            self.config.giphy_api_key,
            limit,
            self.config.rating.to_giphy_string()
        );

        let response: serde_json::Value = self.api_get(&url).await?;
        self.parse_giphy_results(response)
    }

    async fn random_giphy(&self, tag: Option<&str>) -> Result<Gif> {
        let mut url = format!(
            "https://api.giphy.com/v1/gifs/random?api_key={}&rating={}",
            self.config.giphy_api_key,
            self.config.rating.to_giphy_string()
        );

        if let Some(t) = tag {
            url.push_str(&format!("&tag={}", urlencoding::encode(t)));
        }

        let response: serde_json::Value = self.api_get(&url).await?;
        self.parse_giphy_gif(&response["data"])
    }

    async fn get_giphy_by_id(&self, id: &str) -> Result<Gif> {
        let url = format!(
            "https://api.giphy.com/v1/gifs/{}?api_key={}",
            id,
            self.config.giphy_api_key
        );

        let response: serde_json::Value = self.api_get(&url).await?;
        self.parse_giphy_gif(&response["data"])
    }

    fn parse_giphy_results(&self, response: serde_json::Value) -> Result<Vec<Gif>> {
        let data = response["data"]
            .as_array()
            .ok_or_else(|| DrivenError::Parse("Invalid Giphy response".into()))?;

        data.iter()
            .map(|g| self.parse_giphy_gif(g))
            .collect()
    }

    fn parse_giphy_gif(&self, gif: &serde_json::Value) -> Result<Gif> {
        let images = &gif["images"];

        Ok(Gif {
            id: gif["id"].as_str().unwrap_or_default().to_string(),
            title: gif["title"].as_str().unwrap_or_default().to_string(),
            url: gif["url"].as_str().unwrap_or_default().to_string(),
            source_url: gif["source"].as_str().unwrap_or_default().to_string(),
            username: gif["username"].as_str().map(String::from),
            import_datetime: gif["import_datetime"].as_str().map(String::from),
            provider: GifProvider::Giphy,
            images: GifImages {
                original: self.parse_giphy_image(&images["original"]),
                fixed_height: self.parse_giphy_image(&images["fixed_height"]),
                fixed_width: self.parse_giphy_image(&images["fixed_width"]),
                preview: images["preview_gif"].as_object().map(|_| {
                    self.parse_giphy_image(&images["preview_gif"])
                }),
                still: images["original_still"].as_object().map(|_| {
                    self.parse_giphy_image(&images["original_still"])
                }),
            },
        })
    }

    fn parse_giphy_image(&self, img: &serde_json::Value) -> GifImage {
        GifImage {
            url: img["url"].as_str().unwrap_or_default().to_string(),
            width: img["width"]
                .as_str()
                .and_then(|s| s.parse().ok())
                .unwrap_or(0),
            height: img["height"]
                .as_str()
                .and_then(|s| s.parse().ok())
                .unwrap_or(0),
            size: img["size"]
                .as_str()
                .and_then(|s| s.parse().ok()),
            mp4: img["mp4"].as_str().map(String::from),
            webp: img["webp"].as_str().map(String::from),
        }
    }

    // Tenor API

    async fn search_tenor(&self, query: &str, limit: u32) -> Result<Vec<Gif>> {
        let url = format!(
            "https://tenor.googleapis.com/v2/search?key={}&q={}&limit={}&contentfilter={}",
            self.config.tenor_api_key,
            urlencoding::encode(query),
            limit,
            self.config.rating.to_tenor_string()
        );

        let response: serde_json::Value = self.api_get(&url).await?;
        self.parse_tenor_results(response)
    }

    async fn trending_tenor(&self, limit: u32) -> Result<Vec<Gif>> {
        let url = format!(
            "https://tenor.googleapis.com/v2/featured?key={}&limit={}&contentfilter={}",
            self.config.tenor_api_key,
            limit,
            self.config.rating.to_tenor_string()
        );

        let response: serde_json::Value = self.api_get(&url).await?;
        self.parse_tenor_results(response)
    }

    fn parse_tenor_results(&self, response: serde_json::Value) -> Result<Vec<Gif>> {
        let results = response["results"]
            .as_array()
            .ok_or_else(|| DrivenError::Parse("Invalid Tenor response".into()))?;

        Ok(results
            .iter()
            .map(|g| self.parse_tenor_gif(g))
            .collect())
    }

    fn parse_tenor_gif(&self, gif: &serde_json::Value) -> Gif {
        let media = &gif["media_formats"];

        Gif {
            id: gif["id"].as_str().unwrap_or_default().to_string(),
            title: gif["content_description"].as_str().unwrap_or_default().to_string(),
            url: gif["url"].as_str().unwrap_or_default().to_string(),
            source_url: gif["itemurl"].as_str().unwrap_or_default().to_string(),
            username: None,
            import_datetime: gif["created"].as_f64().map(|t| t.to_string()),
            provider: GifProvider::Tenor,
            images: GifImages {
                original: self.parse_tenor_image(&media["gif"]),
                fixed_height: self.parse_tenor_image(&media["tinygif"]),
                fixed_width: self.parse_tenor_image(&media["tinygif"]),
                preview: media["nanogif"].as_object().map(|_| {
                    self.parse_tenor_image(&media["nanogif"])
                }),
                still: None,
            },
        }
    }

    fn parse_tenor_image(&self, media: &serde_json::Value) -> GifImage {
        GifImage {
            url: media["url"].as_str().unwrap_or_default().to_string(),
            width: media["dims"][0].as_u64().unwrap_or(0) as u32,
            height: media["dims"][1].as_u64().unwrap_or(0) as u32,
            size: media["size"].as_u64(),
            mp4: None,
            webp: None,
        }
    }

    async fn api_get(&self, url: &str) -> Result<serde_json::Value> {
        let client = reqwest::Client::new();
        let response = client
            .get(url)
            .send()
            .await
            .map_err(|e| DrivenError::Network(e.to_string()))?;

        if !response.status().is_success() {
            let error = response.text().await.unwrap_or_default();
            return Err(DrivenError::Api(format!("GIF API error: {}", error)));
        }

        response
            .json()
            .await
            .map_err(|e| DrivenError::Parse(e.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = GifConfig::default();
        assert!(config.enabled);
        assert_eq!(config.default_limit, 25);
    }

    #[test]
    fn test_content_rating_strings() {
        assert_eq!(ContentRating::G.to_giphy_string(), "g");
        assert_eq!(ContentRating::PG13.to_giphy_string(), "pg-13");
        assert_eq!(ContentRating::G.to_tenor_string(), "off");
    }
}