-
Notifications
You must be signed in to change notification settings - Fork 164
/
package.cpp
2027 lines (1789 loc) · 65 KB
/
package.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// package.cpp
// ePub3
//
// Created by Jim Dovey on 2012-11-28.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "container.h"
#include "package.h"
#include "archive.h"
#include "archive_xml.h"
#include "xpath_wrangler.h"
#include "nav_table.h"
#include "glossary.h"
#include "iri.h"
#include "basic.h"
#include "byte_stream.h"
#include "filter_chain.h"
#include "filter_manager.h"
#include "media-overlays_smil_model.h"
#include <ePub3/utilities/error_handler.h>
#include <sstream>
#include <list>
#include REGEX_INCLUDE
#include <ePub3/xml/document.h>
#include <ePub3/xml/element.h>
//#include "iri.h"
#include <google-url/url_canon.h>
#include <google-url/url_util.h>
EPUB3_BEGIN_NAMESPACE
#define _XML_OVERRIDE_SWITCHES (EPUB_USE(LIBXML2) && PROMISCUOUS_LIBXML_OVERRIDES == 0)
#if _XML_OVERRIDE_SWITCHES
extern "C" {
extern void __resetLibXMLOverrides(void);
extern void __setupLibXML(void);
}
#endif
void PrintNodeSet(xml::NodeSet& nodeSet)
{
for (decltype(nodeSet.size()) i = 0; i < nodeSet.size(); i++)
{
auto node = nodeSet[i];
fprintf(stderr, "Node %02lu: ", i);
if ( !bool(node) )
{
fprintf(stderr, "[nullptr]");
}
else
{
fprintf(stderr, "%s", node->XMLString().utf8());
}
fprintf(stderr, "\n");
}
}
#if EPUB_COMPILER_SUPPORTS(CXX_USER_LITERALS)
static const xmlChar * OPFNamespace = "http://www.idpf.org/2007/opf"_xml;
static const xmlChar * DCNamespace = "http://purl.org/dc/elements/1.1/"_xml;
static const xmlChar * MediaTypeElementName = "mediaType"_xml;
#else
static const xmlChar * OPFNamespace = (const xmlChar*)"http://www.idpf.org/2007/opf";
static const xmlChar * DCNamespace = (const xmlChar*)"http://purl.org/dc/elements/1.1/";
static const xmlChar * MediaTypeElementName = (const xmlChar*)"mediaType";
#endif
bool Package::gValidateSchema = true;
PackageBase::PackageBase(const shared_ptr<Container>& owner, const string& type) : _archive(owner->GetArchive()), _opf(nullptr), _type(type)
{
if ( !_archive )
throw std::invalid_argument("Owner doesn't have an archive!");
}
PackageBase::PackageBase(PackageBase&& o) : _archive(o._archive), _opf(std::move(o._opf)), _pathBase(std::move(o._pathBase)), _type(std::move(o._type)), _manifestByID(std::move(o._manifestByID)), _manifestByAbsolutePath(std::move(o._manifestByAbsolutePath)), _spine(std::move(o._spine))
{
o._archive = nullptr;
}
PackageBase::~PackageBase()
{
// our Container owns the archive
}
bool PackageBase::Open(const string& path, bool skipLoadingPotentiallyEncryptedContent)
{
ArchiveXmlReader reader(_archive->ReaderAtPath(path.stl_str()));
#if ENABLE_XML_READ_DOC_MEMORY
_opf = reader.readXml(path);
#else
#if EPUB_USE(LIBXML2)
_opf = reader.xmlReadDocument(path.c_str(), nullptr);
#elif EPUB_USE(WIN_XML)
_opf = reader.ReadDocument(path.c_str(), nullptr, 0);
#endif
#endif //ENABLE_XML_READ_DOC_MEMORY
if ( !bool(_opf) )
{
HandleError(EPUBError::OCFInvalidRootfileURL, _Str(__PRETTY_FUNCTION__, ": No OPF file at ", path.stl_str()));
return false;
}
size_t loc = path.rfind("/");
if ( loc == std::string::npos )
{
_pathBase = '/';
}
else
{
_pathBase = path.substr(0, loc+1);
}
return true;
}
shared_ptr<SpineItem> PackageBase::SpineItemAt(size_t idx) const
{
shared_ptr<SpineItem> item = _spine;
for ( size_t i = 0; i < idx && item != nullptr; i++ )
{
item = item->Next();
}
return item;
}
size_t PackageBase::IndexOfSpineItemWithIDRef(const string &idref) const
{
shared_ptr<SpineItem> item = FirstSpineItem();
for ( size_t i = 0; item != nullptr; i++, item = item->Next() )
{
if ( item->Idref() == idref )
return i;
}
return size_t(-1);
}
shared_ptr<ManifestItem> PackageBase::ManifestItemWithID(const string &ident) const
{
auto found = _manifestByID.find(ident);
if ( found == _manifestByID.end() )
return nullptr;
return found->second;
}
string PackageBase::CFISubpathForManifestItemWithID(const string &ident) const
{
size_t sz = IndexOfSpineItemWithIDRef(ident);
if ( sz == size_t(-1) )
throw std::invalid_argument(_Str("Identifier '", ident, "' was not found in the spine."));
return _Str(_spineCFIIndex, "/", (sz+1)*2, "[", ident, "]!");
}
const shared_vector<ManifestItem> PackageBase::ManifestItemsWithProperties(PropertyIRIList properties) const
{
shared_vector<ManifestItem> result;
for ( auto& item : _manifestByID )
{
if ( item.second->HasProperty(properties) )
result.push_back(item.second);
}
return result;
}
shared_ptr<ManifestItem> PackageBase::ManifestItemAtRelativePath(const string& path) const
{
string absPath = _pathBase + (path[0] == '/' ? path.substr(1) : path);
auto found = _manifestByAbsolutePath.find(absPath);
if (found != _manifestByAbsolutePath.end()) {
return found->second;
}
// Edge case...
// before giving up, let's check for lower/upper-case percent encoding mismatch (e.g. %2B vs. %2b)
// (well, we're normalising to un-escaped paths)
//if ( path.find("%") != std::string::npos ) SOMETIMES OPF MANIFEST ITEM HREF IS PERCENT-ESCAPED, BUT NOT HTML SRC !!
url_canon::RawCanonOutputW<256> output;
// SEE BELOW FOR A DEBUGGING BREAKPOINT / CHECK
// note that std::string .size() is the same as
// ePub3:string .utf8_size() defined in utfstring.h (equivalent to strlen(str.c_str()) ),
// but not the same as ePub3:string .size() !!
// WATCH OUT!
url_util::DecodeURLEscapeSequences(path.c_str(), static_cast<int>(path.utf8_size()), &output);
string path_(output.data(), output.length());
string absPath_ = _pathBase + (path_[0] == '/' ? path_.substr(1) : path_);
for (auto& item : _manifestByID)
{
string absolute = item.second->AbsolutePath();
url_canon::RawCanonOutputW<256> output_;
// THIS IS FOR DEBUGGING, SEE COMMENT BELOW ...
const char * absChars = absolute.c_str();
int absLength_STRLEN = (int)strlen(absChars);
int absLength_SIZE = static_cast<int>(absolute.size());
int absLength_UTF8SIZE = static_cast<int>(absolute.utf8_size());
if (absLength_STRLEN != absLength_SIZE || absLength_STRLEN != absLength_UTF8SIZE || absLength_SIZE != absLength_UTF8SIZE)
{
// Place breakpoint here
//printf("String length DIFF absLength_STRLEN:%d - absLength_SIZE:%d - absLength_UTF8SIZE:%d\n", absLength_STRLEN, absLength_SIZE, absLength_UTF8SIZE);
}
// note that std::string .size() is the same as
// ePub3:string .utf8_size() defined in utfstring.h (equivalent to strlen(str.c_str()) ),
// but not the same as ePub3:string .size() !!
// WATCH OUT!
url_util::DecodeURLEscapeSequences(absolute.c_str(), static_cast<int>(absolute.utf8_size()), &output_);
string absolute_(output_.data(), output_.length());
if (absolute_ == absPath_)
return item.second;
}
// DEBUG
//printf("MISSING ManifestItemAtRelativePath %s (%s)\n", path.c_str(), absPath.c_str());
return nullptr;
}
shared_ptr<NavigationTable> PackageBase::NavigationTable(const string &title) const
{
auto found = _navigation.find(title);
if ( found == _navigation.end() )
return nullptr;
return found->second;
}
shared_ptr<Collection> PackageBase::CollectionWithRole(string_view role) const
{
auto found = _collections.find(role);
if (found == _collections.end())
return nullptr;
return found->second;
}
unique_ptr<ByteStream> PackageBase::ReadStreamForItemAtPath(const string &path) const
{
return _archive->ByteStreamAtPath(path.stl_str());
}
shared_ptr<SpineItem> PackageBase::ConfirmOrCorrectSpineItemQualifier(shared_ptr<SpineItem> pItem, CFI::Component *pComponent) const
{
if ( pComponent->HasQualifier() && pItem->Idref() != pComponent->qualifier )
{
// find the item with the qualifier
pItem = _spine;
uint32_t idx = 2;
while ( pItem != nullptr )
{
if ( pItem->Idref() == pComponent->qualifier )
{
// found it-- correct the CFI
pComponent->nodeIndex = idx;
break;
}
pItem = pItem->Next();
}
}
else if ( pComponent->HasQualifier() == false )
{
HandleError(EPUBError::CFINonAssertedXMLID);
}
return pItem;
}
NavigationList PackageBase::NavTablesFromManifestItem(shared_ptr<PackageBase> owner, ManifestItemPtr pItem)
{
// have to do this one manually, as PackageBase doesn't inherit from PointerType itself
PackagePtr sharedPkg = std::dynamic_pointer_cast<Package>(owner);
if ( !sharedPkg )
return NavigationList();
if ( pItem == nullptr )
return NavigationList();
auto doc = pItem->ReferencedDocument();
if ( !bool(doc) )
return NavigationList();
NavigationList navList;
if (pItem->MediaType() != NCXContentType)
navList = _LoadEPUB3NavTablesFromManifestItem(sharedPkg, pItem, doc);
else
navList = _LoadNCXNavTablesFromManifestItem(sharedPkg, pItem, doc);
if (navList.empty() && pItem->Href().rfind(".ncx") == pItem->Href().size()-4)
navList = _LoadNCXNavTablesFromManifestItem(sharedPkg, pItem, doc);
return navList;
}
NavigationList PackageBase::_LoadEPUB3NavTablesFromManifestItem(PackagePtr sharedPkg, ManifestItemPtr pItem, shared_ptr<xml::Document> doc)
{
// find each <nav> node
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
XPathWrangler xpath(doc, {{"epub", ePub3NamespaceURI}, {"html", XHTMLNamespaceURI}}); // goddamn I love C++11 initializer list constructors
#else
XPathWrangler::NamespaceList __m;
__m["epub"] = ePub3NamespaceURI;
XPathWrangler xpath(doc, __m);
#endif
xpath.NameDefaultNamespace("html");
xml::NodeSet nodes = xpath.Nodes("//html:nav");
NavigationList tables;
for (auto navNode : nodes)
{
auto navTablePtr = std::make_shared<ePub3::NavigationTable>(sharedPkg, pItem->Href()); //NavigationTable::New(sharedPkg, pItem->Href());
if (navTablePtr->ParseXML(navNode))
tables.push_back(navTablePtr);
}
// now look for any <dl> nodes with an epub:type of "glossary"
nodes = xpath.Nodes("//html:dl[epub:type='glossary']");
for (auto node : nodes)
{
auto glosPtr = std::make_shared<Glossary>(node, sharedPkg); //Glossary::New(node, sharedPkg);
tables.push_back(glosPtr);
}
return tables;
}
NavigationList PackageBase::_LoadNCXNavTablesFromManifestItem(PackagePtr sharedPkg, ManifestItemPtr pItem, shared_ptr<xml::Document> doc)
{
// find each <nav> node
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
XPathWrangler xpath(doc, { { "ncx", NCXNamespaceURI} }); // goddamn I love C++11 initializer list constructors
#else
XPathWrangler::NamespaceList __m;
__m["ncx"] = NCXNamespaceURI;
XPathWrangler xpath(doc, __m);
#endif
xpath.NameDefaultNamespace("ncx");
auto titles = xpath.Strings("/ncx:ncx/ncx:docTitle/ncx:text/text()");
string title;
if (!titles.empty())
title = titles[0];
auto nodes = xpath.Nodes("/ncx:ncx/ncx:navMap");
NavigationList tables;
if (!nodes.empty())
{
auto navTablePtr = std::make_shared<ePub3::NavigationTable>(sharedPkg, pItem->Href()); //NavigationTable::New(sharedPkg, pItem->Href());
if (navTablePtr->ParseNCXNavMap(nodes[0], title))
tables.push_back(navTablePtr);
}
// now look for any <pageList> nodes
nodes = xpath.Nodes("/ncx:ncx/ncx:pageList");
if (!nodes.empty())
{
auto navTablePtr = std::make_shared<ePub3::NavigationTable>(sharedPkg, pItem->Href()); //NavigationTable::New(sharedPkg, pItem->Href());
if (navTablePtr->ParseNCXPageList(nodes[0]))
tables.push_back(navTablePtr);
}
// now any <navList> nodes
nodes = xpath.Nodes("/ncx:ncx/ncx:navList");
for (auto node : nodes)
{
auto navTablePtr = std::make_shared<ePub3::NavigationTable>(sharedPkg, pItem->Href()); //NavigationTable::New(sharedPkg, pItem->Href());
if (navTablePtr->ParseNCXNavList(node))
tables.push_back(navTablePtr);
}
return tables;
}
#if 0
#pragma mark - Package High-Level API
#endif
Package::Package(const shared_ptr<Container>& owner, const string& type) : PropertyHolder(), OwnedBy(owner), PackageBase(owner, type)
{
}
bool Package::Open(const string& path, bool skipLoadingPotentiallyEncryptedContent)
{
#if _XML_OVERRIDE_SWITCHES
__setupLibXML();
#endif
auto status = PackageBase::Open(path);
if (status) {
// Setup the content filter chain before unpacking the package
// to filter its manifest items if needed. For example with
// some encrypted EPUB the navigation tables must be decrypted
// before being parsed.
auto fm = FilterManager::Instance();
auto fc = fm->BuildFilterChainForPackage(shared_from_this());
SetFilterChain(fc);
status = Unpack(skipLoadingPotentiallyEncryptedContent);
}
if (status)
{
ConstContainerPtr container = Owner();
//ConstContainerPtr sharedContainer = std::dynamic_pointer_cast<Container>(owner);
// See ReadiumJS package_document_parser.js updateMetadataWithIBookProperties()
// https://github.com/readium/readium-js/blob/develop/epub-modules/epub/src/models/package_document_parser.js#L91
// (vendor metadata takes precedence over OPF, to match rendering expectations with some commercial EPUBs that do not necessarily contains correct OPF metadata)
string fxl = container->GetVendorMetadata_AppleIBooksDisplayOption_FixedLayout();
if (fxl == "true")
{
this->RegisterPrefixIRIStem("rendition", "http://www.idpf.org/vocab/rendition/#");
this->RemoveProperty("layout", "rendition");
PropertyHolderPtr holderPtr = CastPtr<PropertyHolder>();
PropertyPtr prop = std::make_shared<Property>(holderPtr); //Property::New(holderPtr);
prop->SetPropertyIdentifier(MakePropertyIRI("layout", "rendition"));
prop->SetValue("pre-paginated");
AddProperty(prop);
}
string orientation = container->GetVendorMetadata_AppleIBooksDisplayOption_Orientation();
bool landscape = orientation == "landscape-only";
bool portrait = !landscape && orientation == "portrait-only";
bool none = !landscape && !portrait && orientation == "none";
if (landscape || portrait || none)
{
this->RegisterPrefixIRIStem("rendition", "http://www.idpf.org/vocab/rendition/#");
this->RemoveProperty("orientation", "rendition");
PropertyHolderPtr holderPtr = CastPtr<PropertyHolder>();
PropertyPtr prop = std::make_shared<Property>(holderPtr); //Property::New(holderPtr);
prop->SetPropertyIdentifier(MakePropertyIRI("orientation", "rendition"));
string val = landscape?"landscape":(portrait?"portrait":"auto");
prop->SetValue(val);
AddProperty(prop);
}
}
#if _XML_OVERRIDE_SWITCHES
__resetLibXMLOverrides();
#endif
return status;
}
bool Package::_OpenForTest(shared_ptr<xml::Document> doc, const string& basePath)
{
#if _XML_OVERRIDE_SWITCHES
__setupLibXML();
#endif
_opf = doc;
_pathBase = basePath;
auto status = Unpack();
#if _XML_OVERRIDE_SWITCHES
__resetLibXMLOverrides();
#endif
return status;
}
unique_ptr<ArchiveReader> Package::ReaderForRelativePath(const string& path) const
{
return _archive->ReaderAtPath((_pathBase + path).stl_str());
}
void Package::Unpack_Finally(bool resetContentFilterChain)
{
if (resetContentFilterChain) {
auto fm = FilterManager::Instance();
auto fc = fm->BuildFilterChainForPackage(shared_from_this());
SetFilterChain(fc);
}
this->LoadNavigationTables();
// go through the TOC and copy titles to the relevant spine items for easy access
this->CompileSpineItemTitles();
this->LoadMediaOverlays();
}
void Package::LoadMediaOverlays() {
PackagePtr sharedMe = shared_from_this();
//std::weak_ptr<Package> weakSharedMe = sharedMe; // Not needed: smart shared pointer passed as reference, then onto OwnedBy() which maintains its own weak pointer
_mediaOverlays = std::make_shared<class MediaOverlaysSmilModel>(sharedMe);
_mediaOverlays->Initialize();
}
void Package::LoadNavigationTables()
{
if (!_navigation.empty()) // && !_navigation["toc"]->Children().empty()
{
return;
}
auto root = _opf->Root();
string rootName(root->Name());
rootName.tolower();
bool isEPUB3 = true;
string versionStr;
int version = 0;
if ( rootName != "package" )
{
HandleError(EPUBError::OPFInvalidPackageDocument);
return;
}
versionStr = _getProp(root, "version");
if ( versionStr.empty() )
{
HandleError(EPUBError::OPFPackageHasNoVersion);
}
else
{
// GNU libstdc++ seems to not want to let us use these C++11 routines...
#ifndef _LIBCPP_VERSION
version = (int)strtol(versionStr.c_str(), nullptr, 10);
#else
version = std::stoi(versionStr.stl_str());
#endif
if (version < 3)
isEPUB3 = false;
}
PackagePtr sharedMe = shared_from_this();
// now the navigation tables
if (isEPUB3)
{
// look for EPUB3 navigation document(s)
for ( auto item : _manifestByID )
{
if ( !item.second->HasProperty(ItemProperties::Navigation) )
continue;
NavigationList tables = NavTablesFromManifestItem(sharedMe, item.second);
for ( auto& table : tables )
{
// have to dynamic_cast these guys to get the right pointer type
NavigationTablePtr navTable = NavigationTable::CastFrom<NavigationElement>(table);
#if EPUB_HAVE(CXX_MAP_EMPLACE)
_navigation.emplace(navTable->Type(), navTable);
#else
_navigation[navTable->Type()] = navTable;
#endif
}
}
}
if (_navigation.empty() || _navigation["toc"]->Children().empty())
{
// look for EPUB2 NCX file
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
XPathWrangler xpath(_opf, { { "opf", OPFNamespace } });
#else
XPathWrangler::NamespaceList __m;
__m["opf"] = OPFNamespace;
XPathWrangler xpath(_opf, __m);
#endif
auto tocNames = xpath.Strings("/opf:package/opf:spine/@toc");
if (tocNames.empty() && _navigation.empty())
{
// no NCX, and no other nav document
// otherwise, we had a valid EPUB3 nav with empty (one-level) TOC
HandleError(EPUBError::OPFNoNavDocument);
}
else
{
if (!tocNames.empty()) {
try
{
ManifestItemPtr tocItem = ManifestItemWithID(tocNames[0]);
if (!bool(tocItem))
throw EPUBError::OPFNoNavDocument;
NavigationList tables = NavTablesFromManifestItem(sharedMe, tocItem);
for (auto& table : tables)
{
// have to dynamic_cast these guys to get the right pointer type
NavigationTablePtr navTable = NavigationTable::CastFrom<NavigationElement>(table);
#if EPUB_HAVE(CXX_MAP_EMPLACE)
_navigation.emplace(navTable->Type(), navTable);
#else
_navigation[navTable->Type()] = navTable;
#endif
}
}
catch (std::exception& exc)
{
std::cerr << "Exception locating or processing NCX navigation document: " << exc.what() << std::endl;
throw;
}
catch (EPUBError errCode)
{
// a 'break'-style mechanism here
// the error handler will determine if it's safe to continue
HandleError(errCode);
}
catch (...)
{
HandleError(EPUBError::OPFNoNavDocument);
}
}
}
}
}
bool Package::Unpack(bool skipLoadingPotentiallyEncryptedContent)
{
PackagePtr sharedMe = shared_from_this();
// very basic sanity check
auto root = _opf->Root();
string rootName(root->Name());
rootName.tolower();
bool isEPUB3 = true;
string versionStr;
int version = 0;
if ( rootName != "package" )
{
HandleError(EPUBError::OPFInvalidPackageDocument);
return false; // not an OPF file, innit?
}
versionStr = _getProp(root, "version");
if ( versionStr.empty() )
{
HandleError(EPUBError::OPFPackageHasNoVersion);
}
else
{
// GNU libstdc++ seems to not want to let us use these C++11 routines...
#ifndef _LIBCPP_VERSION
version = (int)strtol(versionStr.c_str(), nullptr, 10);
#else
version = std::stoi(versionStr.stl_str());
#endif
if (version < 3)
isEPUB3 = false;
}
auto val = _getProp(root, "prefix", ePub3NamespaceURI);
InstallPrefixesFromAttributeValue(val);
// go through children to determine the CFI index of the <spine> tag
static xml::string kSpineName((const char*)"spine");
static xml::string kManifestName((const char*)"manifest");
static xml::string kMetadataName((const char*)"metadata");
_spineCFIIndex = 0;
uint32_t idx = 0;
auto child = root->FirstElementChild();
while ( bool(child) )
{
idx += 2;
if ( child->Name() == kSpineName )
{
_spineCFIIndex = idx;
if ( _spineCFIIndex != 6 )
HandleError(EPUBError::OPFSpineOutOfOrder);
}
else if ( child->Name() == kManifestName && idx != 4 )
{
HandleError(EPUBError::OPFManifestOutOfOrder);
}
else if ( child->Name() == kMetadataName && idx != 2 )
{
HandleError(EPUBError::OPFMetadataOutOfOrder);
}
child = child->NextElementSibling();
}
if ( _spineCFIIndex == 0 )
{
HandleError(EPUBError::OPFNoSpine);
return false; // spineless!
}
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
XPathWrangler xpath(_opf, {{"opf", OPFNamespace}, {"dc", DCNamespace}});
#else
XPathWrangler::NamespaceList __m;
__m["opf"] = OPFNamespace;
__m["dc"] = DCNamespace;
XPathWrangler xpath(_opf, __m);
#endif
// simple things: manifest and spine items
xml::NodeSet manifestNodes;
xml::NodeSet spineNodes;
try
{
manifestNodes = xpath.Nodes("/opf:package/opf:manifest/opf:item");
spineNodes = xpath.Nodes("/opf:package/opf:spine/opf:itemref");
if ( manifestNodes.empty() )
{
HandleError(EPUBError::OPFNoManifestItems);
}
if ( spineNodes.empty() )
{
HandleError(EPUBError::OPFNoSpineItems);
}
for ( auto node : manifestNodes )
{
auto p = std::make_shared<ManifestItem>(sharedMe); //ManifestItem::New(sharedMe);
if ( p->ParseXML(node) )
{
#if EPUB_HAVE(CXX_MAP_EMPLACE)
_manifestByID.emplace(p->Identifier(), p);
_manifestByAbsolutePath.emplace(p->AbsolutePath(), p);
#else
_manifestByID[p->Identifier()] = p;
_manifestByAbsolutePath[p->AbsolutePath()] = p;
#endif
StoreXMLIdentifiable(p);
}
else
{
// TODO: Need an error here
}
}
// check fallback chains
typedef std::map<string, bool> IdentSet;
IdentSet idents;
for ( auto &pair : _manifestByID )
{
ManifestItemPtr item = pair.second;
if ( item->FallbackID().empty() )
continue;
idents[item->XMLIdentifier()] = true;
while ( item != nullptr && !item->FallbackID().empty() )
{
if ( idents[item->FallbackID()] )
{
HandleError(EPUBError::OPFFallbackChainCircularReference);
break;
}
item = item->Fallback();
}
idents.clear();
}
SpineItemPtr cur;
for ( auto node : spineNodes )
{
auto next = std::make_shared<SpineItem>(sharedMe); //SpineItem::New(sharedMe);
if ( next->ParseXML(node) == false )
{
// TODO: need an error code here
continue;
}
// validation of idref
auto manifestFound = _manifestByID.find(next->Idref());
if ( manifestFound == _manifestByID.end() )
{
HandleError(EPUBError::OPFInvalidSpineIdref, _Str(next->Idref(), " does not correspond to a manifest item"));
continue;
}
// validation of spine resource type w/fallbacks
ManifestItemPtr manifestItem = next->ManifestItem();
bool isContentDoc = false;
do
{
if ( manifestItem->MediaType() == "application/xhtml+xml" ||
manifestItem->MediaType() == "image/svg" )
{
isContentDoc = true;
break;
}
} while ( (manifestItem = manifestItem->Fallback()) );
if ( !isContentDoc )
HandleError(EPUBError::OPFFallbackChainHasNoContentDocument);
StoreXMLIdentifiable(next);
if ( cur != nullptr )
{
cur->SetNextItem(next);
}
else
{
_spine = next;
}
cur = next;
}
}
catch (const std::system_error& exc)
{
if ( exc.code().category() == epub_spec_category() )
throw;
return false;
}
catch (...)
{
return false;
}
manifestNodes.clear();
spineNodes.clear();
// collections
xml::NodeSet collectionNodes;
try
{
PropertyHolderPtr holderPtr = CastPtr<PropertyHolder>();
collectionNodes = xpath.Nodes("/opf:package/opf:collection");
for (auto& node : collectionNodes)
{
CollectionPtr collection = std::make_shared<Collection>(shared_from_this(), nullptr); //Collection::New(Ptr(), nullptr);
if (collection->ParseXML(node))
{
#if EPUB_HAVE(CXX_MAP_EMPLACE)
_collections.emplace(collection->Role(), collection);
#else
_collections[collection->Role()] = collection;
#endif
}
}
}
catch (const std::system_error& exc)
{
if (exc.code().category() == epub_spec_category())
throw;
return false;
}
catch (...)
{
return false;
}
// now the metadata, which is slightly more involved due to extensions
xml::NodeSet metadataNodes;
xml::NodeSet refineNodes;
try
{
PropertyHolderPtr holderPtr = CastPtr<PropertyHolder>();
metadataNodes = xpath.Nodes("/opf:package/opf:metadata/*");
if ( metadataNodes.empty() )
HandleError(EPUBError::OPFNoMetadata);
bool foundIdentifier = false, foundTitle = false, foundLanguage = false, foundModDate = false;
string uniqueIDRef = _getProp(root, "unique-identifier");
if ( uniqueIDRef.empty() )
HandleError(EPUBError::OPFPackageUniqueIDInvalid);
std::vector<string> uidRefIds = std::vector<string>();
for ( auto node : metadataNodes )
{
PropertyPtr p;
auto ns = node->Namespace();
if ( bool(ns) && ns->URI() == xml::string(DCNamespace) )
{
// definitely a main node
p = std::make_shared<Property>(holderPtr); //Property::New(holderPtr);
}
else if ( _getProp(node, "name").size() > 0 )
{
// It's an EPUB 2 property, we save them to allow
// backward compatiblity by host apps.
string name = _getProp(node, "name");
string content = _getProp(node, "content");
#if EPUB_HAVE(CXX_MAP_EMPLACE)
_EPUB2Properties.emplace(name, content);
#else
_EPUB2Properties[name] = content;
#endif
// it's an ePub2 item-- ignore it
continue;
}
else if ( _getProp(node, "refines").empty() )
{
// not refining anything, so it's a main node
p = std::make_shared<Property>(holderPtr); //Property::New(holderPtr);
}
else
{
// by elimination it's refining something-- we'll process it later when we know we've got all the main nodes in there
refineNodes.push_back(node);
}
if ( p && p->ParseMetaElement(node) )
{
switch ( p->Type() )
{
case DCType::Identifier:
{
foundIdentifier = true;
uidRefIds.push_back(p->XMLIdentifier());
break;
}
case DCType::Title:
{
foundTitle = true;
break;
}
case DCType::Language:
{
foundLanguage = true;
break;
}
case DCType::Custom:
{
if ( p->PropertyIdentifier() == MakePropertyIRI("modified", "dcterms") )
foundModDate = true;
break;
}
default:
break;
}
AddProperty(p);
StoreXMLIdentifiable(p);
}
}
if ( foundIdentifier && !uniqueIDRef.empty() )
{
bool found = false;
for (int i = 0; i < uidRefIds.size(); i++)
{
const string id = uidRefIds[i];
if ( uniqueIDRef == id )
{
found = true;
break;
}
}
if (!found)
{
HandleError(EPUBError::OPFPackageUniqueIDInvalid);
}
}
if ( !foundIdentifier )
HandleError(EPUBError::OPFMissingIdentifierMetadata);
if ( !foundTitle )
HandleError(EPUBError::OPFMissingTitleMetadata);
if ( !foundLanguage )
HandleError(EPUBError::OPFMissingLanguageMetadata);
if ( !foundModDate && isEPUB3 )
HandleError(EPUBError::OPFMissingModificationDateMetadata);