emoji-gen 0.4.0

Emoji importing tool for the fediverse
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use error_stack::{report, Result};
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;

use imghdr;
use indicatif::ProgressIterator;
use reqwest;
use reqwest::Url;

use tempdir::TempDir;

use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use walkdir::DirEntry;
use walkdir::WalkDir;
use zip::write::FileOptions;

use env_logger;
use log::{debug, error, warn};

use chrono::Local;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Cli {
    /// Option
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Create a zip from a local folder
    Local {
        /// Output file path
        #[arg(short = 'o', long = "output", default_value_t = String::from("generated_emojis"))]
        outputFilepath: String,

        /// Folder with the custom emojis to generate the pack from.
        #[arg(short, long)]
        folder: String,

        /// Origin Host of the emoji
        #[arg(short = 'h', long = "host", default_value_t = String::from("https://git.joinfirefish.org/firefish/emoji-gen"))]
        originHost: String,

        /// Name for the pack
        #[arg(short, long, default_value_t = ("Custom").to_string())]
        group: String,
    },
    /// Create a zip from a remote instance content
    Crawl {
        /// Output file path
        #[arg(short = 'o', long = "output", default_value_t = String::from("generated_emojis"))]
        outputFilepath: String,

        /// Host to crawl emojis from
        #[arg(short, long)]
        host: String,
    },
}

#[derive(Serialize, Deserialize)]
struct Meta {
    metaVersion: i8,
    host: String,
    /**
    	* Date and time representation returned by ECMAScript `Date.prototype.toString`.
    	*/
    exportedAt: String,
    emojis: Vec<Emoji>,
}
#[derive(Serialize, Deserialize)]
struct EmojiResponse {
    shortcode: Option<String>,
    url: Option<String>,
    static_url: String,
    category: Option<String>,
}

#[derive(Serialize, Deserialize)]
struct Emoji {
    downloaded: bool,
    fileName: String,
    emoji: EmojiData,
}

#[derive(Serialize, Deserialize)]
struct EmojiData {
    name: String,
    category: String,
    aliases: Vec<String>,
}

fn getTypename(typeEnum: imghdr::Type) -> &'static str {
    return match typeEnum {
        imghdr::Type::Bgp => "bgp",
        imghdr::Type::Bmp => "bmp",
        imghdr::Type::Exr => "exr",
        imghdr::Type::Flif => "flif",
        imghdr::Type::Gif => "gif",
        imghdr::Type::Ico => "ico",
        imghdr::Type::Jpeg => "jpg",
        imghdr::Type::Pbm => "pbm",
        imghdr::Type::Pgm => "pgm",
        imghdr::Type::Png => "png",
        imghdr::Type::Ppm => "ppm",
        imghdr::Type::Rast => "rast",
        imghdr::Type::Rgb => "rgb",
        imghdr::Type::Rgbe => "rgbe",
        imghdr::Type::Tiff => "tiff",
        imghdr::Type::Webp => "webp",
        imghdr::Type::Xbm => "xbm",
    };
}

#[derive(Debug)]
enum EmojiGenError {
    ZipCreationFailed,
    EmojiFetchFailed,
    MetadataGenerationFailed,
    ImageFetchingFailed,
}

impl fmt::Display for EmojiGenError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str("Error processing emojis: Could not create the emoji zip bundle.")
    }
}

impl Error for EmojiGenError {}

fn main() {
    env_logger::init();

    let args = Cli::parse();

    match process(args.command) {
        Ok(()) => {}
        Err(err) => {
            error!("The process could not be completed. Quiting.");

            error!("\n{err:?}");
        }
    };
}

