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
// Copyright (C) 2023 Andreas Hartmann <hartan@7x.de>
// GNU General Public License v3.0+ (https://www.gnu.org/licenses/gpl-3.0.txt)
// SPDX-License-Identifier: GPL-3.0-or-later

//! Search packages with Flatpak.

use crate::provider::prelude::*;

#[derive(Debug, Default, PartialEq)]
pub struct Flatpak {}

impl Flatpak {
    pub fn new() -> Self {
        Default::default()
    }
}

impl fmt::Display for Flatpak {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Flatpak")
    }
}

#[async_trait]
impl IsProvider for Flatpak {
    async fn search_internal(
        &self,
        command: &str,
        target_env: Arc<Environment>,
    ) -> ProviderResult<Vec<Candidate>> {
        let mut state = FlatpakState::default();
        state
            .discover_remotes(&target_env)
            .await
            .map_err(|e| match e {
                RemoteError::Execution(ExecutionError::NotFound(val)) => {
                    ProviderError::Requirements(val)
                }
                RemoteError::Execution(e) => ProviderError::Execution(e),
                err => ProviderError::ApplicationError(anyhow::Error::new(err)),
            })?;

        let candidates = state
            .get_remote_flatpaks(&target_env, command)
            .await
            .map_err(Error::RemoteFlatpaks)?;

        state
            .check_installed_flatpaks(&target_env, candidates)
            .await
            .map_err(Error::LocalFlatpaks)
            .map_err(|e| e.into())
    }
}

#[derive(Debug, Default)]
struct FlatpakState {
    remotes: Vec<Remote>,
}

impl FlatpakState {
    /// Discover all remotes configured in an environment.
    ///
    /// Remotes are stored internally for later use. You must call this function before
    /// [`FlatpakState::get_remote_flatpaks()`] or [`FlatpakState::check_installed_flatpaks()`].
    pub async fn discover_remotes(&mut self, env: &Arc<Environment>) -> Result<(), RemoteError> {
        let stdout = env
            .output_of(cmd!("flatpak", "remotes", "--columns=name:f,options:f"))
            .await?;

        // When there is no result, flatpak will still at least print a single newline char.
        if stdout.trim().is_empty() {
            return Err(RemoteError::NoRemote);
        }

        for line in stdout.lines() {
            match line.split_once('\t') {
                Some((name, opts)) => {
                    let remote_type = if opts.contains("user") {
                        RemoteType::User
                    } else if opts.contains("system") {
                        RemoteType::System
                    } else {
                        return Err(RemoteError::UnknownType(opts.to_string()));
                    };

                    let remote = Remote {
                        name: name.to_string(),
                        r#type: remote_type,
                    };

                    self.remotes.push(remote);
                }
                None => return Err(RemoteError::Parse(stdout)),
            }
        }

        Ok(())
    }

    /// Retrieves all flatpaks in all remotes and filters them.
    ///
    /// Filtering is performed by performing a case-insensitive match against the `search_for`
    /// argument. No fuzzy matching or similar is currently used.
    pub async fn get_remote_flatpaks(
        &mut self,
        env: &Arc<Environment>,
        search_for: &str,
    ) -> Result<Vec<Candidate>, RemoteFlatpakError> {
        // Sanity checks. No reason to be friendly here, this is a simple usage error.
        debug_assert!(
            !self.remotes.is_empty(),
            "cannot query remote flatpaks without a remote"
        );
        let mut candidates: Vec<Candidate> = vec![];

        for remote in &self.remotes {
            let output = env
                .output_of(cmd!(
                    "flatpak",
                    "remote-ls",
                    "--app",
                    "--cached",
                    "--columns=application:f,version:f,origin:f,description:f",
                    &remote.r#type.to_cli(),
                    &remote.name
                ))
                .await
                .map_err(|e| RemoteFlatpakError::Execution {
                    remote: remote.clone(),
                    source: e,
                })?;

            'next_line: for line in output.lines() {
                let mut candidate = Candidate::default();
                for (index, split) in line.split('\t').enumerate() {
                    match index {
                        0 => {
                            if split.to_lowercase().contains(&search_for.to_lowercase()) {
                                candidate.package = split.to_string();
                            } else {
                                continue 'next_line;
                            }
                        }
                        1 => candidate.version = split.to_string(),
                        2 => candidate.origin = remote.to_origin(),
                        3 => candidate.description = split.to_string(),
                        _ => log::warn!("superfluous fragment '{}' in line '{}'", split, line),
                    }
                }

                if !candidate.package.is_empty() {
                    let mut install_action = cmd!(
                        "flatpak",
                        "install",
                        "--app",
                        &remote.r#type.to_cli(),
                        &remote.name,
                        &candidate.package
                    );
                    install_action.needs_privileges(matches!(remote.r#type, RemoteType::System));
                    candidate.actions.install = Some(install_action);

                    candidate.actions.execute = cmd!(
                        "flatpak".to_string(),
                        "run".to_string(),
                        remote.r#type.to_cli(),
                        candidate.package.clone()
                    );

                    candidates.push(candidate);
                }
            }
        }

        Ok(candidates)
    }

    /// Take a list of candidates and update their installation status.
    ///
    /// Queries the locally installed flatpaks and updates the `action.install` metadata to reflect
    /// the installation status.
    pub async fn check_installed_flatpaks(
        &self,
        env: &Arc<Environment>,
        mut candidates: Vec<Candidate>,
    ) -> Result<Vec<Candidate>, LocalFlatpaksError> {
        let output = env
            .output_of(cmd!(
                "flatpak",
                "list",
                "--app",
                "--columns=application:f,version:f,origin:f,installation:f,description:f"
            ))
            .await?;

        for candidate in candidates.iter_mut() {
            if output.lines().any(|line| {
                let (origin, installation) = candidate
                    .origin
                    .trim_end_matches(')')
                    .split_once(" (")
                    .with_context(|| {
                        format!(
                            "failed to unparse package origin '{}' into origin and installation",
                            candidate.origin
                        )
                    })
                    .to_log()
                    .unwrap_or(("", ""));
                line.contains(&candidate.package)
                    && line.contains(&candidate.version)
                    && line.contains(&candidate.description)
                    && line.contains(origin)
                    && line.contains(installation)
            }) {
                // Already installed
                candidate.actions.install = None;
            }
        }

        Ok(candidates)
    }
}

/// Rust-representation of a configured flatpak remote
#[derive(Debug, Default, PartialEq, Clone)]
pub struct Remote {
    /// Pure name of the remote
    name: String,
    /// Type of remote
    r#type: RemoteType,
}

impl Remote {
    /// Convert a remote into a human-readable origin representation.
    pub fn to_origin(&self) -> String {
        self.to_string()
    }
}

impl fmt::Display for Remote {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} ({})", self.name, self.r#type)
    }
}

