aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src-tauri/src/core/java/providers/adoptium.rs
blob: 13ef2a53945215188b852438787616312336e215 (plain) (blame)
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
use crate::core::java::provider::JavaProvider;
use crate::core::java::{ImageType, JavaCatalog, JavaDownloadInfo, JavaError, JavaReleaseInfo};
use serde::Deserialize;
use tauri::AppHandle;

const ADOPTIUM_API_BASE: &str = "https://api.adoptium.net/v3";

#[derive(Debug, Clone, Deserialize)]
pub struct AdoptiumAsset {
    pub binary: AdoptiumBinary,
    pub release_name: String,
    pub version: AdoptiumVersionData,
}

#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct AdoptiumBinary {
    pub os: String,
    pub architecture: String,
    pub image_type: String,
    pub package: AdoptiumPackage,
    #[serde(default)]
    pub updated_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AdoptiumPackage {
    pub name: String,
    pub link: String,
    pub size: u64,
    pub checksum: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct AdoptiumVersionData {
    pub major: u32,
    pub minor: u32,
    pub security: u32,
    pub semver: String,
    pub openjdk_version: String,
}

#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct AvailableReleases {
    pub available_releases: Vec<u32>,
    pub available_lts_releases: Vec<u32>,
    pub most_recent_lts: Option<u32>,
    pub most_recent_feature_release: Option<u32>,
}

pub struct AdoptiumProvider;

impl AdoptiumProvider {
    pub fn new() -> Self {
        Self
    }
}

impl Default for AdoptiumProvider {
    fn default() -> Self {
        Self::new()
    }
}

impl JavaProvider for AdoptiumProvider {
    async fn fetch_catalog(
        &self,
        app_handle: &AppHandle,
        force_refresh: bool,
    ) -> Result<JavaCatalog, JavaError> {
        if !force_refresh {
            if let Ok(Some(cached)) = crate::core::java::load_cached_catalog(app_handle) {
                return Ok(cached);
            }
        }

        let os = self.os_name();
        let arch = self.arch_name();
        let client = reqwest::Client::new();

        let releases_url = format!("{}/info/available_releases", ADOPTIUM_API_BASE);
        let available: AvailableReleases = client
            .get(&releases_url)
            .header("Accept", "application/json")
            .send()
            .await
            .map_err(|e| {
                JavaError::NetworkError(format!("Failed to fetch available releases: {}", e))
            })?
            .json()
            .await
            .map_err(|e| {
                JavaError::SerializationError(format!("Failed to parse available releases: {}", e))
            })?;

        // Parallelize HTTP requests for better performance
        let mut fetch_tasks = Vec::new();

        for major_version in &available.available_releases {
            for image_type in &["jre", "jdk"] {
                let major_version = *major_version;
                let image_type = image_type.to_string();
                let url = format!(
                    "{}/assets/latest/{}/hotspot?os={}&architecture={}&image_type={}",
                    ADOPTIUM_API_BASE, major_version, os, arch, image_type
                );
                let client = client.clone();
                let is_lts = available.available_lts_releases.contains(&major_version);
                let arch = arch.to_string();

                let task = tokio::spawn(async move {
                    match client
                        .get(&url)
                        .header("Accept", "application/json")
                        .send()
                        .await
                    {
                        Ok(response) => {
                            if response.status().is_success() {
                                if let Ok(assets) = response.json::<Vec<AdoptiumAsset>>().await {
                                    if let Some(asset) = assets.into_iter().next() {
                                        let release_date = asset.binary.updated_at.clone();
                                        return Some(JavaReleaseInfo {
                                            major_version,
                                            image_type,
                                            version: asset.version.semver.clone(),
                                            release_name: asset.release_name.clone(),
                                            release_date,
                                            file_size: asset.binary.package.size,
                                            checksum: asset.binary.package.checksum,
                                            download_url: asset.binary.package.link,
                                            is_lts,
                                            is_available: true,
                                            architecture: asset.binary.architecture.clone(),
                                        });
                                    }
                                }
                            }
                            // Fallback for unsuccessful response
                            Some(JavaReleaseInfo {
                                major_version,
                                image_type,
                                version: format!("{}.x", major_version),
                                release_name: format!("jdk-{}", major_version),
                                release_date: None,
                                file_size: 0,
                                checksum: None,
                                download_url: String::new(),
                                is_lts,
                                is_available: false,
                                architecture: arch,
                            })
                        }
                        Err(_) => Some(JavaReleaseInfo {
                            major_version,
                            image_type,
                            version: format!("{}.x", major_version),
                            release_name: format!("jdk-{}", major_version),
                            release_date: None,
                            file_size: 0,
                            checksum: None,
                            download_url: String::new(),
                            is_lts,
                            is_available: false,
                            architecture: arch,
                        }),
                    }
                });
                fetch_tasks.push(task);
            }
        }

        // Collect all results concurrently
        let mut releases = Vec::new();
        for task in fetch_tasks {
            match task.await {
                Ok(Some(release)) => {
                    releases.push(release);
                }
                Ok(None) => {
                    // Task completed but returned None, should not happen in current implementation
                }
                Err(e) => {
                    eprintln!("AdoptiumProvider::fetch_catalog task join error: {:?}", e);
                }
            }
        }

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let catalog = JavaCatalog {
            releases,
            available_major_versions: available.available_releases,
            lts_versions: available.available_lts_releases,
            cached_at: now,
        };

        let _ = super::super::save_catalog_cache(app_handle, &catalog);

        Ok(catalog)
    }

