paperpaw-plugin-store 1.0.6

PaperPaw plugin store: finds data plugins for this device in a plugin library and installs, updates and removes them
Documentation
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
//! The first-run setup's offer with the real kernel on an X4 that loads
//! code plugins: the plugins chosen are fetched one after another from
//! the plugin library and installed, said once at the end; one that
//! cannot come is named, and the store has it later.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "tests panic on purpose when something is wrong"
)]

mod common;

use common::{LIST, Shopping};
use paperpaw_native::signature::{public_key, sign};
use paperpaw_native::{Chip, Header, LINK_BASE};
use paperpaw_sdk::builtin::actions;
use paperpaw_sdk::native::{Fingerprint, Native, installed_code};
use paperpaw_sdk::{Id, Instant, Params, PluginKind, Storage};

/// The build of this PaperPaw.
const BUILD: Fingerprint = Fingerprint::of(paperpaw_sdk::native::INTERFACE, 0x4567_89ab_cdef);
/// The seed of PaperPaw's key for its own plugins.
const PAPERPAW: [u8; 32] = [5; 32];

fn native() -> Native {
    let mut native = Native::new("code.ppn");
    native.fingerprint = BUILD;
    native
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// A plugin file built for [`BUILD`], signed by PaperPaw.
fn ppn() -> Vec<u8> {
    let image = [0u8; 128];
    let mut header = Header {
        chip: Chip::Esp32C3,
        fingerprint: BUILD.0,
        base: LINK_BASE,
        image_len: image.len() as u32,
        code_at: 96,
        entry: 0,
        api: 32,
        relocs: 0,
        align: 16,
        compiler: 1,
        hot_at: 0,
        hot_len: 0,
        patches: 0,
        needs_api: 0,
        families: [0; 8],
        interface: paperpaw_sdk::native::INTERFACE,
        sha256: [0; 32],
    };
    let mut sha = header.digest();
    sha.update(&image);
    header.sha256 = sha.finish();
    let mut file = header.to_bytes().to_vec();
    file.extend_from_slice(&image);
    file.extend_from_slice(&sign(&file, &PAPERPAW).to_bytes());
    file
}

fn manifest(id: &str) -> String {
    format!("[plugin]\nid = {id}\nname = {id}\nversion = 0.4.0\n")
}

/// Plugin `id`'s page at the library.
fn page(id: &str, code: &[u8]) -> String {
    let ini = manifest(id);
    format!(
        r#"{{"format": 2, "plugin": {{"id": "{id}", "name": "{id}",
  "summary": "PaperPaw's own.", "group": "reading",
  "author": "PaperPaw", "licence": "Apache-2.0", "kind": "code", "author_key": "{}",
  "latest": {{"version": "0.4.0", "sdk": "0.4", "formats": 1, "size": {},
    "files": [{{"path": "plugin.ini", "url": "{id}/0.4.0/plugin.ini",
                "size": {}, "sha1": "{}"}}],
    "builds": [{{"device": "x4", "abi": "{BUILD}", "url": "{id}/0.4.0/x4.ppn",
                 "size": {}, "sha256": "{}"}}]}}}}}}"#,
        hex(&public_key(&PAPERPAW)),
        ini.len(),
        ini.len(),
        paperpaw_digest::sha1::hex(ini.as_bytes()),
        code.len(),
        paperpaw_digest::sha256::hex(code),
    )
}

fn page_url(id: &str) -> String {
    format!("https://paperpaw.org/api/v1/plugins/{id}.json?device=x4&lang=en&abi={BUILD}")
}

/// The offer opened as the setup opens it, on an X4 loading code plugins.
fn offer() -> Shopping {
    let mut shopping = Shopping::on(
        Some("x4"),
        Some(native()),
        r#"{"format": 2, "plugins": []}"#,
    );
    shopping.now += 100;
    shopping.kernel.open_screen(
        Instant(shopping.now),
        Id::new_static("store.offer"),
        Params::new(),
    );
    shopping
}