/// Types of remote
#[derive(Debug, Default, PartialEq, Clone)]
pub enum RemoteType {
    #[default]
    User,
    System,
    // FIXME(hartan): No idea how to recognize/discover this one
    Other(String),
}

impl RemoteType {
    /// Convert a remote type into an appropriate flatpak CLI flag.
    pub fn to_cli(&self) -> String {
        match self {
            Self::User => "--user".to_string(),
            Self::System => "--system".to_string(),
            Self::Other(val) => format!("--installation={}", val),
        }
    }
}

impl fmt::Display for RemoteType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::User => write!(f, "user"),
            Self::System => write!(f, "system"),
            Self::Other(val) => write!(f, "{}", val),
        }
    }
}

#[derive(Debug, ThisError)]
pub enum Error {
    #[error("failed to obtain remotes to search in")]
    Remote(#[from] RemoteError),

    #[error(transparent)]
    LocalFlatpaks(#[from] LocalFlatpaksError),

    #[error(transparent)]
    RemoteFlatpaks(#[from] RemoteFlatpakError),
}

impl From<Error> for ProviderError {
    fn from(value: Error) -> Self {
        match value {
            Error::Remote(RemoteError::Execution(ExecutionError::NotFound(val))) => {
                ProviderError::Requirements(val)
            }
            _ => ProviderError::ApplicationError(anyhow::Error::new(value)),
        }
    }
}

/// Errors from trying to discover configured flatpak remotes.
#[derive(Debug, ThisError)]
pub enum RemoteError {
    #[error("no configured remote found")]
    NoRemote,

    #[error("failed to parse remote info from output: {0}")]
    Parse(String),

    #[error("failed to determine remote type from options: '{0}'")]
    UnknownType(String),

    #[error("failed to query configured flatpak remotes")]
    Execution(#[from] ExecutionError),
}

#[derive(Debug, ThisError)]
pub enum RemoteFlatpakError {
    #[error("failed to query available applications from remote '{remote}'")]
    Execution {
        remote: Remote,
        source: ExecutionError,
    },
}

#[derive(Debug, ThisError)]
pub enum LocalFlatpaksError {
    #[error("failed to query locally installed flatpaks")]
    Execution(#[from] ExecutionError),
}

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

    test::default_tests!(Flatpak::new());

    #[test]
    fn no_remotes() {
        let query = quick_test!(Flatpak::new(), Ok("\n".to_string()));

        assert::is_err!(query);
        assert::err::application!(query);
    }

    #[test]
    fn single_remote_nonexistent_app() {
        let query = quick_test!(
            Flatpak::new(),
            // The remotes
            Ok("foobar\tuser\n".to_string()),
            // Flatpaks in that remote
            Ok("app.cool.my\t0.12.56-beta\tfoobar\tSome descriptive text\n".to_string()),
            // Locally installed flatpaks
            Ok("\n".to_string())
        );

        assert::is_err!(query);
        assert::err::not_found!(query);
    }

    #[test]
    fn single_remote_matching_app() {
        let query = quick_test!(
            Flatpak::new(),
            // The remotes
            Ok("foobar\tuser\n".to_string()),
            // Flatpaks in that remote
            Ok("app.cool.my-test-app\t0.12.56-beta\tfoobar\tSome descriptive text\n".to_string()),
            // Locally installed flatpaks
            Ok("\n".to_string())
        );

        let result = query.results.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].package, "app.cool.my-test-app".to_string());
        assert_eq!(result[0].origin, "foobar (user)".to_string());
    }
}