main.rs 8.71 KB
Newer Older
1
extern crate chrono;
Emmanuel Raviart's avatar
Emmanuel Raviart committed
2
3
4
5
6
7
8
9
extern crate clap;
extern crate rayon;
extern crate serde_json;
extern crate tricoteuses_api_assemblee_config as config;
extern crate tricoteuses_api_assemblee_data as data;

use clap::{App, Arg};
use config::Verbosity;
10
use data::{Acteur, CodeTypeOrgane, EnabledDatasets, Mandat, PhotoDepute, NO_DATASET};
Emmanuel Raviart's avatar
Emmanuel Raviart committed
11
12
13
use rayon::prelude::*;
use std::collections::HashMap;
use std::fs::{self, File};
14
use std::mem;
Emmanuel Raviart's avatar
Emmanuel Raviart committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use std::path::Path;
use std::process::Command;

fn main() {
    let matches = App::new("Tricoteuses API Assemblée")
        .version("1.0")
        .author("Emmanuel Raviart <emmanuel@raviart.com>")
        .about("GraphQL API to access open data of French Assemblée nationale")
        .arg(
            Arg::with_name("config")
                .short("c")
                .long("config")
                .value_name("FILE")
                .help("Sets a custom config file")
                .takes_value(true),
Emmanuel Raviart's avatar
Emmanuel Raviart committed
30
31
        )
        .arg(
Emmanuel Raviart's avatar
Emmanuel Raviart committed
32
33
34
35
            Arg::with_name("no_download")
                .short("D")
                .long("no-download")
                .help("Reuse existing photos (don't download them)"),
Emmanuel Raviart's avatar
Emmanuel Raviart committed
36
37
        )
        .arg(
Emmanuel Raviart's avatar
Emmanuel Raviart committed
38
39
40
41
            Arg::with_name("v")
                .short("v")
                .multiple(true)
                .help("Sets the level of verbosity"),
Emmanuel Raviart's avatar
Emmanuel Raviart committed
42
43
        )
        .get_matches();
Emmanuel Raviart's avatar
Emmanuel Raviart committed
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

    let config_file_path = Path::new(matches.value_of("config").unwrap_or("../Config.toml"));
    let config = config::load(config_file_path);

    let verbosity = match matches.occurrences_of("v") {
        0 => Verbosity::Verbosity0,
        1 => Verbosity::Verbosity1,
        2 | _ => Verbosity::Verbosity2,
    };

    let config_dir = config_file_path.parent().unwrap();

    let context = data::load(
        &config,
        &config_dir,
        &EnabledDatasets {
            acteurs_et_organes: true,
            ..NO_DATASET
        },
        &verbosity,
    );

    let data_dir = config_dir.join(config.data.dir);
    let legislature = "15";
    let photos_dir = data_dir.join(format!("photos_deputes_{}", legislature));

    let mut deputes = Vec::<&Acteur>::new();
Emmanuel Raviart's avatar
Emmanuel Raviart committed
71
72
    for acteur in context
        .acteur_by_uid
73
74
75
        .values()
        .map(|acteur| unsafe { mem::transmute::<*const Acteur, &Acteur>(*acteur) })
    {
Emmanuel Raviart's avatar
Emmanuel Raviart committed
76
        for mandat in acteur.mandats(Some(&chrono::Local::today().format("%Y-%m-%d").to_string())) {
77
78
79
80
81
82
83
            if let Mandat::MandatParlementaire(mandat_parlementaire) = mandat {
                if let Some(legislature_mandat) = &mandat_parlementaire.legislature {
                    if legislature_mandat == legislature
                        && mandat_parlementaire.type_organe == CodeTypeOrgane::Assemblee
                    {
                        deputes.push(acteur);
                        break; // Don't push the same deputé several times.
Emmanuel Raviart's avatar
Emmanuel Raviart committed
84
85
86
87
88
                    }
                }
            }
        }
    }
89
    deputes.sort_unstable_by(|depute1, depute2| depute1.uid.text.cmp(&depute2.uid.text));
Emmanuel Raviart's avatar
Emmanuel Raviart committed
90
91
92
93
94
95

    // Download photos.
    if !photos_dir.exists() {
        fs::create_dir(&photos_dir).expect("Creation of photos directory failed");
    }
    if !matches.is_present("no_download") {
96
        let missing_photo_file_path = Path::new("images/transparent_150x192.jpg");
Emmanuel Raviart's avatar
Emmanuel Raviart committed
97
98
        deputes.par_iter().for_each(|depute| {
            let ident = &depute.etat_civil.ident;
99
            let photo_filename = format!("{}.jpg", depute.uid().get(2..).unwrap());
100
101
102
            let photo_file_path = photos_dir.join(&photo_filename);
            let photo_temp_filename = format!("{}_temp.jpg", depute.uid().get(2..).unwrap());
            let photo_temp_file_path = photos_dir.join(&photo_temp_filename);
Emmanuel Raviart's avatar
Emmanuel Raviart committed
103
            let url_photo = format!(
104
                "http://www2.assemblee-nationale.fr/static/tribun/{}/photos/{}",
Emmanuel Raviart's avatar
Emmanuel Raviart committed
105
                legislature, photo_filename
Emmanuel Raviart's avatar
Emmanuel Raviart committed
106
107
108
109
110
111
112
            );
            if verbosity != Verbosity::Verbosity0 {
                println!(
                    "Loading photo {} for {} {}...",
                    url_photo, ident.prenom, ident.nom
                );
            }
113
114
115
116
117
            for retries in 0..3 {
                let output = Command::new("wget")
                    .current_dir(&photos_dir)
                    .arg("-q")
                    .arg("-O")
118
                    .arg(&photo_temp_filename)
119
120
121
122
                    .arg(&url_photo)
                    .output()
                    .expect("Wget failed");
                if output.status.success() {
Emmanuel Raviart's avatar
Emmanuel Raviart committed
123
124
                    fs::rename(&photo_temp_file_path, &photo_file_path)
                        .expect("Renaming of image failed");
125
126
127
128
129
                    return;
                }
                if retries >= 2 {
                    println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
                    println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
Emmanuel Raviart's avatar
Emmanuel Raviart committed
130
                    println!(
131
                        "Wget of {} ({} {}) failed",
Emmanuel Raviart's avatar
Emmanuel Raviart committed
132
133
                        url_photo, ident.prenom, ident.nom
                    );
134
135
136
137
                    if photo_file_path.exists() {
                        println!("  => Reusing existing image");
                    } else {
                        println!("  => Using blank image");
Emmanuel Raviart's avatar
Emmanuel Raviart committed
138
139
                        fs::copy(&missing_photo_file_path, &photo_file_path)
                            .expect("Copy of blank image failed");
140
141
142
143
                    }
                }
                if photo_temp_file_path.exists() {
                    fs::remove_file(&photo_temp_file_path).expect("Temporary image removal failed");
144
                }
Emmanuel Raviart's avatar
Emmanuel Raviart committed
145
146
147
148
149
150
151
            }
        });
    }

    // Resize photos to 150x192, because some haven't exactly this size.
    deputes.par_iter().for_each(|depute| {
        let numero_depute = depute.uid().get(2..).unwrap();
152
        let output = Command::new("gm")
Emmanuel Raviart's avatar
Emmanuel Raviart committed
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
            .current_dir(&photos_dir)
            .arg("convert")
            .arg("-resize")
            .arg("150x192!")
            .arg(format!("{}.jpg", numero_depute))
            .arg(format!("{}_150x192.jpg", numero_depute))
            .output()
            .expect("Gm photo resizing failed");
        if !output.status.success() {
            println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
            panic!("Gm photo resizing failed");
        }
    });

    // Create a mosaic of photos.
    let mut photo_by_id_depute = HashMap::<String, PhotoDepute>::new();
    let mut rows_filenames: Vec<String> = Vec::new();
    for (row_index, row) in deputes.chunks(25).enumerate() {
        let mut photos_filenames = Vec::<String>::new();
        for (column_index, depute) in row.iter().enumerate() {
            let uid = depute.uid();
            let numero_depute = uid.get(2..).unwrap();
            let photo_filename = format!("{}_150x192.jpg", numero_depute);
            photos_filenames.push(photo_filename.to_string());
            photo_by_id_depute.insert(
                uid.to_string(),
                PhotoDepute {
                    chemin: format!("photos_deputes_{}/{}", legislature, photo_filename),
                    chemin_mosaique: format!("photos_deputes_{}/deputes.jpg", legislature),
                    hauteur: 192,
                    largeur: 150,
Emmanuel Raviart's avatar
Emmanuel Raviart committed
185
186
                    x_mosaique: column_index as i32 * 150,
                    y_mosaique: row_index as i32 * 192,
Emmanuel Raviart's avatar
Emmanuel Raviart committed
187
188
189
190
                },
            );
        }
        let row_filename = format!("row-{}.jpg", row_index);
191
        let output = Command::new("gm")
Emmanuel Raviart's avatar
Emmanuel Raviart committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
            .current_dir(&photos_dir)
            .arg("convert")
            .args(&photos_filenames)
            .arg("+append")
            .arg(&row_filename)
            .output()
            .expect("Gm row creation failed");
        if !output.status.success() {
            println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
            panic!("Gm row creation failed");
        }
        rows_filenames.push(row_filename);
    }
206
    let output = Command::new("gm")
Emmanuel Raviart's avatar
Emmanuel Raviart committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
        .current_dir(&photos_dir)
        .arg("convert")
        .args(&rows_filenames)
        .arg("-append")
        .arg("deputes.jpg")
        .output()
        .expect("Gm mosaic creation failed");
    if !output.status.success() {
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        panic!("Gm mosaic creation failed");
    }
    for row_filename in rows_filenames {
        fs::remove_file(photos_dir.join(&row_filename)).expect("Row image removal failed");
    }

    let json_file_path = photos_dir.join("deputes.json");
    let json_file = File::create(&json_file_path).unwrap();
    serde_json::to_writer_pretty(json_file, &photo_by_id_depute).unwrap();
}