/// The offer on an X4 whose shell kept the room as `room` says.
fn offer_with_room(room: &str) -> Shopping {
    let storage = common::Shared::default();
    storage
        .write(".paperpaw/code-room.txt", room.as_bytes())
        .unwrap();
    let mut shopping = Shopping::with(
        Some("x4"),
        Some(native()),
        r#"{"format": 2, "plugins": []}"#,
        storage,
    );
    shopping.now += 100;
    shopping.kernel.open_screen(
        Instant(shopping.now),
        Id::new_static("store.offer"),
        Params::new(),
    );
    shopping
}

/// After an SD install from CrossPoint (the stock layout: the shell says a
/// full flash gives more) the setup's offer says what room there is for
/// code plugins and that a full install via USB gives more; on PaperPaw's
/// own layout, or where the shell says nothing of it, not a word.
#[test]
fn the_offer_says_a_full_install_gives_more_room_only_on_the_stock_layout() {
    // 1,126,400 B of room (1.1 MB), 3,000,000 B (2.9 MB) with a full flash.
    for (room, said) in [
        ("1126400 0 4096 83 0 0 3000000\n", true),
        ("1126400 0 4096 83 0 0 0\n", false),
        ("1126400 0 4096 83 0 0\n", false),
    ] {
        let mut shopping = offer_with_room(room);
        let shown = shopping.shown();
        assert!(shown.contains("Reading statistics"), "{shown}");
        assert_eq!(
            shown.contains("paperpaw.org/flash"),
            said,
            "{room}: {shown}"
        );
        if said {
            assert!(shown.contains("Room for plugins: 1.1 MB"), "{shown}");
            assert!(shown.contains("about 2.9 MB"), "{shown}");
        } else {
            assert!(!shown.contains("Room for plugins"), "{room}: {shown}");
        }
    }
    // And not on a device with no room for code of its own to speak of.
    let shown = offer().shown();
    assert!(!shown.contains("paperpaw.org/flash"), "{shown}");
}

/// Plugin `id`'s page and files answered.
fn serve(shopping: &mut Shopping, id: &str, code: &[u8]) {
    shopping.serve(&page_url(id), page(id, code).as_bytes());
    let files = "https://paperpaw.org/api/v1/plugins";
    shopping.serve(
        &format!("{files}/{id}/0.4.0/plugin.ini"),
        manifest(id).as_bytes(),
    );
    shopping.serve(&format!("{files}/{id}/0.4.0/x4.ppn"), code);
}

#[test]
fn the_plugins_chosen_are_installed_and_said_once() {
    let mut shopping = offer();
    let shown = shopping.shown();
    for name in [
        "Reading statistics",
        "Home widgets",
        "Wireless library",
        "Progress sync",
    ] {
        assert!(shown.contains(name), "{shown}");
    }
    // *Done* there with nothing chosen too.
    assert!(shown.contains("| Done"), "{shown}");
    shopping.choose("Reading statistics");
    shopping.choose("Wireless library");
    // Past the reading sync to *Done*.
    shopping.run(actions::DOWN);
    shopping.run(actions::DOWN);
    let shown = shopping.shown();
    assert!(shown.contains("Done"), "{shown}");
    shopping.run(actions::CONFIRM);
    let code = ppn();
    serve(&mut shopping, "stats", &code);
    // No word of each on its own: the next one comes.
    assert!(
        !shopping.shown().contains("Installed"),
        "{}",
        shopping.shown()
    );
    serve(&mut shopping, "calibre", &code);
    for id in ["stats", "calibre"] {
        let plugin = shopping.kernel.plugins().get(id).unwrap();
        assert_eq!(plugin.kind, PluginKind::Code);
        assert!(shopping.storage.exists(&format!("plugins/{id}/code.ppn")));
        assert!(installed_code(&shopping.storage, id).is_some());
    }
    // The notice, as its lines show.
    let shown = shopping.shown().replace(" | ", " ");
    assert!(
        shown.contains("Added: stats, calibre. They start the next time PaperPaw starts."),
        "{shown}"
    );
    assert!(
        !shopping
            .storage
            .exists(".paperpaw/plugins/store/queue-quiet.txt")
    );
}

/// The requests asked for since, by address.
fn asked(shopping: &mut Shopping) -> Vec<String> {
    shopping
        .requests()
        .into_iter()
        .map(|call| call.url)
        .collect()
}