fn process(command: Command) -> Result<(), EmojiGenError> {
    let tmpDir: TempDir = TempDir::new("emoji-gen").unwrap();
    let tmpFolder: &Path = tmpDir.path();
    let zipFilepath: PathBuf;
    let emojis: Vec<Emoji>;
    let hostUrl: String;

    match command {
        Command::Local {
            outputFilepath,
            folder,
            originHost,
            group,
        } => {
            zipFilepath = prepare_zip_filepath(outputFilepath)?;

            emojis = get_local_emojis(Path::new(folder.as_str()), group, tmpFolder)?;

            hostUrl = originHost;
        }
        Command::Crawl {
            outputFilepath,
            host,
        } => {
            zipFilepath = prepare_zip_filepath(outputFilepath)?;

            emojis = get_host_emojis(
                &Url::parse(&host).map_err(|_| {
                    report!(EmojiGenError::EmojiFetchFailed)
                        .attach_printable(format!("Url '{}' is invalid.", host))
                })?,
                tmpFolder,
            )?;

            hostUrl = host;
        }
    }

    generate_meta(hostUrl, emojis, tmpFolder)?;

    zip(tmpFolder, &zipFilepath)?;
    drop(tmpFolder);

    println!(
        "✅ Done! Importable ZIP file under '{}'",
        zipFilepath.display()
    );

    Ok(())
}

fn prepare_zip_filepath(outputFilepath: String) -> Result<PathBuf, EmojiGenError> {
    let mut zipFilepath = PathBuf::from(outputFilepath.as_str());

    zipFilepath.set_extension("zip");

    if zipFilepath.exists() {
        return Err(
            report!(EmojiGenError::ZipCreationFailed).attach_printable(format!(
                "File '{}' exists. Please choose another name.",
                zipFilepath.display()
            )),
        );
    }

    Ok(zipFilepath)
}

fn get_host_emojis(host: &Url, tmpFolder: &Path) -> Result<Vec<Emoji>, EmojiGenError> {
    println!(
        "Getting all the fine emojis from Url '{}'...",
        host.as_str()
    );

    let hostUrl = &host.join("/api/v1/custom_emojis").unwrap();

    let emojis = match reqwest::blocking::get(hostUrl.clone()) {
        Ok(response) => match response.json::<Vec<EmojiResponse>>() {
            Ok(emojiRes) => {
                let emojos: Vec<EmojiResponse> = emojiRes;
                let iter = emojos.iter();
                Ok(iter
                    .progress_count(emojos.len() as u64)
                    .map(|res| {
                        get_host_emoji_data(
                            Url::parse(res.url.as_ref().unwrap().as_str().clone()).unwrap(),
                            res.shortcode.clone().unwrap_or_default(),
                            res.category.clone().unwrap_or_default(),
                            tmpFolder,
                        )
                    })
                    .filter_map(|r| r.ok())
                    .collect::<Vec<Emoji>>())
            }
            Err(_) => Err(
                report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
                    "Could not get emoji list from url '{}'.",
                    hostUrl.as_str()
                )),
            ),
        },
        Err(_) => Err(
            report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
                "Could not get response from url '{}'.",
                hostUrl.as_str()
            )),
        ),
    }?;

    Ok(emojis)
}

fn get_host_emoji_data(
    fileUrl: Url,
    name: String,
    category: String,
    tmpFolder: &Path,
) -> Result<Emoji, EmojiGenError> {
    debug!("{}", fileUrl.to_string());

    let newFilename = get_image_from_url(&fileUrl, tmpFolder, name.clone())?;

    let data: EmojiData = EmojiData {
        name: name,
        category: category.to_string(),
        aliases: Vec::<String>::new(),
    };

    Ok(Emoji {
        downloaded: true,
        fileName: newFilename,
        emoji: data,
    })
}

fn get_image_from_url(
    fileUrl: &Url,
    tmpFolder: &Path,
    filename: String,
) -> Result<String, EmojiGenError> {
    let img_bytes = &reqwest::blocking::get(fileUrl.clone())
        .map_err(|_| {
            report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
                "Could not get image file from url '{}'.",
                fileUrl.as_str()
            ))
        })?
        .bytes()
        .unwrap();

    let mut tmpFilepath: PathBuf = tmpFolder.join(filename);

    match imghdr::from_bytes(img_bytes) {
        Some(extension) => tmpFilepath.set_extension(getTypename(extension)),
        None => tmpFilepath.set_extension("xxx"),
    };

    println!("Creating image file at path '{}'...", tmpFilepath.display());

    let mut imageFile = File::create(tmpFilepath.as_os_str()).map_err(|_| {
        report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
            "Could not create image file at temporary path '{}'.",
            tmpFilepath.display()
        ))
    })?;
    imageFile.write_all(img_bytes).map_err(|_| {
        report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
            "Could not write image at temporary path '{}'.",
            tmpFilepath.display()
        ))
    })?;

    Ok(String::from(
        tmpFilepath.file_name().unwrap().to_str().unwrap(),
    ))
}