    async fn fetch_release(
        &self,
        major_version: u32,
        image_type: ImageType,
    ) -> Result<JavaDownloadInfo, JavaError> {
        let os = self.os_name();
        let arch = self.arch_name();

        let url = format!(
            "{}/assets/latest/{}/hotspot?os={}&architecture={}&image_type={}",
            ADOPTIUM_API_BASE, major_version, os, arch, image_type
        );

        let client = reqwest::Client::new();
        let response = client
            .get(&url)
            .header("Accept", "application/json")
            .send()
            .await
            .map_err(|e| JavaError::NetworkError(format!("Network request failed: {}", e)))?;

        if !response.status().is_success() {
            return Err(JavaError::NetworkError(format!(
                "Adoptium API returned error: {} - The version/platform might be unavailable",
                response.status()
            )));
        }

        let assets: Vec<AdoptiumAsset> = response.json().await.map_err(|e| {
            JavaError::SerializationError(format!("Failed to parse API response: {}", e))
        })?;

        let asset = assets
            .into_iter()
            .next()
            .ok_or_else(|| JavaError::NotFound)?;

        Ok(JavaDownloadInfo {
            version: asset.version.semver.clone(),
            release_name: asset.release_name,
            download_url: asset.binary.package.link,
            file_name: asset.binary.package.name,
            file_size: asset.binary.package.size,
            checksum: asset.binary.package.checksum,
            image_type: asset.binary.image_type,
        })
    }

    async fn available_versions(&self) -> Result<Vec<u32>, JavaError> {
        let url = format!("{}/info/available_releases", ADOPTIUM_API_BASE);

        let response = reqwest::get(url)
            .await
            .map_err(|e| JavaError::NetworkError(format!("Network request failed: {}", e)))?;

        let releases: AvailableReleases = response.json().await.map_err(|e| {
            JavaError::SerializationError(format!("Failed to parse response: {}", e))
        })?;

        Ok(releases.available_releases)
    }

    fn provider_name(&self) -> &'static str {
        "adoptium"
    }

    fn os_name(&self) -> &'static str {
        #[cfg(target_os = "linux")]
        {
            if std::path::Path::new("/etc/alpine-release").exists() {
                return "alpine-linux";
            }
            "linux"
        }
        #[cfg(target_os = "macos")]
        {
            "mac"
        }
        #[cfg(target_os = "windows")]
        {
            "windows"
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        {
            "linux"
        }
    }

    fn arch_name(&self) -> &'static str {
        #[cfg(target_arch = "x86_64")]
        {
            "x64"
        }
        #[cfg(target_arch = "aarch64")]
        {
            "aarch64"
        }
        #[cfg(target_arch = "x86")]
        {
            "x86"
        }
        #[cfg(target_arch = "arm")]
        {
            "arm"
        }
        #[cfg(not(any(
            target_arch = "x86_64",
            target_arch = "aarch64",
            target_arch = "x86",
            target_arch = "arm"
        )))]
        {
            "x64"
        }
    }

    fn install_prefix(&self) -> &'static str {
        "temurin"
    }
}