/// Leaving the page with plugins chosen adds them as *Done* does: the
/// switches are the choice. With none chosen, nothing.
#[test]
fn back_adds_those_chosen_and_nothing_else() {
    let mut shopping = offer();
    shopping.choose("Reading statistics");
    shopping.run(actions::BACK);
    assert_ne!(
        shopping.kernel.active_screen().map(Id::as_str),
        Some("store.offer")
    );
    assert_eq!(asked(&mut shopping), [page_url("stats")]);
    assert!(
        shopping
            .storage
            .exists(".paperpaw/plugins/store/offer-chosen.txt")
    );
    let shown = shopping.shown().replace(" | ", " ");
    assert!(shown.contains("added in the background"), "{shown}");
    // Nothing chosen: left as it was.
    let mut shopping = offer();
    shopping.run(actions::BACK);
    assert!(asked(&mut shopping).is_empty());
    assert!(
        !shopping
            .storage
            .exists(".paperpaw/plugins/store/offer-chosen.txt")
    );
    assert!(!shopping.storage.exists(".paperpaw/plugins/store/queue.txt"));
}

/// By touch: the header's arrow back is *Back*, a plugin chosen by a tap
/// added once (not again by the *Back* that *Done* sends).
#[test]
fn the_headers_arrow_adds_those_chosen_too() {
    let mut shopping = Shopping::touch_with(Some(native()), r#"{"format": 2, "plugins": []}"#);
    shopping.now += 100;
    shopping.kernel.open_screen(
        Instant(shopping.now),
        Id::new_static("store.offer"),
        Params::new(),
    );
    let _ = shopping.shown();
    let row = shopping
        .kernel
        .describe()
        .into_iter()
        .find(|p| p.label.starts_with("Wireless"))
        .unwrap()
        .area;
    shopping.touch_at(i32::from(row.x) + 40, i32::from(row.y) + 20, false);
    // The arrow at the header's start.
    shopping.touch_at(30, 30, false);
    assert_ne!(
        shopping.kernel.active_screen().map(Id::as_str),
        Some("store.offer")
    );
    let page = page_url("calibre").replace("device=x4&", "device=x4-pro&");
    assert_eq!(asked(&mut shopping), [page]);
    let queue = String::from_utf8(
        paperpaw_sdk::read_file(&shopping.storage, ".paperpaw/plugins/store/queue.txt", 4096)
            .unwrap(),
    )
    .unwrap();
    assert_eq!(queue, "> ~calibre\n");
}

/// *Done* with nothing chosen goes back to the setup, adding nothing.
#[test]
fn done_with_nothing_chosen_adds_nothing() {
    let mut shopping = offer();
    for _ in 0..4 {
        shopping.run(actions::DOWN);
    }
    shopping.run(actions::CONFIRM);
    assert_ne!(
        shopping.kernel.active_screen().map(Id::as_str),
        Some("store.offer")
    );
    assert!(asked(&mut shopping).is_empty());
    assert!(
        !shopping
            .storage
            .exists(".paperpaw/plugins/store/offer-chosen.txt")
    );
}

#[test]
fn one_that_cannot_come_is_named() {
    let mut shopping = offer();
    shopping.choose("Home widgets");
    shopping.run(actions::DOWN);
    shopping.run(actions::DOWN);
    shopping.run(actions::DOWN);
    shopping.run(actions::DOWN);
    shopping.run(actions::CONFIRM);
    let call = shopping.request(&page_url("widgets"));
    shopping.answer(&call, 404, b"not found");
    let shown = shopping.shown().replace(" | ", " ");
    assert!(
        shown.contains("Could not be added: Home widgets. They are in the Plugin store."),
        "{shown}"
    );
    assert!(shopping.kernel.plugins().get("widgets").is_none());
}

#[test]
fn the_list_and_the_store_are_left_as_they_were() {
    // The list asked when the store opened is not asked again.
    let mut shopping = offer();
    assert!(shopping.requests().iter().all(|c| c.url != LIST));
}

/// The statistics built in, as on Android (by its id).
struct BuiltInStats;

impl paperpaw_sdk::Plugin for BuiltInStats {
    fn manifest(&self) -> paperpaw_sdk::Manifest {
        paperpaw_sdk::Manifest::new(
            Id::new_static("stats"),
            "Reading statistics",
            paperpaw_sdk::Version::new(0, 4, 0),
        )
        .description("Reading statistics.")
        .uses(paperpaw_sdk::Uses::NOTHING)
    }

    fn register(&self, _: &mut paperpaw_sdk::Registrar) -> Result<(), paperpaw_sdk::RegisterError> {
        Ok(())
    }
}

#[test]
fn built_in_ones_are_switched_on() {
    let mut kernel = paperpaw_core::Kernel::builder(common::DEVICE)
        .storage(paperpaw_sdk::MemoryStorage::new())
        .plugin(paperpaw_plugin_fonts_default::DefaultFontPacks)
        .plugin(paperpaw_plugin_menu::Menu)
        .plugin(paperpaw_plugin_store::Store)
        .plugin_off(BuiltInStats)
        .build()
        .unwrap();
    kernel.start(Instant(0));
    kernel.open_screen(Instant(100), Id::new_static("store.offer"), Params::new());
    kernel.render(&mut |_, _| {});
    let shown: Vec<String> = kernel.describe().into_iter().map(|p| p.label).collect();
    // Only what can be added here: no code plugins without a network.
    assert!(
        shown.iter().any(|l| l.starts_with("Reading statistics")),
        "{shown:?}"
    );
    assert!(
        !shown.iter().any(|l| l.starts_with("Wireless")),
        "{shown:?}"
    );
    // Chosen, then *Done*.
    kernel.run_action(Instant(200), actions::CONFIRM);
    kernel.run_action(Instant(300), actions::DOWN);
    kernel.run_action(Instant(400), actions::CONFIRM);
    let stats = kernel.plugins().get("stats").unwrap();
    assert!(stats.enabled, "{stats:?}");
    assert!(
        kernel
            .take_io()
            .iter()
            .all(|io| !matches!(io, paperpaw_core::Io::Http(_)))
    );
}

/// The kernel restarted on `storage`, as on an X4 loading code plugins:
/// the store not opened.
fn restarted(storage: common::Shared) -> paperpaw_core::Kernel {
    let mut kernel = paperpaw_core::Kernel::builder(common::DEVICE)
        .storage(storage)
        .network(true)
        .catalog_device("x4")
        .code_plugins(native(), Box::new(common::NoCode))
        .plugin(paperpaw_plugin_fonts_default::DefaultFontPacks)
        .plugin(paperpaw_plugin_menu::Menu)
        .plugin(paperpaw_plugin_store::Store)
        .build()
        .unwrap();
    kernel.start(Instant(0));
    kernel
}

#[test]
fn the_setups_plugins_go_on_after_a_restart_unasked_ones_do_not() {
    let mut shopping = offer();
    shopping.choose("Reading statistics");
    for _ in 0..4 {
        shopping.run(actions::DOWN);
    }
    shopping.run(actions::CONFIRM);
    // Its page asked for, then a restart before anything came.
    shopping.request(&page_url("stats"));
    let storage = shopping.storage.clone();
    let queue = String::from_utf8(
        paperpaw_sdk::read_file(&storage, ".paperpaw/plugins/store/queue.txt", 4096).unwrap(),
    )
    .unwrap();
    // Marked quiet one by one: an *Update all* put in later is not.
    assert_eq!(queue, "> ~stats\n");
    let mut kernel = restarted(storage.clone());
    let asked: Vec<String> = kernel
        .take_io()
        .into_iter()
        .filter_map(|io| match io {
            paperpaw_core::Io::Http(call) => Some(call.url),
            _ => None,
        })
        .collect();
    assert_eq!(asked, [page_url("stats")], "the store not opened");
    // An update put in the queue the usual way waits for the store.
    storage
        .write(".paperpaw/plugins/store/queue.txt", b"> weather\n")
        .unwrap();
    let mut kernel = restarted(storage);
    assert!(
        kernel
            .take_io()
            .iter()
            .all(|io| !matches!(io, paperpaw_core::Io::Http(_)))
    );
}