fn get_local_emojis(
    folder: &Path,
    group: String,
    tmpFolder: &Path,
) -> Result<Vec<Emoji>, EmojiGenError> {
    match folder.canonicalize() {
        Ok(f) => {
            if !f.is_dir() {
                Err(
                    report!(EmojiGenError::EmojiFetchFailed).attach_printable(format!(
                        "Folder path '{}' is not a directory.",
                        folder.display()
                    )),
                )
            } else {
                Ok(f)
            }
        }
        Err(_) => Err(report!(EmojiGenError::EmojiFetchFailed)
            .attach_printable(format!("Folder '{}' does not exist.", folder.display()))),
    }?;

    println!(
        "Getting all the fine emojis from folder '{}'...",
        folder.display()
    );

    let mut emojis = Vec::<Emoji>::new();

    let iter = WalkDir::new(folder).into_iter();
    let count = WalkDir::new(folder).into_iter().count() as u64;

    for result in iter.progress_count(count) {
        if let Err(_) = result {
            continue;
        }
        let opt_file = result.ok();
        if opt_file.is_none() {
            continue;
        }
        let file = opt_file.unwrap();
        if !file.metadata().unwrap().is_file() {
            continue;
        }

        let filename = file.path().file_name().unwrap();

        println!("Checking file '{}'...", filename.to_string_lossy());

        let image = imghdr::from_file(file.path()).map_err(|_| {
            report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
                "Could not get image at path '{}'.",
                file.path().display()
            ))
        })?;

        if image.is_none() {
            if filename.to_ascii_uppercase() == "LICENSE"
                || filename.to_ascii_uppercase() == "LICENSE.md"
            {
                get_image_from_path(&file.path(), tmpFolder)
                    .map_err(|err| warn!("{}", err))
                    .unwrap();
            }

            continue;
        }

        match get_local_emoji_data(file, group.clone().into(), tmpFolder) {
            Ok(emoji) => {
                emojis.push(emoji);
            }
            Err(err) => {
                // Passing because this is not fatal
                warn!("{}", err)
            }
        }
    }

    Ok(emojis)
}

fn get_local_emoji_data(
    file: DirEntry,
    original_category: Rc<String>,
    tmpFolder: &Path,
) -> Result<Emoji, EmojiGenError> {
    debug!("{}", file.path().display());

    let fileName = String::from(file.file_name().to_str().unwrap());
    let name = String::from(file.path().file_stem().unwrap().to_str().unwrap())
        .replace(&[' ', '-'][..], "_");

    get_image_from_path(&file.path(), tmpFolder)?;

    let data = EmojiData {
        name: name,
        category: original_category.to_string(),
        aliases: Vec::<String>::new(),
    };

    Ok(Emoji {
        downloaded: true,
        fileName,
        emoji: data,
    })
}

fn get_image_from_path(filePath: &Path, tmpFolder: &Path) -> Result<(), EmojiGenError> {
    let filename = filePath.file_name().unwrap();
    let img_data = std::fs::read(filePath.as_os_str()).map_err(|_| {
        report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
            "Could not read image file at path '{}'.",
            filePath.display()
        ))
    })?;

    let img_bytes = img_data.as_slice();

    let imageFilePath = &tmpFolder.join(filename);
    let mut imageFile = File::create(imageFilePath).map_err(|_| {
        report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
            "Could not create image to temporary path '{}'.",
            imageFilePath.display()
        ))
    })?;

    imageFile.write_all(&img_bytes).map_err(|_| {
        report!(EmojiGenError::ImageFetchingFailed).attach_printable(format!(
            "Could not write image to temporary path '{}'.",
            imageFilePath.display()
        ))
    })?;

    Ok(())
}

