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
// SPDX-FileCopyrightText: 2021 HH Partners
//
// SPDX-License-Identifier: MIT

//! Create and get jobs.

use serde::{Deserialize, Serialize};

use crate::{Fossology, FossologyError, FossologyResponse, InfoWithNumber};

/// # Errors
///
/// - Error while sending request, redirect loop was detected or redirect limit was exhausted.
/// - Response can't be serialized to [`Vec`] of [`Job`]s or [`Info`](crate::Info).
/// - Response is not [`Vec`] of [`Job`]s.
pub fn get_jobs(
    fossology: &Fossology,
    upload_id: Option<i32>,
    group_name: Option<String>,
    limit: Option<i32>,
    page: Option<i32>,
) -> Result<Vec<Job>, FossologyError> {
    let mut builder = fossology.init_get_with_token("jobs");

    builder = if let Some(upload_id) = upload_id {
        builder.query(&[("upload", &upload_id.to_string())])
    } else {
        builder
    };

    builder = if let Some(group_name) = group_name {
        builder.header("groupName", group_name)
    } else {
        builder
    };

    builder = if let Some(limit) = limit {
        builder.header("limit", limit)
    } else {
        builder
    };

    builder = if let Some(page) = page {
        builder.header("page", page)
    } else {
        builder
    };

    let response = builder.send()?.json::<FossologyResponse<Vec<Job>>>()?;

    match response {
        FossologyResponse::Response(res) => Ok(res),
        FossologyResponse::ApiError(err) => Err(FossologyError::Other(err.message)),
    }
}

/// # Errors
///
/// - Error while sending request, redirect loop was detected or redirect limit was exhausted.
/// - Response can't be serialized to [`ScheduledJob`] or [`Info`](crate::Info).
/// - Response is not [`ScheduledJob`].
pub fn schedule_analysis(
    fossology: &Fossology,
    folder_id: i32,
    upload_id: i32,
    group_name: Option<String>,
    analysis: &ScheduleAgents,
) -> Result<ScheduledJob, FossologyError> {
    let mut builder = fossology.init_post_with_token("jobs").json(analysis);

    builder = if let Some(group_name) = group_name {
        builder.header("groupName", group_name)
    } else {
        builder
    };

    let response = builder
        .header("folderId", folder_id.to_string())
        .header("uploadId", upload_id.to_string())
        .json(analysis)
        .send()?
        .json::<FossologyResponse<InfoWithNumber>>()?;

    match response {
        FossologyResponse::Response(res) => Ok(ScheduledJob { id: res.message }),
        FossologyResponse::ApiError(err) => Err(FossologyError::Other(err.message)),
    }
}

#[derive(Debug, Serialize)]
pub struct ScheduledJob {
    pub id: i32,
}

#[derive(Debug, Serialize, Default)]
pub struct ScheduleAgents {
    pub analysis: Analysis,
    pub decider: Decider,
    pub reuse: Reuse,
}

#[derive(Debug, Serialize, Default)]
pub struct Analysis {
    pub bucket: bool,
    pub copyright_email_author: bool,
    pub ecc: bool,
    pub keyword: bool,
    pub mime: bool,
    pub monk: bool,
    pub nomos: bool,
    pub ojo: bool,
    pub package: bool,
}

#[derive(Debug, Serialize, Default)]
pub struct Decider {
    pub nomos_monk: bool,
    /// Needs to be false for the other deciders to work:
    /// https://github.com/fossology/fossology/issues/1639
    bulk_reused: bool,
    pub new_scanner: bool,
    pub ojo_decider: bool,
}

#[derive(Debug, Serialize, Default)]
pub struct Reuse {
    pub reuse_upload: i32,
    pub reuse_group: String,
    pub reuse_main: bool,
    pub reuse_enhanced: bool,
    pub reuse_report: bool,
    pub reuse_copyright: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Job {
    pub id: i32,

    pub name: String,

    pub queue_date: String,

    pub upload_id: String,

    pub user_id: String,

    pub group_id: String,

    pub eta: i32,

    pub status: JobStatus,
}

#[derive(Debug, Deserialize, PartialEq, Eq)]
pub enum JobStatus {
    Completed,
    Failed,
    Queued,
    Processing,
}

#[cfg(test)]
mod test {
    use std::{thread, time::Duration};

    use crate::{auth::test::create_test_fossology_with_writetoken, upload::new_upload_from_file};

    use super::*;

    #[test]
    fn get_unarchive_job() {
        let fossology = create_test_fossology_with_writetoken("http://localhost:8080/repo/api/v1");

        let upload =
            new_upload_from_file(&fossology, 1, "tests/data/base-files_11.tar.xz").unwrap();

        let jobs = get_jobs(&fossology, Some(upload.upload_id), None, None, None).unwrap();

        assert_eq!(jobs.len(), 1);
        assert_eq!(jobs[0].status, JobStatus::Processing);
    }

    #[test]
    fn schedule_jobs() {
        let fossology = create_test_fossology_with_writetoken("http://localhost:8080/repo/api/v1");

        let upload =
            new_upload_from_file(&fossology, 1, "tests/data/base-files_11.tar.xz").unwrap();

        let jobs = get_jobs(&fossology, Some(upload.upload_id), None, None, None).unwrap();

        assert_eq!(jobs.len(), 1);

        while get_jobs(&fossology, Some(upload.upload_id), None, None, None).unwrap()[0].status
            == JobStatus::Processing
        {
            thread::sleep(Duration::from_secs(1));
        }

        let mut schedule = ScheduleAgents::default();
        schedule.analysis.nomos = true;
        schedule.analysis.ojo = true;
        schedule.analysis.copyright_email_author = true;
        schedule.analysis.ecc = true;
        schedule.analysis.keyword = true;

        let scheduled_job =
            schedule_analysis(&fossology, 1, upload.upload_id, None, &schedule).unwrap();

        let jobs = get_jobs(&fossology, Some(upload.upload_id), None, None, None).unwrap();

        assert_eq!(jobs.len(), 2);
        assert!(jobs.iter().any(|j| j.id == scheduled_job.id));
    }
}