7 Commits

23 changed files with 2413 additions and 356 deletions
+4 -2
View File
@@ -1,6 +1,6 @@
# Liber Domi — core (public) # Liber Domi — core (public)
Liber (Latin: book) is the Domi home for books. This repository is the **public, MPL-2.0 core** Liber (Latin: book) is the Domi home for books. This repository is the **public, CPAL-1.0 core**
(`https://gitea.marek-novak.cz/mnovak/Liber-public`; the roadmap calls it `LiberPublic`): pure Rust, no network, (`https://gitea.marek-novak.cz/mnovak/Liber-public`; the roadmap calls it `LiberPublic`): pure Rust, no network,
no UI, no clock. The app lives in the private `Liber` repo (`https://gitea.marek-novak.cz/mnovak/Liber`) and depends no UI, no clock. The app lives in the private `Liber` repo (`https://gitea.marek-novak.cz/mnovak/Liber`) and depends
on this one **by git tag**, never by a path. The roadmap and the day pages are in the app repo (`docs/01_books.md`). on this one **by git tag**, never by a path. The roadmap and the day pages are in the app repo (`docs/01_books.md`).
@@ -10,7 +10,9 @@ on this one **by git tag**, never by a path. The roadmap and the day pages are i
crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and
writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote) writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote)
crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge
(sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format (sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format;
Day 5 `together`: what another person's Liber sends (strictly parsed), where a shared note
lands in one's own copy (exact / approximate / lost), the spoiler guard, recording approval
crates/liber-habit Day 2: the local day (the only day computation in Liber), days read, the forgiving streak, crates/liber-habit Day 2: the local day (the only day computation in Liber), days read, the forgiving streak,
the reminder schedule, the medal rules (a pure function of the log) the reminder schedule, the medal rules (a pure function of the log)
crates/liber-lang Day 3: words by UAX #29 with UTF-16 offsets, the Lemmatizer trait (a licensed table first, crates/liber-lang Day 3: words by UAX #29 with UTF-16 offsets, the Lemmatizer trait (a licensed table first,
Generated
+5 -5
View File
@@ -327,7 +327,7 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]] [[package]]
name = "liber-audio" name = "liber-audio"
version = "0.4.3" version = "0.6.1"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
@@ -337,7 +337,7 @@ dependencies = [
[[package]] [[package]]
name = "liber-format" name = "liber-format"
version = "0.4.3" version = "0.6.1"
dependencies = [ dependencies = [
"base64", "base64",
"chardetng", "chardetng",
@@ -357,7 +357,7 @@ dependencies = [
[[package]] [[package]]
name = "liber-habit" name = "liber-habit"
version = "0.4.3" version = "0.6.1"
dependencies = [ dependencies = [
"liber-library", "liber-library",
"proptest", "proptest",
@@ -367,7 +367,7 @@ dependencies = [
[[package]] [[package]]
name = "liber-lang" name = "liber-lang"
version = "0.4.3" version = "0.6.1"
dependencies = [ dependencies = [
"proptest", "proptest",
"serde", "serde",
@@ -379,7 +379,7 @@ dependencies = [
[[package]] [[package]]
name = "liber-library" name = "liber-library"
version = "0.4.3" version = "0.6.1"
dependencies = [ dependencies = [
"csv", "csv",
"encoding_rs", "encoding_rs",
+2 -2
View File
@@ -3,9 +3,9 @@ resolver = "3"
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"] members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
[workspace.package] [workspace.package]
version = "0.4.3" version = "0.6.1"
edition = "2024" edition = "2024"
license = "MPL-2.0" license = "CPAL-1.0"
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public" repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
rust-version = "1.88" rust-version = "1.88"
+140 -345
View File
@@ -1,373 +1,168 @@
Mozilla Public License Version 2.0 Common Public Attribution License Version 1.0 (CPAL)
==================================
1. Definitions 1. “Definitions”
--------------
1.1. "Contributor" 1.0.1 “Commercial Use” means distribution or otherwise making the Covered Code available to a third party.
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version" 1.1 “Contributor” means each entity that creates or contributes to the creation of Modifications.
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution" 1.2 “Contributor Version” means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor.
means Covered Software of a particular Contributor.
1.4. "Covered Software" 1.3 “Covered Code” means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof.
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses" 1.4 “Electronic Distribution Mechanism” means a mechanism generally accepted in the software development community for the electronic transfer of data.
means
(a) that the initial Contributor has attached the notice described 1.5 “Executable” means Covered Code in any form other than Source Code.
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of 1.6 “Initial Developer” means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A.
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form" 1.7 “Larger Work” means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.
means any form of the work other than Source Code Form.
1.7. "Larger Work" 1.8 “License” means this document.
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License" 1.8.1 “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein.
means this document.
1.9. "Licensable" 1.9 “Modifications” means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a Modification is:
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications" A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications.
means any of the following:
(a) any file in Source Code Form that results from an addition to, B. Any new file that contains any part of the Original Code or previous Modifications.
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered 1.10 “Original Code” means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License.
Software.
1.11. "Patent Claims" of a Contributor 1.10.1 “Patent Claims” means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor.
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License" 1.11 “Source Code” means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an Executable, or source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor’s choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge.
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form" 1.12 “You” (or “Your”) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, “You” includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
means the form of the work preferred for making modifications.
1.14. "You" (or "Your") 2. Source Code License.
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions 2.1 The Initial Developer Grant.
-------------------------------- The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims:
2.1. Grants (a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, and/or as part of a Larger Work; and
Each Contributor hereby grants You a world-wide, royalty-free, (b) under Patents Claims infringed by the making, using or selling of Original Code, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Code (or portions thereof).
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark) (c) the licenses granted in this Section 2.1(a) and (b) are effective on the date Initial Developer first distributes Original Code under the terms of this License.
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer (d) Notwithstanding Section 2.1(b) above, no patent license is granted: 1) for code that You delete from the Original Code; 2) separate from the Original Code; or 3) for infringements caused by: i) the modification of the Original Code or ii) the combination of the Original Code with other software or devices.
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date 2.2 Contributor Grant.
Subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license
The licenses granted in Section 2.1 with respect to any Contribution (a) under intellectual property rights (other than patent or trademark) Licensable by Contributor, to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code and/or as part of a Larger Work; and
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope (b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: 1) Modifications made by that Contributor (or portions thereof); and 2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination).
The licenses granted in this Section 2 are the only rights granted under (c) the licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first makes Commercial Use of the Covered Code.
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License. (d) Notwithstanding Section 2.2(b) above, no patent license is granted: 1) for any code that Contributor has deleted from the Contributor Version; 2) separate from the Contributor Version; 3) for infringements caused by: i) third party modifications of Contributor Version or ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or 4) under Patent Claims infringed by Covered Code in the absence of Modifications made by that Contributor.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor: 3. Distribution Obligations.
(a) for any code that a Contributor has removed from Covered Software; 3.1 Application of License.
or The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or restricts the applicable version of this License or the recipients’ rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5.
(b) for infringements caused by: (i) Your and any other third party's 3.2 Availability of Source Code.
modifications of Covered Software, or (ii) the combination of its Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party.
Contributions with other software (except as part of its Contributor
Version); or 3.3 Description of Modifications.
You must cause all Covered Code to which You contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code.
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions. 3.4 Intellectual Property Matters
This License does not grant any rights in the trademarks, service marks, (a) Third Party Claims. If Contributor has knowledge that a license under a third party’s intellectual property rights is required to exercise the rights granted by such Contributor under Sections 2.1 or 2.2, Contributor must include a text file with the Source Code distribution titled “LEGAL” which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If Contributor obtains such knowledge after the Modification is made available as described in Section 3.2, Contributor shall promptly modify the LEGAL file in all copies Contributor makes available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained.
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4). (b) Contributor APIs. If Contributor’s Modifications include an application programming interface and Contributor has knowledge of patent licenses which are reasonably necessary to implement that API, Contributor must also include this information in the LEGAL file.
2.4. Subsequent Licenses (c) Representations. Contributor represents that, except as disclosed pursuant to Section 3.4(a) above, Contributor believes that Contributor’s Modifications are Contributor’s original creation(s) and/or Contributor has sufficient rights to grant the rights conveyed by this License.
No Contributor makes additional grants as a result of Your choice to 3.5 Required Notices.
distribute the Covered Software under a subsequent version of this You must duplicate the notice in Exhibit A in each file of the Source Code. If it is not possible to put such notice in a particular Source Code file due to its structure, then You must include such notice in a location (such as a relevant directory) where a user would be likely to look for such a notice. If You created one or more Modification(s) You may add your name as a Contributor to the notice described in Exhibit A. You must also duplicate this License in any documentation for the Source Code where You describe recipients’ rights or ownership rights relating to Covered Code. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer.
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3). 3.6 Distribution of Executable Versions.
You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You describe recipients’ rights relating to the Covered Code. You may distribute the Executable version of Covered Code or ownership rights under a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient’s rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer, Original Developer or any Contributor. You hereby agree to indemnify the Initial Developer, Original Developer and every Contributor for any liability incurred by the Initial Developer, Original Developer or such Contributor as a result of any such terms You offer.
2.5. Representation
3.7 Larger Works.
Each Contributor represents that the Contributor believes its You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code.
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License. 4. Inability to Comply Due to Statute or Regulation.
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
2.6. Fair Use
5. Application of this License.
This License is not intended to limit any rights You have under This License applies to code to which the Initial Developer has attached the notice in Exhibit A and to related Covered Code.
applicable copyright doctrines of fair use, fair dealing, or other
equivalents. 6. Versions of the License.
2.7. Conditions 6.1 New Versions.
Socialtext, Inc. (“Socialtext”) may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number.
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1. 6.2 Effect of New Versions.
Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Socialtext. No one other than Socialtext has the right to modify the terms applicable to Covered Code created under this License.
3. Responsibilities
------------------- 6.3 Derivative Works.
If You create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), You must (a) rename Your license so that the phrases “Socialtext”, “CPAL” or any confusingly similar phrase do not appear in your license (except to note that your license differs from this License) and (b) otherwise make it clear that Your version of the license contains terms which differ from the CPAL. (Filling in the name of the Initial Developer, Original Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.)
3.1. Distribution of Source Form
7. DISCLAIMER OF WARRANTY.
All distribution of Covered Software in Source Code Form, including any COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER, ORIGINAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source 8. TERMINATION.
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not 8.1 This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive.
attempt to alter or restrict the recipients' rights in the Source Code
Form. 8.2 If You initiate litigation by asserting a patent infringement claim (excluding declatory judgment actions) against Initial Developer, Original Developer or a Contributor (the Initial Developer, Original Developer or Contributor against whom You file such action is referred to as “Participant”) alleging that:
3.2. Distribution of Executable Form (a) such Participant’s Contributor Version directly or indirectly infringes any patent, then any and all rights granted by such Participant to You under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively, unless if within 60 days after receipt of notice You either: (i) agree in writing to pay Participant a mutually agreeable reasonable royalty for Your past and future use of Modifications made by such Participant, or (ii) withdraw Your litigation claim with respect to the Contributor Version against such Participant. If within 60 days of notice, a reasonable royalty and payment arrangement are not mutually agreed upon in writing by the parties or the litigation claim is not withdrawn, the rights granted by Participant to You under Sections 2.1 and/or 2.2 automatically terminate at the expiration of the 60 day notice period specified above.
If You distribute Covered Software in Executable Form then: (b) any software, hardware, or device, other than such Participant’s Contributor Version, directly or indirectly infringes any patent, then any rights granted to You by such Participant under Sections 2.1(b) and 2.2(b) are revoked effective as of the date You first made, used, sold, distributed, or had made, Modifications made by that Participant.
(a) such Covered Software must also be made available in Source Code 8.3 If You assert a patent infringement claim against Participant alleging that such Participant’s Contributor Version directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code 8.4 In the event of termination under Sections 8.1 or 8.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or any distributor hereunder prior to termination shall survive termination.
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and 9. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ORIGINAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY’S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the 10. U.S. GOVERNMENT END USERS.
license for the Executable Form does not attempt to limit or alter The Covered Code is a “commercial item,” as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of “commercial computer software” and “commercial computer software documentation,” as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein.
the recipients' rights in the Source Code Form under this License.
11. MISCELLANEOUS.
3.3. Distribution of a Larger Work This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by California law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in the United States of America, any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California, with venue lying in Santa Clara County, California, with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys’ fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License.
You may create and distribute a Larger Work under terms of Your choice, 12. RESPONSIBILITY FOR CLAIMS.
provided that You also comply with the requirements of this License for As between Initial Developer, Original Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer, Original Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability.
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the 13. MULTIPLE-LICENSED CODE.
Covered Software is not Incompatible With Secondary Licenses, this Initial Developer may designate portions of the Covered Code as Multiple-Licensed. Multiple-Licensed means that the Initial Developer permits you to utilize portions of the Covered Code under Your choice of the CPAL or the alternative licenses, if any, specified by the Initial Developer in the file described in Exhibit A.
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of 14. ADDITIONAL TERM: ATTRIBUTION
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary (a) As a modest attribution to the organizer of the development of the Original Code (“Original Developer”), in the hope that its promotional value may help justify the time, money and effort invested in writing the Original Code, the Original Developer may include in Exhibit B (“Attribution Information”) a requirement that each time an Executable and Source Code or a Larger Work is launched or initially run (which includes initiating a session), a prominent display of the Original Developer’s Attribution Information (as defined below) must occur on the graphic user interface employed by the end user to access such Covered Code (which may include display on a splash screen), if any. The size of the graphic image should be consistent with the size of the other elements of the Attribution Information. If the access by the end user to the Executable and Source Code does not create a graphic user interface for access to the Covered Code, this obligation shall not apply. If the Original Code displays such Attribution Information in a particular form (such as in the form of a splash screen, notice at login, an “about” display, or dedicated attribution area on user interface screens), continued use of such form for that Attribution Information is one way of meeting this requirement for notice.
License(s).
(b) Attribution information may only include a copyright notice, a brief phrase, graphic image and a URL (“Attribution Information”) and is subject to the Attribution Limits as defined below. For these purposes, prominent shall mean display for sufficient duration to give reasonable notice to the user of the identity of the Original Developer and that if You include Attribution Information or similar information for other parties, You must ensure that the Attribution Information for the Original Developer shall be no less prominent than such Attribution Information or similar information for the other party. For greater certainty, the Original Developer may choose to specify in Exhibit B below that the above attribution requirement only applies to an Executable and Source Code resulting from the Original Code or any Modification, but not a Larger Work. The intent is to provide for reasonably modest attribution, therefore the Original Developer cannot require that You display, at any time, more than the following information as Attribution Information: (a) a copyright notice including the name of the Original Developer; (b) a word or one phrase (not exceeding 10 words); (c) one graphic image provided by the Original Developer; and (d) a URL (collectively, the “Attribution Limits”).
3.4. Notices
(c) If Exhibit B does not include any Attribution Information, then there are no requirements for You to display any Attribution Information of the Original Developer.
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, (d) You acknowledge that all trademarks, service marks and/or trade names contained within the Attribution Information distributed with the Covered Code are the exclusive property of their owners and may only be used with the permission of their owners, or under circumstances otherwise permitted by law or as expressly set out in this License.
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to 15. ADDITIONAL TERM: NETWORK USE.
the extent required to remedy known factual inaccuracies. The term “External Deployment” means the use, distribution, or communication of the Original Code or Modifications in any way such that the Original Code or Modifications may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Code or Modifications as a distribution under section 3.1 and make Source Code available under Section 3.2.
3.5. Application of Additional Terms EXHIBIT A. Common Public Attribution License Version 1.0.
You may choose to offer, and to charge a fee for, warranty, support, "The contents of this file are subject to the Common Public Attribution License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/license/cpal_1-0. The License is based on the Mozilla Public License Version 1.1 but Sections 14 and 15 have been added to cover use of software over a computer network and provide for limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent with Exhibit B.
indemnity or liability obligations to one or more recipients of Covered Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
Software. However, You may do so only on Your own behalf, and not on The Original Code is Liber-public.
behalf of any Contributor. You must make it absolutely clear that any The Original Developer is the Initial Developer.
such warranty, support, indemnity, or liability obligation is offered by The Initial Developer of the Original Code is Marek Novák. All portions of the code written by Marek Novák are Copyright (c) 2026. All Rights Reserved.
You alone, and You hereby agree to indemnify every Contributor for any Contributor: none."
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional EXHIBIT B. Attribution Information
disclaimers of warranty and limitations of liability specific to any
jurisdiction. Attribution Copyright Notice: Copyright (c) 2026 Marek Novák
Attribution Phrase (not exceeding 10 words): Built on Domi
4. Inability to Comply Due to Statute or Regulation Attribution URL: https://aula.marek-novak.cz
--------------------------------------------------- Graphic Image as provided in the Covered Code, if any: none.
Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+14 -1
View File
@@ -1,8 +1,21 @@
# Liber Domi — core # Liber Domi — core
The public, MPL-2.0 core of Liber Domi, the Domi home for books: e-book formats (EPUB, FB2, TXT, DRM-free The public, CPAL-1.0 core of Liber Domi, the Domi home for books: e-book formats (EPUB, FB2, TXT, DRM-free
MOBI/AZW3) into one sanitized document model, positions that survive re-rendering, the library model and its MOBI/AZW3) into one sanitized document model, positions that survive re-rendering, the library model and its
event-log merge, stats, Goodreads/StoryGraph import and the `liber-export` format. Pure Rust: no network, no UI, event-log merge, stats, Goodreads/StoryGraph import and the `liber-export` format. Pure Rust: no network, no UI,
no clock. See `docs/FORMATS.md` and `docs/DEPENDENCIES.md`. no clock. See `docs/FORMATS.md` and `docs/DEPENDENCIES.md`.
Liber never removes DRM: protected books are detected and refused. Liber never removes DRM: protected books are detected and refused.
## Licence
From this commit on, Liber-public is licensed under the **Common Public Attribution License 1.0** (SPDX
`CPAL-1.0`): see `LICENSE`. Versions before it (tags up to and including `v0.6.0`) stay available under MPL-2.0 to
those who received them.
**Credit (Exhibit B).** Anyone who redistributes this code, or a larger work built on it, must show this credit
where CPAL §14 asks for it (each time a program with a user interface is launched, for example on its About screen):
> Copyright (c) 2026 Marek Novák · Built on Domi · https://aula.marek-novak.cz
There is no graphic image. The credit is required in larger works too.
+234
View File
@@ -0,0 +1,234 @@
//! Czech: spelling is nearly phonemic. Rules: digraphs (ch, dž, ou, au, eu, ej), palatals (ď ť ň, and d t n before
//! i/í/ě), ě after labials (bě → bje, mě → mɲe), ř and its voiceless form, n before k/g, regressive voicing
//! assimilation and final devoicing, syllabic r and l, stress on the first syllable. Symbols follow espeak-ng `cs`.
/// One phoneme and whether it is a vowel nucleus.
#[derive(Clone, Debug, PartialEq)]
struct Ph {
s: String,
vowel: bool,
}
fn v(s: &str) -> Ph {
Ph { s: s.to_owned(), vowel: true }
}
fn c(s: &str) -> Ph {
Ph { s: s.to_owned(), vowel: false }
}
const R_HACEK: &str = "r\u{31D}";
const R_HACEK_VOICELESS: &str = "r\u{31D}\u{30A}";
/// Short words read without stress (prepositions and the like lean on the next word).
const CLITICS: [&str; 16] = ["a", "i", "v", "ve", "s", "se", "z", "ze", "k", "ke", "o", "u", "si", "jsem", "jsi", "že"];
fn letters(w: &str) -> Vec<Ph> {
let ch: Vec<char> = w.chars().collect();
let mut out = Vec::new();
let mut i = 0;
let at = |k: usize| ch.get(k).copied();
while i < ch.len() {
let x = ch[i];
let next = at(i + 1);
let after = at(i + 2);
// Two-letter units.
match (x, next) {
('c', Some('h')) => {
out.push(c("x"));
i += 2;
continue;
}
('d', Some('ž')) => {
out.push(c("dʒ"));
i += 2;
continue;
}
('o', Some('u')) => {
out.push(v("oʊ"));
i += 2;
continue;
}
('a', Some('u')) => {
out.push(v("aʊ"));
i += 2;
continue;
}
('e', Some('u')) => {
out.push(v("eʊ"));
i += 2;
continue;
}
('e', Some('j')) if after.is_none_or(|a| !"aáeéěiíoóuúůyý".contains(a)) => {
out.push(v("eɪ"));
i += 2;
continue;
}
// d t n before i í ě: ď ť ň.
('d' | 't' | 'n', Some('i' | 'í' | 'ě')) => {
out.push(c(match x {
'd' => "ɟ",
't' => "c",
_ => "ɲ",
}));
out.push(match next {
Some('í') => v("iː"),
Some('ě') => v("e"),
_ => v("i"),
});
i += 2;
continue;
}
// bě pě vě fě: b je; mě: m ɲe.
('b' | 'p' | 'v' | 'f', Some('ě')) => {
out.push(c(&x.to_string()));
out.push(c("j"));
out.push(v("e"));
i += 2;
continue;
}
('m', Some('ě')) => {
out.push(c("m"));
out.push(c("ɲ"));
out.push(v("e"));
i += 2;
continue;
}
_ => {}
}
let p = match x {
'a' => v("a"),
'á' => v("aː"),
'e' | 'ě' => v("e"),
'é' => v("eː"),
'i' | 'y' => v("i"),
'í' | 'ý' => v("iː"),
'o' => v("o"),
'ó' => v("oː"),
'u' => v("u"),
'ú' | 'ů' => v("uː"),
'c' => c("ts"),
'č' => c("tʃ"),
'ř' => c(R_HACEK),
'š' => c("ʃ"),
'ž' => c("ʒ"),
'ť' => c("c"),
'ď' => c("ɟ"),
'ň' => c("ɲ"),
'g' => c("ɡ"),
'q' => {
out.push(c("k"));
c("v")
}
'w' => c("v"),
'x' => {
out.push(c("k"));
c("s")
}
'n' if matches!(next, Some('k' | 'g')) => c("ŋ"),
x if x.is_alphabetic() => c(&x.to_string()),
_ => {
i += 1;
continue;
}
};
out.push(p);
i += 1;
}
out
}
/// Voiced ↔ voiceless obstruents.
const PAIRS: [(&str, &str); 11] = [
("b", "p"),
("d", "t"),
("ɟ", "c"),
("ɡ", "k"),
("v", "f"),
("z", "s"),
("ʒ", "ʃ"),
("h", "x"),
("dʒ", "tʃ"),
("dz", "ts"),
(R_HACEK, R_HACEK_VOICELESS),
];
fn voiced(s: &str) -> Option<bool> {
PAIRS.iter().find_map(|(a, b)| {
if s == *a {
Some(true)
} else if s == *b {
Some(false)
} else {
None
}
})
}
fn with_voice(s: &str, on: bool) -> String {
PAIRS
.iter()
.find_map(|(a, b)| if s == *a || s == *b { Some(if on { *a } else { *b }) } else { None })
.unwrap_or(s)
.to_owned()
}
fn assimilate(p: &mut [Ph]) {
// Right to left: the end of the word is voiceless; an obstruent takes the voicing of the obstruent after it
// (v and ř never pass their voicing on). ř is voiceless after a voiceless consonant.
let n = p.len();
for i in (0..n).rev() {
if p[i].vowel || voiced(&p[i].s).is_none() {
continue;
}
let next = p.get(i + 1).filter(|q| !q.vowel);
let target = match next {
// A one-consonant preposition (v, z, k, s) takes the next word's voicing, which one word cannot know.
None if i + 1 == n && n == 1 => None,
None if i + 1 == n => Some(false),
Some(q) if q.s != "v" && q.s != R_HACEK && q.s != R_HACEK_VOICELESS => voiced(&q.s),
_ => None,
};
if p[i].s == R_HACEK || p[i].s == R_HACEK_VOICELESS {
let after_voiceless = i > 0 && voiced(&p[i - 1].s) == Some(false);
if after_voiceless || target == Some(false) {
p[i].s = R_HACEK_VOICELESS.to_owned();
}
continue;
}
if let Some(t) = target {
p[i].s = with_voice(&p[i].s, t);
}
}
}
fn syllabic(p: &mut [Ph]) {
// r or l with no vowel on either side is the nucleus of its syllable (vlk, krk, Brno).
let n = p.len();
for i in 0..n {
if (p[i].s == "r" || p[i].s == "l") && !p[i].vowel {
let left = i == 0 || !p[i - 1].vowel;
let right = i + 1 == n || !p[i + 1].vowel;
if left && right && i > 0 {
p[i].s.push('\u{329}');
p[i].vowel = true;
}
}
}
}
pub fn word(w: &str) -> String {
let mut p = letters(w);
assimilate(&mut p);
syllabic(&mut p);
let stressed = !CLITICS.contains(&w);
let mut out = String::new();
let mut done = false;
for ph in &p {
if ph.vowel && !done && stressed {
out.push(super::STRESS);
done = true;
}
out.push_str(&ph.s);
}
out
}
+265
View File
@@ -0,0 +1,265 @@
//! German: rules for the common cases. Stress on the first syllable, after an unstressed prefix (be-, ge-, ver- …)
//! or on -ieren/-tion/-ei; vowels long when doubled, before h, in an open syllable, or before a single final
//! consonant (except short function words); unstressed e → ə, final -er → ɐ, r after a vowel vocalised (ɐ);
//! ch → x after a/o/u/au, ç elsewhere; sch, st-/sp-, z, final devoicing, -ig → ɪç. Symbols follow espeak-ng `de`.
#[derive(Clone, Debug)]
struct Ph {
s: String,
vowel: bool,
}
const PREFIXES: [&str; 8] = ["be", "ge", "er", "ver", "zer", "ent", "emp", "miss"];
/// Monosyllables whose vowel is short before one final consonant.
const SHORT: [&str; 28] = [
"das", "des", "es", "ist", "mit", "in", "im", "um", "an", "am", "ab", "ob", "von", "man", "bis", "was", "hat",
"weg", "ich", "mich", "dich", "sich", "nicht", "doch", "noch", "auch", "und", "ins",
];
fn is_vowel_letter(c: char) -> bool {
"aeiouäöüy".contains(c)
}
pub fn word(w: &str) -> String {
let ch: Vec<char> = w.chars().collect();
let n = ch.len();
// Where the stressed vowel is: the index into `ch` of the first letter of the stressed nucleus.
let mut stress_from = 0;
for p in PREFIXES {
if w.starts_with(p) && n > p.len() + 3 && ch[p.chars().count()..].iter().any(|&c| is_vowel_letter(c)) {
stress_from = p.chars().count();
break;
}
}
let ends = |s: &str| w.ends_with(s);
if ends("ieren") && n > 5 {
stress_from = n - 5;
} else if (ends("tion") || ends("erei")) && n > 4 {
stress_from = n - 2;
}
let mut out: Vec<Ph> = Vec::new();
let mut stressed_at: Option<usize> = None;
let mut i = 0;
let short_word = SHORT.contains(&w);
while i < n {
let x = ch[i];
let at = |k: usize| ch.get(k).copied();
let rest: String = ch[i..].iter().collect();
let cons = |s: &str| Ph { s: s.to_owned(), vowel: false };
let vow = |s: &str| Ph { s: s.to_owned(), vowel: true };
let mark = |out: &Vec<Ph>, stressed_at: &mut Option<usize>| {
if stressed_at.is_none() && i >= stress_from {
*stressed_at = Some(out.len());
}
};
// Consonant clusters first.
let (ph, step): (Option<Vec<Ph>>, usize) = if rest.starts_with("tsch") {
(Some(vec![cons("tʃ")]), 4)
} else if rest.starts_with("sch") {
(Some(vec![cons("ʃ")]), 3)
} else if rest.starts_with("chs") {
(Some(vec![cons("k"), cons("s")]), 3)
} else if rest.starts_with("ch") {
let back = out.last().is_some_and(|p| {
p.vowel && matches!(p.s.as_str(), "a" | "aː" | "o" | "oː" | "ɔ" | "u" | "uː" | "ʊ" | "aʊ")
});
(Some(vec![cons(if back { "x" } else { "ç" })]), 2)
} else if rest.starts_with("ck") {
(Some(vec![cons("k")]), 2)
} else if rest.starts_with("tz") || rest.starts_with("ts") {
(Some(vec![cons("t"), cons("s")]), 2)
} else if rest.starts_with("ph") {
(Some(vec![cons("f")]), 2)
} else if rest.starts_with("th") {
(Some(vec![cons("t")]), 2)
} else if rest.starts_with("qu") {
(Some(vec![cons("k"), cons("v")]), 2)
} else if rest.starts_with("ng") {
(Some(vec![cons("ŋ")]), 2)
} else if rest.starts_with("nk") {
(Some(vec![cons("ŋ"), cons("k")]), 2)
} else if rest.starts_with("pf") {
(Some(vec![cons("p"), cons("f")]), 2)
} else if rest.starts_with("dt") {
(Some(vec![cons("t")]), 2)
} else if (i == 0 || i == stress_from) && (rest.starts_with("st") || rest.starts_with("sp")) {
(Some(vec![cons("ʃ"), cons(&ch[i + 1].to_string())]), 2)
} else if rest == "ig" && i > 0 {
mark(&out, &mut stressed_at);
(Some(vec![vow("ɪ"), cons("ç")]), 2)
} else {
(None, 0)
};
if let Some(ps) = ph {
out.extend(ps);
i += step;
continue;
}
// Diphthongs and long spellings.
let di = match (x, at(i + 1)) {
('e' | 'a', Some('i' | 'y')) => Some("aɪ"),
('e' | 'ä', Some('u')) => Some("ɔʏ"),
('a', Some('u')) => Some("aʊ"),
('i', Some('e')) if at(i + 2) != Some('r') || i + 3 < n => Some("iː"),
('a', Some('a')) => Some("aː"),
('e', Some('e')) => Some("eː"),
('o', Some('o')) => Some("oː"),
_ => None,
};
if let Some(d) = di {
mark(&out, &mut stressed_at);
if d == "ɔʏ" {
out.push(vow("ɔ"));
out.push(Ph { s: "ʏ".into(), vowel: false });
} else {
out.push(vow(d));
}
i += 2;
if at(i) == Some('h') && !at(i + 1).is_some_and(is_vowel_letter) {
i += 1;
}
continue;
}
if is_vowel_letter(x) {
mark(&out, &mut stressed_at);
let next = at(i + 1);
let after = at(i + 2);
let is_stressed = stressed_at == Some(out.len());
// Unstressed e in endings.
let tail: String = ch[i..].iter().collect();
if x == 'e'
&& !is_stressed
&& (tail == "e" || tail == "en" || tail == "em" || tail == "es" || tail == "el" || tail == "et")
{
out.push(vow("ə"));
i += 1;
continue;
}
if x == 'e' && !is_stressed && tail == "er" {
out.push(vow("ɐ"));
i += 2;
continue;
}
// h after a vowel is silent and makes it long (gehen, Jahr, ruhig).
let silent_h = next == Some('h');
let uch = x == 'u' && next == Some('c') && after == Some('h') && at(i + 3).is_none();
let open = next.is_some_and(|c| !is_vowel_letter(c) && c != 'h')
&& after.is_some_and(is_vowel_letter)
&& !matches!((next, after), (Some('c'), Some('h')));
let final_single = next.is_some_and(|c| !is_vowel_letter(c)) && after.is_none() && !short_word;
let at_end = next.is_none();
let long =
silent_h || uch || (open && is_stressed) || (final_single && is_stressed) || (at_end && is_stressed);
let s = match (x, long) {
('a', true) => "aː",
('a', false) => "a",
('e', true) => "eː",
('e', false) => "ɛ",
('i' | 'y', true) => "iː",
('i' | 'y', false) => "ɪ",
('o', true) => "oː",
('o', false) => "ɔ",
('u', true) => "uː",
('u', false) => "ʊ",
('ä', true) => "ɛː",
('ä', false) => "ɛ",
('ö', true) => "øː",
('ö', false) => "œ",
('ü', true) => "yː",
_ => "ʏ",
};
out.push(vow(s));
i += if silent_h { 2 } else { 1 };
continue;
}
// A doubled consonant is one sound (Mann, Wasser, können).
if i > 0 && ch[i - 1] == x && !is_vowel_letter(x) {
i += 1;
continue;
}
// Single consonants.
let prev_vowel = out.last().is_some_and(|p| p.vowel);
let next_vowel = at(i + 1).is_some_and(is_vowel_letter);
let p: Option<&str> = match x {
'r' if prev_vowel && !next_vowel => Some("ɐ"),
'r' if i == 0 => Some("r"),
'r' => Some("ɾ"),
's' if next_vowel
&& (i == 0
|| prev_vowel
|| out.last().is_some_and(|p| matches!(p.s.as_str(), "l" | "n" | "m" | "ɾ"))) =>
{
Some("z")
}
'ß' => Some("s"),
'z' => {
out.push(cons("t"));
Some("s")
}
'v' => Some("f"),
'w' => Some("v"),
'j' => Some("j"),
'g' => Some("ɡ"),
'c' if at(i + 1).is_some_and(|c| "eiäy".contains(c)) => {
out.push(cons("t"));
Some("s")
}
'c' => Some("k"),
'x' => {
out.push(cons("k"));
Some("s")
}
'h' if prev_vowel => None,
x if x.is_alphabetic() => {
out.push(cons(&x.to_string()));
None
}
_ => None,
};
if let Some(p) = p {
out.push(if p == "ɐ" { vow("ɐ") } else { cons(p) });
if p == "ɐ" {
// Vocalic r is not a syllable of its own.
out.last_mut().expect("pushed").vowel = false;
}
}
i += 1;
}
// Final devoicing: a voiced obstruent before a consonant or at the end.
let n = out.len();
for k in 0..n {
let last = k + 1 == n
|| !out[k + 1].vowel
&& out[k + 1].s != "ɾ"
&& out[k + 1].s != "l"
&& out[k + 1].s != "r"
&& out[k + 1].s != "j"
&& out[k + 1].s != "ʏ";
if last && !out[k].vowel {
let d = match out[k].s.as_str() {
"b" => Some("p"),
"d" => Some("t"),
"ɡ" => Some("k"),
"v" => Some("f"),
"z" => Some("s"),
_ => None,
};
if let Some(d) = d {
out[k].s = d.to_owned();
}
}
}
let mut s = String::new();
for (k, p) in out.iter().enumerate() {
if Some(k) == stressed_at && !short_word_unstressed(w) {
s.push(super::STRESS);
}
s.push_str(&p.s);
}
s
}
/// Articles and similar short words carry no stress mark.
fn short_word_unstressed(w: &str) -> bool {
matches!(w, "der" | "die" | "dem" | "den" | "ein" | "eine" | "einen" | "zu" | "und" | "oder" | "es" | "sie" | "er")
}
+201
View File
@@ -0,0 +1,201 @@
//! English: CMUdict's ARPABET → espeak-ng `en-us` IPA (stress before the vowel, ɜː/ɚ for stressed/unstressed ER,
//! t flapped to ɾ between a vowel and an unstressed vowel), and letter-to-sound rules for words not in the
//! dictionary (good enough for names and rare words, never the main path).
const VOWELS: [(&str, &str, &str); 15] = [
// ARPABET, stressed, unstressed
("AA", "ɑː", "ɑː"),
("AE", "æ", "æ"),
("AH", "ʌ", "ə"),
("AO", "ɔː", "ɔː"),
("AW", "aʊ", "aʊ"),
("AY", "aɪ", "aɪ"),
("EH", "ɛ", "ɛ"),
("ER", "ɜː", "ɚ"),
("EY", "eɪ", "eɪ"),
("IH", "ɪ", "ɪ"),
("IY", "iː", "i"),
("OW", "oʊ", "oʊ"),
("OY", "ɔɪ", "ɔɪ"),
("UH", "ʊ", "ʊ"),
("UW", "uː", "uː"),
];
const CONSONANTS: [(&str, &str); 24] = [
("B", "b"),
("CH", "tʃ"),
("D", "d"),
("DH", "ð"),
("F", "f"),
("G", "ɡ"),
("HH", "h"),
("JH", "dʒ"),
("K", "k"),
("L", "l"),
("M", "m"),
("N", "n"),
("NG", "ŋ"),
("P", "p"),
("R", "ɹ"),
("S", "s"),
("SH", "ʃ"),
("T", "t"),
("TH", "θ"),
("V", "v"),
("W", "w"),
("Y", "j"),
("Z", "z"),
("ZH", "ʒ"),
];
/// One ARPABET pronunciation in IPA; `None` for an unknown symbol.
pub fn from_arpabet(arpa: &[&str]) -> Option<String> {
// (ipa, is vowel, stress 0/1/2)
let mut ph: Vec<(String, bool, u8)> = Vec::with_capacity(arpa.len());
for a in arpa {
let (base, stress) = match a.chars().last() {
Some(d @ '0'..='2') => (&a[..a.len() - 1], d as u8 - b'0'),
_ => (*a, 0),
};
if let Some((_, s, u)) = VOWELS.iter().find(|(k, _, _)| *k == base) {
ph.push(((if stress > 0 { *s } else { *u }).to_owned(), true, stress));
} else if let Some((_, c)) = CONSONANTS.iter().find(|(k, _)| *k == base) {
ph.push(((*c).to_owned(), false, 0));
} else {
return None;
}
}
// Flapping: t (or d) after a vowel or r, before an unstressed vowel → ɾ (better, water, ladder).
for i in 1..ph.len().saturating_sub(1) {
if (ph[i].0 == "t" || ph[i].0 == "d") && (ph[i - 1].1 || ph[i - 1].0 == "ɹ") && ph[i + 1].1 && ph[i + 1].2 == 0
{
ph[i].0 = "ɾ".to_owned();
}
}
let mut out = String::new();
for (s, vowel, stress) in &ph {
if *vowel {
match stress {
1 => out.push(super::STRESS),
2 => out.push(super::STRESS2),
_ => {}
}
}
out.push_str(s);
}
Some(out)
}
/// Letter-to-sound for words the dictionary does not have: common English spellings, stress on the first vowel.
pub fn rules(w: &str) -> String {
const UNITS: [(&str, &str); 38] = [
("tion", "ʃən"),
("sion", "ʒən"),
("ough", "ʌf"),
("igh", "aɪ"),
("tch", "tʃ"),
("sch", "sk"),
("ee", "iː"),
("ea", "iː"),
("oo", "uː"),
("ou", "aʊ"),
("ow", "oʊ"),
("oa", "oʊ"),
("ai", "eɪ"),
("ay", "eɪ"),
("oi", "ɔɪ"),
("oy", "ɔɪ"),
("au", "ɔː"),
("aw", "ɔː"),
("ar", "ɑːɹ"),
("or", "ɔːɹ"),
("er", "ɚ"),
("ir", "ɜː"),
("ur", "ɜː"),
("ch", "tʃ"),
("sh", "ʃ"),
("th", "θ"),
("ph", "f"),
("wh", "w"),
("ck", "k"),
("ng", "ŋ"),
("qu", "kw"),
("kn", "n"),
("wr", "ɹ"),
("gh", ""),
("ll", "l"),
("ss", "s"),
("tt", "t"),
("nn", "n"),
];
let ch: Vec<char> = w.chars().filter(|c| c.is_alphabetic() || *c == '\'').collect();
let s: String = ch.iter().collect();
let mut out = String::new();
let mut stressed = false;
let mut i = 0;
let vowel_ipa = |c: char, next: Option<char>, after: Option<char>| -> Option<&'static str> {
// A vowel before one consonant and a final e is long (make, time, home, cute).
let magic = next.is_some_and(|n| !"aeiou".contains(n)) && after == Some('e');
Some(match (c, magic) {
('a', true) => "eɪ",
('a', false) => "æ",
('e', _) => "ɛ",
('i', true) => "aɪ",
('i', false) => "ɪ",
('o', true) => "oʊ",
('o', false) => "ɑː",
('u', true) => "juː",
('u', false) => "ʌ",
('y', _) => "i",
_ => return None,
})
};
while i < ch.len() {
let rest = &s[s.char_indices().nth(i).map_or(s.len(), |(b, _)| b)..];
if let Some((k, v)) = UNITS.iter().find(|(k, _)| rest.starts_with(k)) {
let is_vowel = v.starts_with(|c: char| "iːuːaʊoʊeɪɔɪɑɚɜʌæɛɪəʊ".contains(c));
if is_vowel && !stressed {
out.push(super::STRESS);
stressed = true;
}
out.push_str(v);
i += k.chars().count();
continue;
}
let c = ch[i];
let next = ch.get(i + 1).copied();
let after = ch.get(i + 2).copied();
// A final e after a consonant is silent.
if c == 'e' && next.is_none() && i > 0 {
i += 1;
continue;
}
if "aeiouy".contains(c) && !(c == 'y' && i == 0) {
if let Some(v) = vowel_ipa(c, next, after) {
if !stressed {
out.push(super::STRESS);
stressed = true;
}
out.push_str(v);
}
i += 1;
continue;
}
let sound: String = match c {
'c' if next.is_some_and(|n| "eiy".contains(n)) => "s".into(),
'c' => "k".into(),
'g' if next.is_some_and(|n| "eiy".contains(n)) => "dʒ".into(),
'g' => "ɡ".into(),
'j' => "dʒ".into(),
'q' => "k".into(),
'r' => "ɹ".into(),
'x' => "ks".into(),
'y' => "j".into(),
c if c.is_ascii_alphabetic() => c.to_string(),
_ => String::new(),
};
out.push_str(&sound);
i += 1;
}
out
}
+162
View File
@@ -0,0 +1,162 @@
//! Text → phonemes for the reading voices (Day 4, `docs/04_listening.md` in the app repo).
//!
//! The voices (Piper VITS models) were trained on espeak-ng's IPA. espeak-ng is GPL, so it is not used: this module
//! writes the same conventions itself — stress marks (`ˈ`, `ˌ`) right before the stressed vowel, `ː` for length,
//! words separated by spaces, `. , ? ! ; :` kept as they are. Czech and German are rules; English is a pronouncing
//! dictionary (CMUdict, BSD-style, supplied by the app) with rules for words it does not have. Numbers are spelled
//! out first. [`tokens`] splits the result into the voice's symbols.
pub mod cs;
pub mod de;
pub mod en;
pub mod num;
use crate::Lang;
use crate::token::{Kind, tokens as words};
use std::collections::HashMap;
use unicode_normalization::UnicodeNormalization;
/// Primary and secondary stress, length.
pub const STRESS: char = 'ˈ';
pub const STRESS2: char = 'ˌ';
pub const LONG: char = 'ː';
/// English pronunciations (word → IPA with stress), from CMUdict.
#[derive(Default)]
pub struct Lexicon(HashMap<String, String>);
/// Caps for a pronouncing dictionary read from a file (hostile input).
pub const LEXICON_MAX_BYTES: usize = 16 << 20;
pub const LEXICON_MAX_ENTRIES: usize = 400_000;
impl Lexicon {
/// CMUdict's format: `WORD PH1 PH2 …` (ARPABET with stress digits); `;;;` comments; `WORD(2)` alternates are
/// skipped (the first pronunciation is the common one).
pub fn from_cmudict(text: &str) -> Option<Lexicon> {
if text.len() > LEXICON_MAX_BYTES {
return None;
}
let mut map = HashMap::new();
for line in text.lines() {
if line.starts_with(";;;") || line.trim().is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(word) = parts.next() else { continue };
if word.contains('(') || word.len() > 48 {
continue;
}
let arpa: Vec<&str> = parts.collect();
if arpa.is_empty() || arpa.len() > 48 {
continue;
}
if map.len() >= LEXICON_MAX_ENTRIES {
return None;
}
if let Some(ipa) = en::from_arpabet(&arpa) {
map.entry(word.to_lowercase()).or_insert(ipa);
}
}
Some(Lexicon(map))
}
pub fn get(&self, word: &str) -> Option<&str> {
self.0.get(word).map(String::as_str)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Adds an entry (tests, a reader's own corrections).
pub fn insert(&mut self, word: &str, ipa: &str) {
self.0.insert(word.to_lowercase(), ipa.to_owned());
}
}
/// One word's IPA in a language.
pub fn word(w: &str, lang: Lang, lex: Option<&Lexicon>) -> String {
let lower: String = w.nfc().flat_map(char::to_lowercase).collect();
let lower = lower.replace(['\u{2019}', '\u{2018}'], "'");
match lang {
Lang::Cs => cs::word(&lower),
Lang::De => de::word(&lower),
// Latin has no voice of its own; read with the Czech rules (close to the school pronunciation in Czechia).
Lang::La => cs::word(&lower),
Lang::En => lex.and_then(|l| l.get(&lower)).map(str::to_owned).unwrap_or_else(|| en::rules(&lower)),
}
}
/// A sentence (or any text) in IPA, the way espeak-ng writes it: words separated by spaces, punctuation attached.
pub fn ipa(text: &str, lang: Lang, lex: Option<&Lexicon>) -> String {
let mut out = String::new();
let push_word = |out: &mut String, w: &str| {
if w.is_empty() {
return;
}
if !out.is_empty() && !out.ends_with(' ') {
out.push(' ');
}
out.push_str(w);
};
for t in words(text) {
match t.kind {
Kind::Word => push_word(&mut out, &word(&t.text, lang, lex)),
Kind::Number => {
let digits: String = t.text.chars().filter(|c| c.is_ascii_digit()).collect();
match digits.parse::<u64>().ok().and_then(|n| num::words(n, lang)) {
Some(spelled) => {
for w in spelled.split_whitespace() {
push_word(&mut out, &word(w, lang, lex));
}
}
None => push_word(&mut out, &word(&t.text, lang, lex)),
}
}
Kind::Punct => {
let p = match t.text.as_str() {
"." | "…" => Some('.'),
"," | "–" | "—" | "-" => Some(','),
"?" => Some('?'),
"!" => Some('!'),
";" => Some(';'),
":" => Some(':'),
_ => None,
};
if let Some(p) = p
&& !out.is_empty()
&& !out.ends_with(['.', ',', '?', '!', ';', ':'])
{
let trimmed = out.trim_end().len();
out.truncate(trimmed);
out.push(p);
}
}
}
}
out.trim().to_owned()
}
/// The voice's symbols: NFD code points, with the voice's vowel clusters (`aɪ`, `oʊ` …) merged into one symbol.
pub fn tokens(ipa: &str, clusters: &[(String, String)]) -> Vec<String> {
let chars: Vec<char> = ipa.nfd().collect();
let mut out = Vec::with_capacity(chars.len());
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if let Some(&n) = chars.get(i + 1)
&& clusters.iter().any(|(a, b)| a.chars().eq(std::iter::once(c)) && b.chars().eq(std::iter::once(n)))
{
out.push(format!("{c}{n}"));
i += 2;
continue;
}
out.push(c.to_string());
i += 1;
}
out
}
+207
View File
@@ -0,0 +1,207 @@
//! Numbers as words, so a voice reads "1847" as a year and "3" as three. Cardinals below a billion; English and
//! German read 1100–1999 as years when they stand alone (the common case in books).
use crate::Lang;
/// The words for `n`, or `None` when it is too large to read.
pub fn words(n: u64, lang: Lang) -> Option<String> {
if n >= 1_000_000_000 {
return None;
}
Some(match lang {
Lang::En => en(n),
Lang::De => de(n),
Lang::Cs | Lang::La => cs(n),
})
}
fn en(n: u64) -> String {
const ONES: [&str; 20] = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
];
const TENS: [&str; 10] = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
fn below_100(n: u64) -> String {
if n < 20 {
ONES[n as usize].to_owned()
} else if n.is_multiple_of(10) {
TENS[(n / 10) as usize].to_owned()
} else {
format!("{} {}", TENS[(n / 10) as usize], ONES[(n % 10) as usize])
}
}
fn below_1000(n: u64) -> String {
match (n / 100, n % 100) {
(0, r) => below_100(r),
(h, 0) => format!("{} hundred", ONES[h as usize]),
(h, r) => format!("{} hundred {}", ONES[h as usize], below_100(r)),
}
}
if (1100..2000).contains(&n) && !n.is_multiple_of(100) {
let r = n % 100;
return format!(
"{} {}",
below_100(n / 100),
if r < 10 { format!("oh {}", ONES[r as usize]) } else { below_100(r) }
);
}
let (m, k, r) = (n / 1_000_000, (n / 1000) % 1000, n % 1000);
let mut parts = Vec::new();
if m > 0 {
parts.push(format!("{} million", below_1000(m)));
}
if k > 0 {
parts.push(format!("{} thousand", below_1000(k)));
}
if r > 0 || parts.is_empty() {
parts.push(below_1000(r));
}
parts.join(" ")
}
fn de(n: u64) -> String {
const ONES: [&str; 20] = [
"null",
"eins",
"zwei",
"drei",
"vier",
"fünf",
"sechs",
"sieben",
"acht",
"neun",
"zehn",
"elf",
"zwölf",
"dreizehn",
"vierzehn",
"fünfzehn",
"sechzehn",
"siebzehn",
"achtzehn",
"neunzehn",
];
const TENS: [&str; 10] =
["", "", "zwanzig", "dreißig", "vierzig", "fünfzig", "sechzig", "siebzig", "achtzig", "neunzig"];
fn unit(n: u64) -> &'static str {
if n == 1 { "ein" } else { ONES[n as usize] }
}
fn below_100(n: u64) -> String {
if n < 20 {
ONES[n as usize].to_owned()
} else if n.is_multiple_of(10) {
TENS[(n / 10) as usize].to_owned()
} else {
format!("{}und{}", unit(n % 10), TENS[(n / 10) as usize])
}
}
fn below_1000(n: u64) -> String {
match (n / 100, n % 100) {
(0, r) => below_100(r),
(h, 0) => format!("{}hundert", unit(h)),
(h, r) => format!("{}hundert{}", unit(h), below_100(r)),
}
}
if (1100..2000).contains(&n) {
let r = n % 100;
return format!("{}hundert{}", below_100(n / 100), if r == 0 { String::new() } else { below_100(r) });
}
let (m, k, r) = (n / 1_000_000, (n / 1000) % 1000, n % 1000);
let mut s = String::new();
if m > 0 {
s.push_str(&if m == 1 { "eine Million ".to_owned() } else { format!("{} Millionen ", below_1000(m)) });
}
if k > 0 {
s.push_str(&format!("{}tausend", if k == 1 { "ein".to_owned() } else { below_1000(k) }));
}
if r > 0 || s.is_empty() {
s.push_str(&below_1000(r));
}
s.trim().to_owned()
}
fn cs(n: u64) -> String {
const ONES: [&str; 20] = [
"nula",
"jedna",
"dva",
"tři",
"čtyři",
"pět",
"šest",
"sedm",
"osm",
"devět",
"deset",
"jedenáct",
"dvanáct",
"třináct",
"čtrnáct",
"patnáct",
"šestnáct",
"sedmnáct",
"osmnáct",
"devatenáct",
];
const TENS: [&str; 10] =
["", "", "dvacet", "třicet", "čtyřicet", "padesát", "šedesát", "sedmdesát", "osmdesát", "devadesát"];
const HUNDREDS: [&str; 10] =
["", "sto", "dvě stě", "tři sta", "čtyři sta", "pět set", "šest set", "sedm set", "osm set", "devět set"];
fn below_1000(n: u64) -> String {
let (h, r) = (n / 100, n % 100);
let mut parts = Vec::new();
if h > 0 {
parts.push(HUNDREDS[h as usize].to_owned());
}
if r > 0 {
if r < 20 {
parts.push(ONES[r as usize].to_owned());
} else {
parts.push(TENS[(r / 10) as usize].to_owned());
if r % 10 > 0 {
parts.push(ONES[(r % 10) as usize].to_owned());
}
}
}
parts.join(" ")
}
let (m, k, r) = (n / 1_000_000, (n / 1000) % 1000, n % 1000);
let mut parts = Vec::new();
if m > 0 {
parts.push(match m {
1 => "milion".to_owned(),
2..=4 => format!("{} miliony", below_1000(m)),
_ => format!("{} milionů", below_1000(m)),
});
}
if k > 0 {
parts.push(match k {
1 => "tisíc".to_owned(),
2..=4 => format!("{} tisíce", below_1000(k)),
_ => format!("{} tisíc", below_1000(k)),
});
}
if r > 0 || parts.is_empty() {
parts.push(if n == 0 { "nula".to_owned() } else { below_1000(r) });
}
parts.join(" ")
}
+2
View File
@@ -119,6 +119,7 @@ impl Rules {
Lang::En => EN_IRREGULAR, Lang::En => EN_IRREGULAR,
Lang::De => DE_IRREGULAR, Lang::De => DE_IRREGULAR,
Lang::La => LA_IRREGULAR, Lang::La => LA_IRREGULAR,
Lang::Cs => &[],
}; };
Rules { lang, irregular: list.iter().copied().collect() } Rules { lang, irregular: list.iter().copied().collect() }
} }
@@ -134,6 +135,7 @@ impl Rules {
Lang::En => en(&w), Lang::En => en(&w),
Lang::De => de(&w, capital), Lang::De => de(&w, capital),
Lang::La => la(&w), Lang::La => la(&w),
Lang::Cs => vec![],
}; };
out.push(w); out.push(w);
let mut seen = HashSet::new(); let mut seen = HashSet::new();
+5
View File
@@ -13,6 +13,7 @@
pub mod align; pub mod align;
pub mod concept; pub mod concept;
pub mod g2p;
pub mod lemma; pub mod lemma;
pub mod level; pub mod level;
pub mod profile; pub mod profile;
@@ -31,6 +32,8 @@ pub enum Lang {
En, En,
De, De,
La, La,
/// Day 4: Czech, for reading aloud (the reader's own language; no lemma rules).
Cs,
} }
impl Lang { impl Lang {
@@ -41,6 +44,7 @@ impl Lang {
"en" | "eng" => Some(Lang::En), "en" | "eng" => Some(Lang::En),
"de" | "ger" | "deu" => Some(Lang::De), "de" | "ger" | "deu" => Some(Lang::De),
"la" | "lat" => Some(Lang::La), "la" | "lat" => Some(Lang::La),
"cs" | "cze" | "ces" => Some(Lang::Cs),
_ => None, _ => None,
} }
} }
@@ -50,6 +54,7 @@ impl Lang {
Lang::En => "en", Lang::En => "en",
Lang::De => "de", Lang::De => "de",
Lang::La => "la", Lang::La => "la",
Lang::Cs => "cs",
} }
} }
} }
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn is_name(tok: &Token, lang: Lang, lem: &dyn Lemmatizer) -> bool {
match lang { match lang {
Lang::De => !lem.knows(&tok.text) && !tok.sentence_start && lem.knows("Haus"), Lang::De => !lem.knows(&tok.text) && !tok.sentence_start && lem.knows("Haus"),
Lang::En => !tok.sentence_start && tok.text != "I" && !tok.text.starts_with("I'"), Lang::En => !tok.sentence_start && tok.text != "I" && !tok.text.starts_with("I'"),
Lang::La => !tok.sentence_start, Lang::La | Lang::Cs => !tok.sentence_start,
} }
} }
+38
View File
@@ -0,0 +1,38 @@
# Czech words and the IPA espeak-ng conventions give them (stress before the first vowel), written for this repository.
dobrý dˈobriː
den dˈen
jak jˈak
máte mˈaːte
řeka r̝ˈeka
tři tr̝̊ˈi
moře mˈor̝e
dítě ɟˈiːce
něco ɲˈetso
čtyři tʃtˈir̝i
chleba xlˈeba
hrad hrˈat
kde ɡdˈe
vlk vˈl̩k
krk kˈr̩k
pouze pˈoʊze
auto ˈaʊto
mě mɲˈe
pět pjˈet
banka bˈaŋka
ještě jˈeʃce
kůň kˈuːɲ
džus dʒˈus
nejlepší nˈeɪlepʃiː
vůz vˈuːs
léto lˈeːto
odpověď ˈotpovjec
kniha kɲˈiha
otec ˈotets
matka mˈatka
dívka ɟˈiːfka
sníh sɲˈiːx
lidé lˈideː
Praha prˈaha
v v
a a
že ʒe
1 # Czech words and the IPA espeak-ng conventions give them (stress before the first vowel), written for this repository.
2 dobrý dˈobriː
3 den dˈen
4 jak jˈak
5 máte mˈaːte
6 řeka r̝ˈeka
7 tři tr̝̊ˈi
8 moře mˈor̝e
9 dítě ɟˈiːce
10 něco ɲˈetso
11 čtyři tʃtˈir̝i
12 chleba xlˈeba
13 hrad hrˈat
14 kde ɡdˈe
15 vlk vˈl̩k
16 krk kˈr̩k
17 pouze pˈoʊze
18 auto ˈaʊto
19 mě mɲˈe
20 pět pjˈet
21 banka bˈaŋka
22 ještě jˈeʃce
23 kůň kˈuːɲ
24 džus dʒˈus
25 nejlepší nˈeɪlepʃiː
26 vůz vˈuːs
27 léto lˈeːto
28 odpověď ˈotpovjec
29 kniha kɲˈiha
30 otec ˈotets
31 matka mˈatka
32 dívka ɟˈiːfka
33 sníh sɲˈiːx
34 lidé lˈideː
35 Praha prˈaha
36 v v
37 a a
38 že ʒe
+31
View File
@@ -0,0 +1,31 @@
# German words and the IPA espeak-ng conventions give them (stress before the stressed vowel), written for this repository.
haus hˈaʊs
mann mˈan
vater fˈaːtɐ
kinder kˈɪndɐ
schule ʃˈuːlə
ich ˈɪç
nacht nˈaxt
bäcker bˈɛkɐ
tag tˈaːk
liebe lˈiːbə
zeit tsˈaɪt
freund fɾˈɔʏnt
stein ʃtˈaɪn
gehen ɡˈeːən
verstehen fɛɐʃtˈeːən
sprechen ʃpɾˈɛçən
über ˈyːbɐ
schön ʃˈøːn
können kˈœnən
bruder bɾˈuːdɐ
mit mˈɪt
das dˈas
wasser vˈasɐ
zug tsˈuːk
jahr jˈaːɐ
milch mˈɪlç
buch bˈuːx
kind kˈɪnt
fisch fˈɪʃ
morgen mˈɔɐɡən
1 # German words and the IPA espeak-ng conventions give them (stress before the stressed vowel), written for this repository.
2 haus hˈaʊs
3 mann mˈan
4 vater fˈaːtɐ
5 kinder kˈɪndɐ
6 schule ʃˈuːlə
7 ich ˈɪç
8 nacht nˈaxt
9 bäcker bˈɛkɐ
10 tag tˈaːk
11 liebe lˈiːbə
12 zeit tsˈaɪt
13 freund fɾˈɔʏnt
14 stein ʃtˈaɪn
15 gehen ɡˈeːən
16 verstehen fɛɐʃtˈeːən
17 sprechen ʃpɾˈɛçən
18 über ˈyːbɐ
19 schön ʃˈøːn
20 können kˈœnən
21 bruder bɾˈuːdɐ
22 mit mˈɪt
23 das dˈas
24 wasser vˈasɐ
25 zug tsˈuːk
26 jahr jˈaːɐ
27 milch mˈɪlç
28 buch bˈuːx
29 kind kˈɪnt
30 fisch fˈɪʃ
31 morgen mˈɔɐɡən
+119
View File
@@ -0,0 +1,119 @@
//! Day 4: text → phonemes for the reading voices. Gold pronunciations written for this repository in espeak-ng's
//! conventions (the voices were trained on them); the accuracy per language is stated in the app's
//! `docs/04_listening.md` and held here as a floor.
use liber_lang::Lang;
use liber_lang::g2p::{Lexicon, en, ipa, num, tokens, word};
fn fixture(text: &str) -> Vec<(String, String)> {
text.lines()
.map(|l| l.trim_end_matches('\r'))
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| {
let (w, p) = l.split_once('\t').expect("word<TAB>ipa");
(w.to_owned(), p.to_owned())
})
.collect()
}
fn accuracy(lang: Lang, cases: &[(String, String)]) -> (usize, Vec<String>) {
let mut wrong = Vec::new();
let ok = cases
.iter()
.filter(|(w, want)| {
let got = word(w, lang, None);
let hit = got == *want;
if !hit {
wrong.push(format!("{w} → {got} (want {want})"));
}
hit
})
.count();
(ok, wrong)
}
#[test]
fn czech_words() {
let cases = fixture(include_str!("fixtures/g2p_cs.tsv"));
let (ok, wrong) = accuracy(Lang::Cs, &cases);
println!("cs: {ok}/{} — {}", cases.len(), wrong.join("; "));
assert!(ok as f64 / cases.len() as f64 >= 0.95, "{wrong:?}");
}
#[test]
fn german_words() {
let cases = fixture(include_str!("fixtures/g2p_de.tsv"));
let (ok, wrong) = accuracy(Lang::De, &cases);
println!("de: {ok}/{} — {}", cases.len(), wrong.join("; "));
assert!(ok as f64 / cases.len() as f64 >= 0.9, "{wrong:?}");
}
#[test]
fn english_from_cmudict_and_rules() {
// CMUdict lines (the format the app reads; the words' ARPABET is common knowledge, not the file).
let lex = Lexicon::from_cmudict(
";;; a comment\nHELLO HH AH0 L OW1\nHELLO(2) HH EH0 L OW1\nWORLD W ER1 L D\nBETTER B EH1 T ER0\nTHE DH AH0\nMOTHER M AH1 DH ER0\nFATHER F AA1 DH ER0\nCAT K AE1 T\nTHINKING TH IH1 NG K IH0 NG\nBOY B OY1\nTOMORROW T AH0 M AA1 R OW2\nBAD B AE1 D XX9\n",
)
.expect("parses");
let cases = [
("hello", "həlˈoʊ"),
("world", "wˈɜːld"),
("better", "bˈɛɾɚ"),
("the", "ðə"),
("mother", "mˈʌðɚ"),
("father", "fˈɑːðɚ"),
("cat", "kˈæt"),
("thinking", "θˈɪŋkɪŋ"),
("boy", "bˈɔɪ"),
("tomorrow", "təmˈɑːɹˌoʊ"),
];
for (w, want) in cases {
assert_eq!(word(w, Lang::En, Some(&lex)), want, "{w}");
}
assert!(lex.get("bad").is_none(), "an unknown ARPABET symbol drops the entry");
assert_eq!(lex.len(), 10, "alternates and bad lines skipped");
// Words not in the dictionary still get a reading: stressed, from the voice's symbols.
let inventory = "ˈˌːabdefhijklmnoprstuvwzæðŋɐɑɔəɚɛɜɡɪɹʃʊʌʒθɾ";
for w in ["make", "night", "station", "zork", "liber"] {
let r = en::rules(w);
assert!(r.starts_with(|c: char| c != ' ') && r.contains('ˈ'), "{w} → {r}");
assert!(r.chars().all(|c| inventory.contains(c)), "{w} → {r}");
}
assert_eq!(en::rules("make"), "mˈeɪk");
assert_eq!(en::rules("night"), "nˈaɪt");
}
#[test]
fn sentences_numbers_and_punctuation() {
assert_eq!(ipa("Dobrý den, jak se máte?", Lang::Cs, None), "dˈobriː dˈen, jˈak se mˈaːte?");
assert_eq!(ipa("Tři kočky.", Lang::Cs, None), "tr̝̊ˈi kˈotʃki.");
// Numbers are read as words in the sentence's language.
assert_eq!(num::words(1847, Lang::En).as_deref(), Some("eighteen forty seven"));
assert_eq!(num::words(1847, Lang::De).as_deref(), Some("achtzehnhundertsiebenundvierzig"));
assert_eq!(num::words(1847, Lang::Cs).as_deref(), Some("tisíc osm set čtyřicet sedm"));
assert_eq!(num::words(21, Lang::De).as_deref(), Some("einundzwanzig"));
assert_eq!(num::words(2_000_000_000, Lang::En), None);
assert!(ipa("V roce 1847 koupil mlýn.", Lang::Cs, None).contains("cˈisiːts"), "tisíc: ti is ť");
// Quotes and dashes never become sounds; a dash is a pause.
assert_eq!(ipa("»Ano« – řekl.", Lang::Cs, None), "ˈano, r̝ˈekl̩.");
}
#[test]
fn tokens_merge_the_voices_clusters() {
let clusters: Vec<(String, String)> = [("a", "ɪ"), ("a", "ʊ"), ("e", "ɪ"), ("o", "ʊ"), ("ɔ", "ɪ")]
.iter()
.map(|(a, b)| ((*a).to_owned(), (*b).to_owned()))
.collect();
assert_eq!(tokens("hˈaʊs", &clusters), ["h", "ˈ", "aʊ", "s"]);
// ř is r + a combining mark (and a second for the voiceless one): separate symbols, as the voice learned them.
assert_eq!(tokens("tr̝̊ˈi", &clusters), ["t", "r", "\u{31D}", "\u{30A}", "ˈ", "i"]);
// ç decomposes (NFD) to c + combining cedilla, the way the German voice was trained.
assert_eq!(tokens("ˈɪç", &clusters), ["ˈ", "ɪ", "c", "\u{327}"]);
}
#[test]
fn hostile_dictionaries_are_refused() {
assert!(Lexicon::from_cmudict(&"A AH0\n".repeat(3_000_000)).is_none(), "over the byte cap");
let odd = Lexicon::from_cmudict("WORD\n\n \nX \u{0}\u{0}\n").expect("parses");
assert!(odd.is_empty());
}
+1
View File
@@ -9,6 +9,7 @@ fn fixture(lang: Lang) -> Vec<(String, String)> {
Lang::En => include_str!("fixtures/lemma_en.tsv"), Lang::En => include_str!("fixtures/lemma_en.tsv"),
Lang::De => include_str!("fixtures/lemma_de.tsv"), Lang::De => include_str!("fixtures/lemma_de.tsv"),
Lang::La => include_str!("fixtures/lemma_la.tsv"), Lang::La => include_str!("fixtures/lemma_la.tsv"),
Lang::Cs => "",
}; };
text.lines() text.lines()
.map(|l| l.trim_end_matches('\r')) .map(|l| l.trim_end_matches('\r'))
+63
View File
@@ -1,6 +1,7 @@
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere. //! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, HabitGoal, Mark, Outcome, Person, WordMark}; use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, HabitGoal, Mark, Outcome, Person, WordMark};
use crate::together::RecordingSource;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::cmp::Ordering; use std::cmp::Ordering;
@@ -192,4 +193,66 @@ pub enum Op {
sha256: String, sha256: String,
language: Option<String>, language: Option<String>,
}, },
/// Day 5: someone the reader reads with: `person` is their Tabellarius group (hex), `name` how Liber shows them.
/// Adding again renames.
PersonAdd {
person: String,
name: String,
},
PersonRemove {
person: String,
},
/// Day 5: hide (or show again) a person's notes, in one book or everywhere (`book: None`).
Hide {
person: String,
book: Option<String>,
hidden: bool,
},
/// Day 5: a highlight was shared with a person (the note itself travels in their group).
Share {
highlight: String,
person: String,
},
Unshare {
highlight: String,
person: String,
},
/// Day 5: a buddy read of a book with people.
BuddyRead {
id: String,
book: String,
people: Vec<String>,
},
/// Day 5: a link was made asking someone (`person`: the name the parent typed) to record a chapter. `key` opens
/// what is in the slot; it lives only here (the reader's own, end-to-end encrypted log) and in the link.
RecordAsk {
slot: String,
book: String,
chapter: u32,
person: String,
key: String,
created: u64,
},
/// Day 5: the link was cancelled (or the recording arrived and the parent closed it).
RecordAskClose {
slot: String,
},
/// Day 5: a recorded chapter, waiting for the parent's approval.
RecordingAdd {
id: String,
book: String,
chapter: u32,
by: String,
source: RecordingSource,
mime: String,
duration_ms: u64,
created: u64,
},
RecordingApprove {
id: String,
},
/// Day 5: deleted by the parent, or found deleted by the person who recorded it. Final.
RecordingRemove {
id: String,
},
} }
+40
View File
@@ -206,6 +206,46 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
for (lang, band) in &lib.bands { for (lang, band) in &lib.bands {
ops.push(Op::KnownBand { lang: lang.clone(), list: band.list.clone(), upto: band.upto }); ops.push(Op::KnownBand { lang: lang.clone(), list: band.list.clone(), upto: band.upto });
} }
// Day 5: people, what was shared and hidden, buddy reads, links and recordings (deleted ones are simply absent).
for (person, p) in &lib.people {
ops.push(Op::PersonAdd { person: person.clone(), name: p.name.clone() });
}
for (person, book) in &lib.hides {
ops.push(Op::Hide { person: person.clone(), book: book.clone(), hidden: true });
}
for (highlight, people) in &lib.shares {
for person in people {
ops.push(Op::Share { highlight: highlight.clone(), person: person.clone() });
}
}
for r in lib.buddy_reads.values() {
ops.push(Op::BuddyRead { id: r.id.clone(), book: r.book.clone(), people: r.people.clone() });
}
for a in lib.asks.values() {
ops.push(Op::RecordAsk {
slot: a.slot.clone(),
book: a.book.clone(),
chapter: a.chapter,
person: a.person.clone(),
key: a.key.clone(),
created: a.created,
});
}
for r in lib.recordings.values() {
ops.push(Op::RecordingAdd {
id: r.id.clone(),
book: r.book.clone(),
chapter: r.chapter,
by: r.by.clone(),
source: r.source.clone(),
mime: r.mime.clone(),
duration_ms: r.duration_ms,
created: r.created,
});
if r.approved {
ops.push(Op::RecordingApprove { id: r.id.clone() });
}
}
ops ops
} }
+1
View File
@@ -10,6 +10,7 @@ pub mod export;
pub mod import; pub mod import;
pub mod library; pub mod library;
pub mod stats; pub mod stats;
pub mod together;
pub use event::{Clock, Event, Hlc, Op}; pub use event::{Clock, Event, Hlc, Op};
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text}; pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
+183
View File
@@ -357,6 +357,42 @@ pub struct Goal {
pub target: u32, pub target: u32,
} }
/// Day 5: someone the reader reads with.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersonEntry {
pub name: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuddyRead {
pub id: String,
pub book: String,
pub people: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RecordAsk {
pub slot: String,
pub book: String,
pub chapter: u32,
pub person: String,
pub key: String,
pub created: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recording {
pub id: String,
pub book: String,
pub chapter: u32,
pub by: String,
pub source: crate::together::RecordingSource,
pub mime: String,
pub duration_ms: u64,
pub created: u64,
pub approved: bool,
}
/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content /// The whole library. Equal events in any arrival order give an equal library. Equality compares the content
/// (books, highlights, sessions, goals), not the bookkeeping of how it was built. /// (books, highlights, sessions, goals), not the bookkeeping of how it was built.
#[derive(Clone, Debug, Default, Serialize, Deserialize)] #[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -377,6 +413,27 @@ pub struct Library {
/// Day 3: language → the frequency band marked as known. /// Day 3: language → the frequency band marked as known.
#[serde(default)] #[serde(default)]
pub bands: BTreeMap<String, Band>, pub bands: BTreeMap<String, Band>,
/// Day 5: the people the reader reads with, by group.
#[serde(default)]
pub people: BTreeMap<String, PersonEntry>,
/// Day 5: (person, book) pairs whose notes are hidden; `None` for every book.
#[serde(default)]
pub hides: BTreeSet<(String, Option<String>)>,
/// Day 5: highlight -> the people it was shared with.
#[serde(default)]
pub shares: BTreeMap<String, BTreeSet<String>>,
#[serde(default)]
pub buddy_reads: BTreeMap<String, BuddyRead>,
/// Day 5: open "Ask someone to record" links, by slot.
#[serde(default)]
pub asks: BTreeMap<String, RecordAsk>,
/// Day 5: recorded chapters, approved or waiting.
#[serde(default)]
pub recordings: BTreeMap<String, Recording>,
#[serde(skip)]
removed_recordings: BTreeSet<String>,
#[serde(skip)]
approved_early: BTreeSet<String>,
#[serde(skip)] #[serde(skip)]
aliases: BTreeMap<String, String>, aliases: BTreeMap<String, String>,
#[serde(skip)] #[serde(skip)]
@@ -401,6 +458,12 @@ impl PartialEq for Library {
&& self.medals_seen == o.medals_seen && self.medals_seen == o.medals_seen
&& self.words == o.words && self.words == o.words
&& self.bands == o.bands && self.bands == o.bands
&& self.people == o.people
&& self.hides == o.hides
&& self.shares == o.shares
&& self.buddy_reads == o.buddy_reads
&& self.asks == o.asks
&& self.recordings == o.recordings
} }
} }
@@ -452,6 +515,28 @@ impl Library {
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str) self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
} }
/// Day 5: whether a person's notes are hidden in this book (or everywhere).
pub fn hidden(&self, person: &str, book: &str) -> bool {
let book = self.canonical(book);
self.hides.contains(&(person.to_owned(), None)) || self.hides.contains(&(person.to_owned(), Some(book)))
}
/// Day 5: the approved recordings of a chapter: the only ones that may be played.
pub fn playable(&self, book: &str, chapter: u32) -> Vec<&Recording> {
let book = self.canonical(book);
self.recordings.values().filter(|r| r.approved && r.book == book && r.chapter == chapter).collect()
}
/// Day 5: recordings waiting for the parent's approval.
pub fn pending(&self) -> Vec<&Recording> {
self.recordings.values().filter(|r| !r.approved).collect()
}
/// Day 5: recordings deleted (their audio must go from every device).
pub fn removed_recordings(&self) -> &BTreeSet<String> {
&self.removed_recordings
}
/// An existing book with the same identity: ISBN-13, else text fingerprint. /// An existing book with the same identity: ISBN-13, else text fingerprint.
pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> { pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> {
if let Some(i) = isbn13 if let Some(i) = isbn13
@@ -786,6 +871,104 @@ impl Library {
b.audio_position = Some((sha256.to_ascii_lowercase(), *ms)); b.audio_position = Some((sha256.to_ascii_lowercase(), *ms));
} }
} }
Op::PersonAdd { person, name } => {
if crate::together::id_ok(person) && crate::together::name_ok(name) {
self.people.insert(person.clone(), PersonEntry { name: name.trim().to_owned() });
}
}
Op::PersonRemove { person } => {
self.people.remove(person);
}
Op::Hide { person, book, hidden } => {
let key = (person.clone(), book.as_deref().map(|b| self.canonical(b)));
if *hidden {
self.hides.insert(key);
} else {
self.hides.remove(&key);
}
}
Op::Share { highlight, person } => {
self.shares.entry(highlight.clone()).or_default().insert(person.clone());
}
Op::Unshare { highlight, person } => {
if let Some(s) = self.shares.get_mut(highlight) {
s.remove(person);
if s.is_empty() {
self.shares.remove(highlight);
}
}
}
Op::BuddyRead { id, book, people } => {
let book = self.canonical(book);
if crate::together::id_ok(id) && self.books.contains_key(&book) && people.len() <= 16 {
self.buddy_reads.insert(id.clone(), BuddyRead { id: id.clone(), book, people: people.clone() });
}
}
Op::RecordAsk { slot, book, chapter, person, key, created } => {
let book = self.canonical(book);
if crate::together::slot_ok(slot)
&& crate::together::key_ok(key)
&& crate::together::name_ok(person)
&& self.books.contains_key(&book)
{
let a = RecordAsk {
slot: slot.clone(),
book,
chapter: *chapter,
person: person.trim().to_owned(),
key: key.clone(),
created: *created,
};
self.asks.insert(slot.clone(), a);
}
}
Op::RecordAskClose { slot } => {
self.asks.remove(slot);
}
Op::RecordingAdd { id, book, chapter, by, source, mime, duration_ms, created } => {
let book = self.canonical(book);
if self.removed_recordings.contains(id)
|| self.recordings.contains_key(id)
|| !crate::together::id_ok(id)
|| !crate::together::name_ok(by)
|| !crate::together::mime_ok(mime)
|| !source.ok()
|| !self.books.contains_key(&book)
{
return;
}
let approved = self.approved_early.remove(id);
self.recordings.insert(
id.clone(),
Recording {
id: id.clone(),
book,
chapter: *chapter,
by: by.trim().to_owned(),
source: source.clone(),
mime: mime.clone(),
duration_ms: *duration_ms,
created: *created,
approved,
},
);
}
Op::RecordingApprove { id } => {
if self.removed_recordings.contains(id) {
return;
}
match self.recordings.get_mut(id) {
Some(r) => r.approved = true,
None => {
self.approved_early.insert(id.clone());
}
}
}
Op::RecordingRemove { id } => {
self.recordings.remove(id);
self.approved_early.remove(id);
self.removed_recordings.insert(id.clone());
}
Op::Edition { book, sha256, language } => { Op::Edition { book, sha256, language } => {
let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit()); let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
if let Some(b) = self.book_mut(book) if let Some(b) = self.book_mut(book)
+342
View File
@@ -0,0 +1,342 @@
//! Day 5 (the app's `docs/05_together.md`): reading together. What one person's Liber sends another (strictly
//! parsed: the other side is as hostile as any outside file), where a shared note lands in the reader's copy, and the
//! spoiler guard. Recordings and the reader's own decisions are ops in the library (`Op::RecordingAdd` …).
use crate::library::{Book, BookInfo, Colour, Mark, ReadStatus};
use liber_format::Document;
use liber_format::position::{Anchor, Resolved, resolve};
use serde::{Deserialize, Serialize};
/// The most a body from another person may be, in bytes (Tabellarius allows 300 KiB a message).
pub const MAX_BODY: usize = 64 * 1024;
/// A shared note's text, in characters.
pub const MAX_NOTE: usize = 10_000;
/// The quoted text a note is anchored to, in characters.
pub const MAX_QUOTE: usize = 2_000;
/// A thread message, in characters.
pub const MAX_MESSAGE: usize = 4_000;
/// A name a person chose, in characters.
pub const MAX_NAME: usize = 80;
pub const MAX_TITLE: usize = 300;
/// Which book a shared item is about: enough to find the reader's own copy, nothing about the sender's files.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BookRef {
pub isbn13: Option<String>,
pub fingerprint: Option<String>,
pub title: String,
}
impl BookRef {
pub fn of(info: &BookInfo) -> BookRef {
BookRef { isbn13: info.isbn13.clone(), fingerprint: info.fingerprint.clone(), title: info.title.clone() }
}
/// The same book (not just the same title): ISBN-13 or text fingerprint equal.
pub fn is(&self, info: &BookInfo) -> bool {
let eq =
|a: &Option<String>, b: &Option<String>| matches!((a, b), (Some(x), Some(y)) if !x.is_empty() && x == y);
eq(&self.isbn13, &info.isbn13) || eq(&self.fingerprint, &info.fingerprint)
}
fn ok(&self) -> bool {
self.isbn13.as_deref().is_none_or(|i| i.len() == 13 && i.bytes().all(|b| b.is_ascii_digit()))
&& self.fingerprint.as_deref().is_none_or(|f| !f.is_empty() && f.len() <= 128 && f.is_ascii())
&& chars_in(&self.title, 1, MAX_TITLE)
}
}
/// Where in the sender's copy an item belongs: the chapter and the progress through the book (0–1).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Spot {
pub chapter: u32,
pub progress: f64,
}
impl Spot {
fn ok(&self) -> bool {
self.chapter <= 100_000 && self.progress.is_finite() && (0.0..=1.0).contains(&self.progress)
}
}
/// A highlight or note shared with a person.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SharedNote {
/// The sender's highlight id.
pub id: String,
pub book: BookRef,
pub anchor: Anchor,
pub spot: Spot,
pub kind: Mark,
pub colour: Colour,
pub note: String,
pub created: u64,
}
impl SharedNote {
fn ok(&self) -> bool {
let a = &self.anchor;
id_ok(&self.id)
&& self.book.ok()
&& self.spot.ok()
&& a.chapter <= 100_000
&& a.start.len() <= 1024
&& a.end.len() <= 1024
&& a.chapter_hash.len() <= 128
&& chars_in(&a.quote.exact, 1, MAX_QUOTE)
&& a.quote.prefix.chars().count() <= 200
&& a.quote.suffix.chars().count() <= 200
&& self.note.chars().count() <= MAX_NOTE
&& self.kind != Mark::Bookmark
}
}
/// Everything that travels in a person's group (Tabellarius app events). Each kind has its own body.
#[derive(Clone, Debug, PartialEq)]
pub enum Wire {
/// `liber.hello`: the name the person chose.
Hello { name: String },
/// `liber.note`
Note(Box<SharedNote>),
/// `liber.note.withdraw`: the sender took a note back.
Withdraw { id: String },
/// `liber.buddy`: an invitation to read a book together.
Buddy { read: String, book: BookRef },
/// `liber.progress`: how far the person is in a buddy read.
Progress { read: String, spot: Spot },
/// `liber.thread`: a message in a chapter's thread.
Thread { read: String, id: String, spot: Spot, text: String },
}
pub const HELLO: &str = "liber.hello";
pub const NOTE: &str = "liber.note";
pub const WITHDRAW: &str = "liber.note.withdraw";
pub const BUDDY: &str = "liber.buddy";
pub const PROGRESS: &str = "liber.progress";
pub const THREAD: &str = "liber.thread";
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct HelloB {
name: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct WithdrawB {
id: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct BuddyB {
read: String,
book: BookRef,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct ProgressB {
read: String,
spot: Spot,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct ThreadB {
read: String,
id: String,
spot: Spot,
text: String,
}
impl Wire {
/// `None` for anything not exactly a Day 5 body: an unknown kind or field, a value out of its bounds.
pub fn parse(kind: &str, body: &[u8]) -> Option<Wire> {
if body.len() > MAX_BODY {
return None;
}
let w = match kind {
HELLO => {
let b: HelloB = serde_json::from_slice(body).ok()?;
Wire::Hello { name: b.name.trim().to_owned() }
}
NOTE => Wire::Note(Box::new(serde_json::from_slice(body).ok()?)),
WITHDRAW => Wire::Withdraw { id: serde_json::from_slice::<WithdrawB>(body).ok()?.id },
BUDDY => {
let b: BuddyB = serde_json::from_slice(body).ok()?;
Wire::Buddy { read: b.read, book: b.book }
}
PROGRESS => {
let b: ProgressB = serde_json::from_slice(body).ok()?;
Wire::Progress { read: b.read, spot: b.spot }
}
THREAD => {
let b: ThreadB = serde_json::from_slice(body).ok()?;
Wire::Thread { read: b.read, id: b.id, spot: b.spot, text: b.text }
}
_ => return None,
};
w.ok().then_some(w)
}
fn ok(&self) -> bool {
match self {
Wire::Hello { name } => name_ok(name),
Wire::Note(n) => n.ok(),
Wire::Withdraw { id } => id_ok(id),
Wire::Buddy { read, book } => id_ok(read) && book.ok(),
Wire::Progress { read, spot } => id_ok(read) && spot.ok(),
Wire::Thread { read, id, spot, text } => {
id_ok(read) && id_ok(id) && spot.ok() && chars_in(text.trim(), 1, MAX_MESSAGE)
}
}
}
/// `(kind, body)` to send.
pub fn encode(&self) -> (&'static str, Vec<u8>) {
let j = |v: serde_json::Result<Vec<u8>>| v.unwrap_or_default();
match self {
Wire::Hello { name } => (HELLO, j(serde_json::to_vec(&HelloB { name: name.clone() }))),
Wire::Note(n) => (NOTE, j(serde_json::to_vec(n.as_ref()))),
Wire::Withdraw { id } => (WITHDRAW, j(serde_json::to_vec(&WithdrawB { id: id.clone() }))),
Wire::Buddy { read, book } => {
(BUDDY, j(serde_json::to_vec(&BuddyB { read: read.clone(), book: book.clone() })))
}
Wire::Progress { read, spot } => {
(PROGRESS, j(serde_json::to_vec(&ProgressB { read: read.clone(), spot: *spot })))
}
Wire::Thread { read, id, spot, text } => (
THREAD,
j(serde_json::to_vec(&ThreadB { read: read.clone(), id: id.clone(), spot: *spot, text: text.clone() })),
),
}
}
}
fn chars_in(s: &str, min: usize, max: usize) -> bool {
let n = s.chars().count();
n >= min && n <= max
}
/// An id another device made: 1–64 letters, digits, `-` or `_`.
pub fn id_ok(s: &str) -> bool {
!s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// A name someone chose: 1–80 characters, no control characters.
pub fn name_ok(s: &str) -> bool {
chars_in(s.trim(), 1, MAX_NAME) && !s.chars().any(char::is_control)
}
/// Where a shared note lands in the reader's copy. Offsets are UTF-16 into the chapter's text.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Placement {
Exact {
chapter: usize,
start: usize,
end: usize,
},
/// "Position approximate": found by its quoted text (another edition, or the text moved).
Approximate {
chapter: usize,
start: usize,
end: usize,
},
/// Not in this copy: shown in the side list with its quote, never at a guessed place.
Lost,
}
impl Placement {
pub fn chapter(&self) -> Option<usize> {
match self {
Placement::Exact { chapter, .. } | Placement::Approximate { chapter, .. } => Some(*chapter),
Placement::Lost => None,
}
}
}
/// The note's anchor in `doc`, the reader's copy of the book `mine`. Only the same book (ISBN-13 or fingerprint)
/// can be exact; any other edition is at best approximate.
pub fn place(doc: &Document, mine: &BookInfo, note: &SharedNote) -> Placement {
let same = note.book.is(mine);
match resolve(doc, &note.anchor) {
Resolved::Exact { chapter, start, end } if same => Placement::Exact { chapter, start, end },
Resolved::Exact { chapter, start, end } | Resolved::Approximate { chapter, start, end } => {
Placement::Approximate { chapter, start, end }
}
Resolved::Lost => Placement::Lost,
}
}
/// How far the reader has got in a book: the furthest position on any device, or the end once it is read.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Reach {
pub chapter: u32,
pub progress: f64,
}
impl Reach {
pub fn of(book: &Book) -> Reach {
if book.status() == ReadStatus::Read
|| book.reads.iter().any(|r| r.outcome == Some(crate::library::Outcome::Read))
{
return Reach { chapter: u32::MAX, progress: 1.0 };
}
match &book.position {
Some(p) => Reach { chapter: p.chapter, progress: p.progress },
None => Reach { chapter: 0, progress: 0.0 },
}
}
}
/// The spoiler guard: whether a note or message stays folded. `placed`: the chapter it landed in in the reader's copy
/// (`None` for the side list and for thread messages); `same`: the same book as the sender's. The chapter being read
/// is open; anything beyond the furthest chapter is folded.
pub fn folded(spot: &Spot, placed: Option<usize>, same: bool, reach: &Reach) -> bool {
if reach.chapter == u32::MAX {
return false;
}
match placed {
Some(ch) => ch as u64 > reach.chapter as u64,
None if same => spot.chapter > reach.chapter,
None => spot.progress > reach.progress,
}
}
/// Where a recording's audio is.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RecordingSource {
/// A slot on the home server: the sealed audio (`sha256` of the blob as it was found, so an approval holds for
/// exactly that take), opened with `key` (base64url, 32 bytes).
Slot { slot: String, key: String, sha256: String },
/// Only on the device that recorded it, sealed in its store.
Local { sha256: String },
}
impl RecordingSource {
pub(crate) fn ok(&self) -> bool {
let hex = |s: &str| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit());
match self {
RecordingSource::Slot { slot, key, sha256 } => slot_ok(slot) && key_ok(key) && hex(sha256),
RecordingSource::Local { sha256 } => hex(sha256),
}
}
}
/// A slot id: 22 base64url characters (128 bits).
pub fn slot_ok(s: &str) -> bool {
s.len() == 22 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// A link key: 43 base64url characters (32 bytes).
pub fn key_ok(s: &str) -> bool {
s.len() == 43 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
/// The audio types a recording may have (the browser's recorder: Opus in WebM or Ogg; Safari: AAC in MP4).
pub fn mime_ok(m: &str) -> bool {
let base = m.split(';').next().unwrap_or("").trim();
matches!(base, "audio/webm" | "audio/ogg" | "audio/mp4") && m.len() <= 64 && m.is_ascii()
}
+353
View File
@@ -0,0 +1,353 @@
//! Day 5 (the app's `docs/05_together.md`): reading together. Mandatory tests 2 (matching), 3 (spoiler guard) and
//! 4 (approval, the core's half), and the strict parsing of what another person's Liber sends.
use liber_format::{Document, Limits};
use liber_library::library::{BookInfo, Colour, Mark};
use liber_library::together::{
self, BookRef, Placement, Reach, RecordingSource, SharedNote, Spot, Wire, folded, place,
};
use liber_library::{Clock, Event, Library, Op};
fn fb2(title: &str, chapters: &[(&str, &[&str])]) -> Document {
let mut body = String::new();
for (t, paras) in chapters {
body.push_str(&format!("<section><title><p>{t}</p></title>"));
for p in *paras {
body.push_str(&format!("<p>{p}</p>"));
}
body.push_str("</section>");
}
let x = format!(
r#"<?xml version="1.0" encoding="utf-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0"><description><title-info><book-title>{title}</book-title><lang>cs</lang></title-info></description><body>{body}</body></FictionBook>"#
);
liber_format::open(x.as_bytes(), Some("b.fb2"), &Limits::default()).expect("parses")
}
const C1: &[&str] =
&["Kapitán van Toch byl tlustý a dobrý člověk.", "Na ostrově Tana Masa žili mloci, kteří uměli házet kamením."];
const C2: &[&str] = &["Mloci se naučili mluvit a číst noviny.", "Pan Bondy založil Salamander Syndicate."];
const C3: &[&str] = &["Válka s mloky začala tiše.", "Nakonec zbyl jen spisovatel a jeho svědomí."];
/// The same book as the sender has.
fn edition_a() -> Document {
fb2("Válka s mloky", &[("I", C1), ("II", C2), ("III", C3)])
}
/// Another edition: a foreword before the story, and a sentence changed in chapter II.
fn edition_b() -> Document {
const FOREWORD: &[&str] = &["Předmluva vydavatele k tomuto vydání."];
const C2B: &[&str] = &["Mloci se naučili mluvit a číst noviny.", "Pan G. H. Bondy založil syndikát."];
fb2("Válka s mloky", &[("Předmluva", FOREWORD), ("I", C1), ("II", C2B), ("III", C3)])
}
fn chapter_of(d: &Document, needle: &str) -> usize {
d.chapters.iter().position(|c| c.root.text().contains(needle)).expect(needle)
}
fn note_on(d: &Document, quote: &str, book: BookRef) -> SharedNote {
let ch = chapter_of(d, quote);
let text = d.chapters[ch].root.text();
let at = text.find(quote).unwrap();
let s = text[..at].encode_utf16().count();
let e = s + quote.encode_utf16().count();
let anchor = liber_format::position::anchor(d, ch, s, e).expect("anchor");
SharedNote {
id: "n-1".into(),
book,
anchor,
spot: Spot { chapter: ch as u32, progress: ch as f64 / d.chapters.len() as f64 },
kind: Mark::Note,
colour: Colour::Green,
note: "Tohle si pamatuj.".into(),
created: 1,
}
}
fn info(isbn: Option<&str>, fp: Option<&str>) -> BookInfo {
BookInfo {
title: "Válka s mloky".into(),
isbn13: isbn.map(str::to_owned),
fingerprint: fp.map(str::to_owned),
..BookInfo::default()
}
}
fn reff(isbn: Option<&str>, fp: Option<&str>) -> BookRef {
BookRef { isbn13: isbn.map(str::to_owned), fingerprint: fp.map(str::to_owned), title: "Válka s mloky".into() }
}
// ---------- 2. matching ----------
#[test]
fn a_note_lands_exactly_in_the_same_edition() {
let a = edition_a();
let n = note_on(&a, "uměli házet kamením", reff(Some("9788020712479"), None));
let want = chapter_of(&a, "uměli házet");
match place(&a, &info(Some("9788020712479"), None), &n) {
Placement::Exact { chapter, start, end } => {
assert_eq!(chapter, want);
let t: Vec<u16> = a.chapters[chapter].root.text().encode_utf16().collect();
assert_eq!(String::from_utf16_lossy(&t[start..end]), "uměli házet kamením");
}
p => panic!("{p:?}"),
}
// The fingerprint identifies the book too.
assert!(matches!(
place(&a, &info(None, Some("fp")), &note_on(&a, "tlustý", reff(None, Some("fp")))),
Placement::Exact { .. }
));
}
#[test]
fn in_another_edition_the_note_is_approximate_and_at_the_right_words() {
let (a, b) = (edition_a(), edition_b());
let n = note_on(&a, "uměli házet kamením", reff(Some("9788020712479"), None));
match place(&b, &info(Some("9788000000000"), Some("other")), &n) {
Placement::Approximate { chapter, start, end } => {
assert_eq!(chapter, chapter_of(&b, "uměli házet"), "chapter I is the second chapter there");
let t: Vec<u16> = b.chapters[chapter].root.text().encode_utf16().collect();
assert_eq!(String::from_utf16_lossy(&t[start..end]), "uměli házet kamením");
}
p => panic!("{p:?}"),
}
// Even where the positions happen to point at the same words, another edition is never "exact".
let n = note_on(&a, "Kapitán van Toch", reff(None, Some("fp-a")));
assert!(matches!(place(&a, &info(None, Some("fp-b")), &n), Placement::Approximate { .. }));
}
#[test]
fn a_note_on_text_that_is_not_there_goes_to_the_side_list() {
let (a, b) = (edition_a(), edition_b());
// "Salamander Syndicate" was rewritten in edition B.
let n = note_on(&a, "založil Salamander Syndicate", reff(None, Some("fp-a")));
assert_eq!(place(&b, &info(None, Some("fp-b")), &n), Placement::Lost);
// Two equally good places in the reader's copy (the same sentence twice, neither with the note's context): never
// a guess.
let twice = fb2("x", &[("I", &["A. Mloci mluví dál. B. Mloci mluví dál. C."])]);
let mut n = note_on(&twice, "Mloci mluví dál.", reff(None, Some("fp-t")));
n.anchor.start = "epubcfi(/6/99!/4/2/1:0)".into();
n.anchor.quote.prefix = "X. ".into();
n.anchor.quote.suffix = " Y.".into();
assert_eq!(place(&twice, &info(None, Some("fp-other")), &n), Placement::Lost);
}
// ---------- 3. spoiler guard ----------
fn ev(id: &str, c: &mut Clock, t: u64, op: Op) -> Event {
Event { id: id.into(), hlc: c.tick(t), device: "phone".into(), op }
}
fn position(chapter: u32, progress: f64) -> Op {
Op::Position {
book: "b1".into(),
cfi: format!("epubcfi(/6/{}!/4/2/1:0)", 2 * chapter + 2),
chapter,
progress,
label: None,
}
}
#[test]
fn notes_beyond_the_furthest_chapter_stay_folded_across_chapters_and_after_reopening() {
let mut c = Clock::default();
let mut evs =
vec![ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false })];
evs.push(ev("e1", &mut c, 2, position(1, 0.30)));
let lib = Library::from_events(&evs);
let reach = Reach::of(&lib.books["b1"]);
let at = |ch: u32, p: f64| Spot { chapter: ch, progress: p };
// Placed notes: by the chapter they landed in, in the reader's copy.
assert!(!folded(&at(0, 0.1), Some(0), true, &reach));
assert!(!folded(&at(1, 0.4), Some(1), true, &reach), "the chapter being read is open");
assert!(folded(&at(2, 0.6), Some(2), true, &reach));
// A note placed in a later chapter of the reader's edition stays folded even if the sender's chapter was earlier.
assert!(folded(&at(1, 0.2), Some(3), false, &reach));
// Not placed (side list) or a thread message: the same book → by chapter; another edition → by progress.
assert!(folded(&at(2, 0.1), None, true, &reach));
assert!(!folded(&at(5, 0.25), None, false, &reach));
assert!(folded(&at(0, 0.31), None, false, &reach));
// Reading on into chapter II opens its notes; going back does not fold them again (the furthest place counts).
evs.push(ev("e2", &mut c, 3, position(2, 0.55)));
evs.push(ev("e3", &mut c, 4, position(0, 0.05)));
// Re-opening: the library is rebuilt from its events, in another arrival order.
evs.reverse();
let lib = Library::from_events(&evs);
let reach = Reach::of(&lib.books["b1"]);
assert!(!folded(&at(2, 0.6), Some(2), true, &reach));
assert!(folded(&at(3, 0.8), Some(3), true, &reach));
// A finished book has no spoilers left.
evs.push(ev(
"e4",
&mut c,
5,
Op::ReadStart { read: "r1".into(), book: "b1".into(), date: Some("2026-11-01".into()) },
));
evs.push(ev(
"e5",
&mut c,
6,
Op::ReadEnd {
read: "r1".into(),
date: Some("2026-11-20".into()),
outcome: liber_library::library::Outcome::Read,
},
));
let lib = Library::from_events(&evs);
assert!(!folded(&at(3, 0.99), Some(3), true, &Reach::of(&lib.books["b1"])));
}
// ---------- 4. approval (the core's half) ----------
fn rec(id: &str) -> Op {
Op::RecordingAdd {
id: id.into(),
book: "b1".into(),
chapter: 2,
by: "Babička".into(),
source: RecordingSource::Slot {
slot: "AAAAAAAAAAAAAAAAAAAAAA".into(),
key: "k".repeat(43),
sha256: "a".repeat(64),
},
mime: "audio/webm;codecs=opus".into(),
duration_ms: 600_000,
created: 10,
}
}
#[test]
fn an_unapproved_recording_is_never_playable_and_a_removed_one_stays_gone() {
let mut c = Clock::default();
let mut evs = vec![
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
ev("e1", &mut c, 2, rec("r1")),
];
let lib = Library::from_events(&evs);
assert_eq!(lib.recordings.len(), 1, "the parent sees it, waiting");
assert!(!lib.recordings["r1"].approved);
assert!(lib.playable("b1", 2).is_empty());
assert!(lib.pending().iter().any(|r| r.id == "r1"));
evs.push(ev("e2", &mut c, 3, Op::RecordingApprove { id: "r1".into() }));
let lib = Library::from_events(&evs);
assert_eq!(lib.playable("b1", 2).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["r1"]);
assert!(lib.playable("b1", 1).is_empty(), "only for its chapter");
assert!(lib.pending().is_empty());
// Deleted on one device: gone on every device that folds the log, and an old add arriving late does not bring it
// back, nor does a late approval.
evs.push(ev("e3", &mut c, 4, Op::RecordingRemove { id: "r1".into() }));
let mut late = Clock::default();
evs.push(ev("e4", &mut late, 2, rec("r1")));
evs.push(ev("e5", &mut c, 5, Op::RecordingApprove { id: "r1".into() }));
let lib = Library::from_events(&evs);
assert!(lib.recordings.is_empty());
assert!(lib.playable("b1", 2).is_empty());
assert!(lib.removed_recordings().contains("r1"));
}
#[test]
fn hostile_recording_and_ask_values_are_dropped() {
let mut c = Clock::default();
let mut bad = rec("r1");
if let Op::RecordingAdd { mime, .. } = &mut bad {
*mime = "text/html".into();
}
let mut no_book = rec("r2");
if let Op::RecordingAdd { book, .. } = &mut no_book {
*book = "missing".into();
}
let evs = vec![
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
ev("e1", &mut c, 2, bad),
ev("e2", &mut c, 3, no_book),
ev(
"e3",
&mut c,
4,
Op::RecordAsk {
slot: "short".into(),
book: "b1".into(),
chapter: 1,
person: "Babička".into(),
key: "k".repeat(43),
created: 1,
},
),
];
let lib = Library::from_events(&evs);
assert!(lib.recordings.is_empty());
assert!(lib.asks.is_empty());
}
// ---------- people, sharing, hiding ----------
#[test]
fn people_shares_and_hiding_fold_like_everything_else() {
let mut c = Clock::default();
let mut evs = vec![
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
ev("e1", &mut c, 2, Op::PersonAdd { person: "g1".into(), name: "Jana".into() }),
ev("e2", &mut c, 3, Op::Share { highlight: "h1".into(), person: "g1".into() }),
ev("e3", &mut c, 4, Op::Hide { person: "g1".into(), book: Some("b1".into()), hidden: true }),
ev("e4", &mut c, 5, Op::BuddyRead { id: "br1".into(), book: "b1".into(), people: vec!["g1".into()] }),
];
let lib = Library::from_events(&evs);
assert_eq!(lib.people["g1"].name, "Jana");
assert!(lib.shares["h1"].contains("g1"));
assert!(lib.hidden("g1", "b1"));
assert!(!lib.hidden("g1", "b2"));
assert_eq!(lib.buddy_reads["br1"].people, ["g1"]);
evs.push(ev("e5", &mut c, 6, Op::Hide { person: "g1".into(), book: None, hidden: true }));
evs.push(ev("e6", &mut c, 7, Op::Unshare { highlight: "h1".into(), person: "g1".into() }));
let lib = Library::from_events(&evs);
assert!(lib.hidden("g1", "b2"), "hidden everywhere");
assert!(lib.shares.get("h1").is_none_or(|s| s.is_empty()));
// An export restores all of it (with a recording, approved).
evs.push(ev("e8", &mut c, 9, rec("r1")));
evs.push(ev("e9", &mut c, 10, Op::RecordingApprove { id: "r1".into() }));
let lib = Library::from_events(&evs);
let mut rc = Clock::default();
let restored: Vec<Event> = liber_library::export::ops_from(&lib)
.into_iter()
.enumerate()
.map(|(i, op)| ev(&format!("x{i}"), &mut rc, i as u64 + 1, op))
.collect();
assert_eq!(Library::from_events(&restored), lib);
evs.push(ev("e7", &mut c, 8, Op::PersonRemove { person: "g1".into() }));
let lib = Library::from_events(&evs);
assert!(lib.people.is_empty());
}
// ---------- what another person's Liber sends ----------
#[test]
fn wire_bodies_are_parsed_strictly() {
let a = edition_a();
let n = note_on(&a, "tlustý a dobrý", reff(None, Some("fp")));
let body = serde_json::to_vec(&n).unwrap();
assert_eq!(Wire::parse("liber.note", &body), Some(Wire::Note(Box::new(n.clone()))));
assert_eq!(Wire::parse("liber.hello", br#"{"name":"Jana"}"#), Some(Wire::Hello { name: "Jana".into() }));
// Unknown kinds and fields, oversized values, bad numbers: refused.
assert_eq!(Wire::parse("liber.unknown", b"{}"), None);
assert_eq!(Wire::parse("liber.hello", br#"{"name":"Jana","admin":true}"#), None);
assert_eq!(Wire::parse("liber.hello", br#"{"name":""}"#), None);
let long = format!(r#"{{"name":"{}"}}"#, "x".repeat(81));
assert_eq!(Wire::parse("liber.hello", long.as_bytes()), None);
let mut big = n.clone();
big.note = "x".repeat(together::MAX_NOTE + 1);
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&big).unwrap()), None);
let mut nan = n.clone();
nan.spot.progress = 2.0;
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&nan).unwrap()), None);
let mut quote = n;
quote.anchor.quote.exact = String::new();
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&quote).unwrap()), None);
let t = br#"{"read":"br1","id":"m1","spot":{"chapter":2,"progress":0.5},"text":"Ten konec!"}"#;
assert!(matches!(Wire::parse("liber.thread", t), Some(Wire::Thread { .. })));
assert_eq!(Wire::parse("liber.thread", &[0xff, 0xfe]), None);
assert_eq!(Wire::parse("liber.thread", &vec![b' '; together::MAX_BODY + 1]), None);
}