fn generate_meta(host: String, emojis: Vec<Emoji>, tmpFolder: &Path) -> Result<(), EmojiGenError> {
    let meta = Meta {
        metaVersion: 1,
        host: host,
        exportedAt: Local::now().to_rfc3339(),
        emojis: emojis,
    };

    let json = serde_json::to_string(&meta).map_err(|_| {
        report!(EmojiGenError::MetadataGenerationFailed)
            .attach_printable(format!("Could not generate metadata for 'meta.json'."))
    })?;

    let metaFilepath: &PathBuf = &tmpFolder.join("meta.json");

    println!(
        "Creating file 'meta.json' at path '{}'...",
        metaFilepath.to_str().unwrap()
    );

    let mut file = File::create(metaFilepath).map_err(|_| {
        report!(EmojiGenError::MetadataGenerationFailed).attach_printable(format!(
            "Could not create file '{}'.",
            metaFilepath.display()
        ))
    })?;

    write!(file, "{}", json).map_err(|_| {
        report!(EmojiGenError::MetadataGenerationFailed).attach_printable(format!(
            "Could not write metadata to file '{}'.",
            metaFilepath.display()
        ))
    })?;

    Ok(())
}

fn zip(src_dir: &Path, dst_file: &Path) -> Result<(), EmojiGenError> {
    if !std::path::Path::new(src_dir).is_dir() {
        return Err(report!(EmojiGenError::ZipCreationFailed)
            .attach_printable(format!("Could not find folder '{}'.", src_dir.display())));
    }

    println!("Creating zip file at path '{}'...", dst_file.display());

    let zipFile = &File::create(dst_file).map_err(|_| {
        report!(EmojiGenError::ZipCreationFailed)
            .attach_printable(format!("Could not create file '{}'.", dst_file.display()))
    })?;
    let mut zip = zip::ZipWriter::new(zipFile);
    let options = FileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated)
        .unix_permissions(0o755);

    let iter = WalkDir::new(src_dir).into_iter();
    let count = WalkDir::new(src_dir).into_iter().count() as u64;

    let mut buffer = Vec::new();
    for entryRes in iter.progress_count(count) {
        let entry = entryRes.map_err(|_| {
            report!(EmojiGenError::ZipCreationFailed).attach_printable(format!(
                "Could get path to a file in folder '{}'.",
                src_dir.display()
            ))
        })?;
        let path = entry.path();
        let name = path.strip_prefix(src_dir).map_err(|_| {
            report!(EmojiGenError::ZipCreationFailed).attach_printable(format!(
                "Could not strip prefix on file path '{}'.",
                path.display()
            ))
        })?;
        // Write file or directory explicitly
        // Some unzip tools unzip files with directory paths correctly, some do not!
        if path.is_file() {
            debug!("adding file {:?} as {:?} ...", path, name);
            #[allow(deprecated)]
            zip.start_file_from_path(name, options).map_err(|_| {
                report!(EmojiGenError::ZipCreationFailed).attach_printable(format!(
                    "Could not create file '{}' in zip file '{:?}'.",
                    path.display(),
                    zipFile
                ))
            })?;
            let mut f = File::open(path).map_err(|_| {
                report!(EmojiGenError::ZipCreationFailed)
                    .attach_printable(format!("Could not read file '{}'.", path.display()))
            })?;

            f.read_to_end(&mut buffer).map_err(|_| {
                report!(EmojiGenError::ZipCreationFailed)
                    .attach_printable(format!("Could not read file '{}'.", path.display()))
            })?;
            zip.write_all(&*buffer).map_err(|_| {
                report!(EmojiGenError::ZipCreationFailed)
                    .attach_printable(format!("Could not write data to zip file '{:?}'.", zipFile))
            })?;
            buffer.clear();
        } else if !name.as_os_str().is_empty() {
            // Only if not root! Avoids path spec / warning
            // and mapname conversion failed error on unzip
            debug!("adding dir {:?} as {:?} ...", path, name);
            #[allow(deprecated)]
            zip.add_directory_from_path(name, options).map_err(|_| {
                report!(EmojiGenError::ZipCreationFailed).attach_printable(format!(
                    "Could not create folder '{}' in zip file '{:?}'.",
                    path.display(),
                    zipFile
                ))
            })?;
        }
    }
    zip.finish().map_err(|_| {
        report!(EmojiGenError::ZipCreationFailed)
            .attach_printable(format!("Could not close zip file '{:?}'.", zipFile))
    })?;
    Ok(())
}