forked from vss-devel/zimmer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzimmer.js
executable file
·1645 lines (1433 loc) · 52.2 KB
/
zimmer.js
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
#!/bin/sh
":" //# -*- mode: js -*-; exec /usr/bin/env TMPDIR=/tmp node --max-old-space-size=2000 --stack-size=42000 "$0" "$@"
"use strict";
/*
MIT License
Copyright (c) 2016 Vadim Shlyakhov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const packageInfo = require('./package.json');
const os = require( 'os' )
const osPath = require( 'path' )
const osProcess = require( 'process' )
const url = require( 'url' )
const crypto = require( "crypto" )
const command = require('commander')
const fs = require( 'fs-extra' )
const expandHomeDir = require( 'expand-home-dir' )
const lzma = require( 'lzma-native' )
const cheerio = require('cheerio')
const uuidv4 = require( "uuid/v4" )
const csvParse = require( 'csv-parse' )
const csvParseSync = require( 'csv-parse/lib/sync' )
const zlib = require( 'mz/zlib' )
const sqlite = require( 'sqlite' )
const sharp = require( 'sharp' )
const genericPool = require( 'generic-pool' )
const mozjpeg = require( 'mozjpeg' )
const childProcess = require('child_process')
const isAnimated = require('animated-gif-detector')
const mimeDb = require( 'mime-db' )
const mimeTypes = require( 'mime-types' )
const mmmagic = require( 'mmmagic' )
const mimeMagic = new mmmagic.Magic( mmmagic.MAGIC_MIME_TYPE )
const moment = require("moment")
require("moment-duration-format")
const startTime = Date.now()
const cpuCount = os.cpus().length
var srcPath
var outPath
var out // output file writer
var wikiDb
var dirQueue
var clusterWriter
let preProcessed = false
var mainPage = {}
// - layout, eg. the LayoutPage, CSS, favicon.png (48x48), JavaScript and images not related to the articles
// A articles - see Article Format
// B article meta data - see Article Format
// I images, files - see Image Handling
// J images, text - see Image Handling
// M ZIM metadata - see Metadata
// U categories, text - see Category Handling
// V categories, article list - see Category Handling
// W categories per article, category list - see Category Handling
// X fulltext index - see ZIM Index Format
var headerLength = 80
var header = {
magicNumber: 72173914, // integer 0 4 Magic number to recognise the file format, must be 72173914
// version integer 4 4 ZIM=5, bytes 1-2: major, bytes 3-4: minor version of the ZIM file format
versionMajor: 5,
versionMinor: 0,
uuid: uuidv4( {}, Buffer.alloc( 16 )), // integer 8 16 unique id of this zim file
articleCount: 0, // integer 24 4 total number of articles
clusterCount: 0, // integer 28 4 total number of clusters
urlPtrPos: null, // integer 32 8 position of the directory pointerlist ordered by URL
titlePtrPos: null, // integer 40 8 position of the directory pointerlist ordered by Title
clusterPtrPos: null, // integer 48 8 position of the cluster pointer list
mimeListPos: headerLength, // integer 56 8 position of the MIME type list (also header size)
mainPage: 0xffffffff, // integer 64 4 main page or 0xffffffff if no main page
layoutPage: 0xffffffff, // integer 68 4 layout page or 0xffffffffff if no layout page
checksumPos: null, // integer 72 8 pointer to the md5checksum of this file without the checksum itself. This points always 16 bytes before the end of the file.
//~ geoIndexPos: null, // integer 80 8 pointer to the geo index (optional). Present if mimeListPos is at least 80.
}
function fullPath ( path ) {
return osPath.join( srcPath, path )
}
function mimeFromPath ( path ) {
var mType = mimeTypes.lookup( path )
if ( mType == null ) {
console.error( 'No mime type found', path )
}
return mType
}
function mimeFromData ( data ) {
return new Promise(( resolve, reject ) =>
mimeMagic.detect( data, ( error, mimeType ) => {
if ( error )
return reject( error )
return resolve( mimeType )
})
)
}
var REDIRECT_MIME = '@REDIRECT@'
var LINKTARGET_MIME = '@LINKTARGET@'
var DELETEDENTRY_MIME = '@DELETEDENTRY@'
var mimeTypeList = []
var maxMimeLength = 512
function mimeFromIndex ( idx ) {
return mimeTypeList[ idx ]
}
function mimeTypeIndex ( mimeType ) {
if ( mimeType == null ) {
console.trace( 'No mime type found', mimeType )
osProcess.exit( 1 )
}
if ( mimeType == REDIRECT_MIME )
return 0xffff
if ( mimeType == LINKTARGET_MIME )
return 0xfffe
if ( mimeType == DELETEDENTRY_MIME )
return 0xfffd
let idx = mimeTypeList.indexOf( mimeType )
if ( idx == -1 ) {
idx = mimeTypeList.length
mimeTypeList.push( mimeType )
}
return idx
}
function getNameSpace ( mimeType ) {
if ( command.uniqueNamespace )
return 'A'
if ( !mimeType )
return null
if ( mimeType == 'text/html' )
return 'A'
else if ( mimeType.split( '/' )[ 0 ] == 'image' )
return 'I'
return '-'
}
function elapsedStr( from , to = Date.now()) {
return moment.duration( to - from ).format('d[d]hh:mm:ss.SSS',{ stopTrim: "h" })
}
function log ( ...args ) {
console.log( elapsedStr( startTime ), ... args )
}
function warning ( ...args ) {
log( ...args )
}
function fatal ( ...args ) {
console.trace( elapsedStr( startTime ), ... args )
osProcess.exit( 1 )
}
function mimeFromData ( data ) {
return new Promise(( resolve, reject ) =>
mimeMagic.detect( data, ( error, mimeType ) => {
if ( error )
return reject( error )
return resolve( mimeType )
})
)
}
function writeUIntLE( buf, value, offset, byteLength ) {
if ( byteLength == 8 ) {
value = BigInt( value )
var low = value & 0xffffffffn
var high = ( value - low ) / 0x100000000n
buf.writeUInt32LE( Number( low ), offset )
buf.writeUInt32LE( Number( high ), offset + 4 )
return offset + byteLength
} else {
return buf.writeUIntLE( Number( value ), offset, byteLength )
}
}
function toBuffer( value, byteLength ) {
const buf = Buffer.allocUnsafe( byteLength )
writeUIntLE( buf, value, 0, byteLength )
return buf
}
function chunksToBuffer( list ) {
const chunks = []
for ( const item of list ) {
let buf
if ( Array.isArray( item )) {
buf = toBuffer( ...item )
} else {
buf = Buffer.from( item )
}
chunks.push( buf )
}
return Buffer.concat( chunks )
}
async function spawn ( command, args, input ) { // after https://github.com/panosoft/spawn-promise
var child = childProcess.spawn( command, args )
// Capture errors
var errors = {}
child.on( 'error', error => errors.spawn = error )
child.stdin.on( 'error', error => errors.stdin = error )
child.stdout.on( 'error', error => errors.stdout = error )
child.stderr.setEncoding( 'utf8' )
child.stderr.on( 'error', error => errors.stderr = error )
child.stderr.on( 'data', data => {
if ( !errors.process ) errors.process = ''
errors.process += data
})
// Capture output
var buffers = []
child.stdout.on( 'data', data => buffers.push( data ))
// input
child.stdin.write( input )
child.stdin.end()
// Run
await new Promise(( resolve, reject ) => {
child.on( 'close', ( code, signal ) => {
if ( code !== 0 ) {
reject( new Error( `Command failed: ${ code } ${ JSON.stringify( errors ) }` ))
} else {
resolve()
}
})
child.stdin.end( input )
})
//~ if ( Object.keys( errors ).length !== 0 )
//~ return Promise.reject( new Error( JSON.stringify( errors )))
return Buffer.concat( buffers )
}
function cvsReader ( path, options ) {
let finished = false
const inp = fs.createReadStream( path )
const parser = csvParse( options )
parser.on( 'error', function ( err ) {
console.error( 'cvsReader ' + err.message )
throw err
})
parser.on( 'end', function () {
log( 'cvsReader end', path )
finished = true
parser.emit( 'readable' )
})
log( 'cvsReader start', path )
inp.pipe( parser )
function getRow () {
return new Promise( resolve => {
const row = parser.read()
if ( row || finished ) {
resolve( row )
} else {
parser.once( 'readable', () => resolve( getRow()))
}
})
}
return getRow
}
//
// Writer
//
class Writer {
constructor ( path ) {
this.position = BigInt( 0 )
this.stream = fs.createWriteStream( path, { highWaterMark: 1024*1024*10 })
this.stream.once( 'open', fd => { })
this.stream.on( 'error', err => {
fatal( 'Writer error', this.stream.path, err )
})
this.queue = genericPool.createPool(
{
async create () { return Symbol() },
async destroy ( resource ) { return true },
},
{}
)
}
async write ( data ) {
const token = await this.queue.acquire()
const startPosition = this.position
this.position += BigInt( data.length )
const saturated = ! this.stream.write( data )
if ( saturated ) {
this.stream.once( 'drain', () => this.queue.release( token ))
} else {
this.queue.release( token )
}
return startPosition
}
async close () {
await this.queue.drain()
return await new Promise( resolve => {
this.queue.clear()
this.stream.once( 'close', () => {
log( this.stream.path, 'closed', this.position, this.stream.bytesWritten )
resolve( this.position )
})
log( 'closing', this.stream.path )
this.stream.end()
})
}
}
//
// Cluster
//
// var ClusterSizeThreshold = 8 * 1024 * 1024
//~ var ClusterSizeThreshold = 4 * 1024 * 1024
var ClusterSizeThreshold = 1 * 1024 * 1024
// var ClusterSizeThreshold = 2 * 1024 * 1024
class Cluster {
constructor ( compressible ) {
this.id = header.clusterCount ++
this.compressible = compressible
this.blobs = []
this.size = 0
}
append ( data ) {
var id = this.id
var blobNum = this.blobs.length
if ( blobNum != 0 && this.size + data.length > ClusterSizeThreshold )
return false
this.blobs.push( data )
this.size += data.length
return blobNum
}
// Cluster
// Field Name Type Offset Length Description
// compression type integer 0 1 0: default (no compression), 1: none (inherited from Zeno), 4: LZMA2 compressed
// The following data bytes have to be uncompressed!
// <1st Blob> integer 1 4 offset to the <1st Blob>
// <2nd Blob> integer 5 4 offset to the <2nd Blob>
// <nth Blob> integer (n-1)*4+1 4 offset to the <nth Blob>
// ... integer ... 4 ...
// <last blob / end> integer n/a 4 offset to the end of the cluster
// <1st Blob> data n/a n/a data of the <1st Blob>
// <2nd Blob> data n/a n/a data of the <2nd Blob>
// ... data ... n/a ...
async getData () {
//~ log( 'Cluster.prototype.save', this.compressible, this.blobs )
// generate blob offsets
const byteLength = 4
let blobOffset = ( this.blobs.length + 1 ) * byteLength
const offsetIndex = this.blobs.map(( blob, i, arr ) => {
const val = [ blobOffset, byteLength ]
blobOffset += blob.length
return val
})
offsetIndex.push([ blobOffset, byteLength ]) // final offset
const chunks = offsetIndex.concat( this.blobs )
let data = chunksToBuffer( chunks )
if ( this.compressible ) {
// https://tukaani.org/lzma/benchmarks.html
// https://catchchallenger.first-world.info/wiki/Quick_Benchmark:_Gzip_vs_Bzip2_vs_LZMA_vs_XZ_vs_LZ4_vs_LZO
data = await lzma.compress( data, 5 ) // 3 | lzma.PRESET_EXTREME )
log( 'Cluster lzma compressed' )
}
const compression = toBuffer( this.compressible ? 4 : 0, 1 )
return Buffer.concat([ compression, data ])
}
}
//
// ClusterPool
//
class ClusterPool {
constructor () {
this.holder = {}
this.savePrefix = outPath + '.tmp'
this.pool = genericPool.createPool(
{
async create () { return Symbol() },
async destroy ( resource ) { return true },
},
{ max: 8, }
)
}
removeCluster ( type ) {
delete this.holder[ type ]
}
getCluster ( type ) {
let cluster = this.holder[ type ]
if ( ! cluster )
cluster = this.holder[ type ] = new Cluster( type )
return cluster
}
async save ( cluster ) {
const data = await cluster.getData()
const row = [ cluster.id ]
if ( ! command.zimlib4Fix ) {
const offset = await out.write( data )
row.push( offset.toString() ) // convert BigInt to String
} else { // zimlib4Fix stores clusters in separate files
await fs.outputFile( osPath.join( this.savePrefix, `${cluster.id}` ), data )
row.push( data.length ) // cluster sizes instead of offsets
}
await wikiDb.run( 'INSERT INTO clusters ( id, offset ) VALUES ( ?,? )', row )
log( 'Cluster saved', row )
}
async append ( mimeType, data, path /* for debugging */ ) {
var compressible = this.isCompressible( mimeType, data, path )
var cluster = this.getCluster( compressible )
var clusterNum = cluster.id
var blobNum = cluster.append( data )
if ( blobNum === false ) { // save current cluster, create and store into a new cluster
this.removeCluster( compressible )
const token = await this.pool.acquire()
await this.save( cluster )
this.pool.release( token )
return this.append( mimeType, data, path )
}
log( 'ClusterWriter.append', compressible, clusterNum, blobNum, data.length, path )
return [ clusterNum, blobNum ]
}
isCompressible ( mimeType, data, id ) {
if ( ! command.compress )
return false
if ( data == null || data.length == 0 )
return false
if ( !mimeType ) {
fatal( 'isCompressible !mimeType', mimeType, data, id )
}
if ( mimeType == 'image/svg+xml' || mimeType.split( '/' )[ 0 ] == 'text' )
return true
return !! ( mimeDb[ mimeType ] && mimeDb[ mimeType ].compressible )
}
// The cluster pointer list is a list of 8 byte offsets which point to all data clusters in a ZIM file.
// Field Name Type Offset Length Description
// <1st Cluster> integer 0 8 pointer to the <1st Cluster>
// <1st Cluster> integer 8 8 pointer to the <2nd Cluster>
// <nth Cluster> integer (n-1)*8 8 pointer to the <nth Cluster>
// ... integer ... 8 ...
async storeIndex () {
const byteLength = 8
const count = header.clusterCount
let rowCb = ( row, index ) => BigInt( row.offset )
if ( command.zimlib4Fix ) {
let offsetZimlib4 = await out.write( Buffer.alloc( 0 )) + BigInt( count * byteLength )
rowCb = ( row, index ) => {
const val = offsetZimlib4
offsetZimlib4 += BigInt( row.offset )
return val
}
}
header.clusterPtrPos = await saveIndex ({
query:`
SELECT
CAST( offset AS TEXT ) AS offset -- to prevent casting to JS Number
FROM clusters
ORDER BY id
;`,
byteLength,
count,
logPrefix: 'storeClusterIndex',
rowCb,
})
}
async storeClusters () {
if ( command.zimlib4Fix ) { // zimlib4Fix stores clusters in separate files
for ( let i = 0; i < header.clusterCount; i++ ) {
const fname = osPath.join( this.savePrefix, `${i}` )
const data = await fs.readFile( fname )
const pos = await out.write( data )
log( 'storeClusters', i, pos )
await fs.remove( fname )
}
await fs.remove( this.savePrefix )
}
}
async finish () {
//~ log( 'ClusterWriter.finish', ClusterWriter )
for ( let i in this.holder ) { // save last clusters
await this.save( this.holder[ i ] )
}
await this.pool.drain()
await this.pool.clear()
await this.storeIndex()
await this.storeClusters()
return
}
}
class NoProcessingRequired extends Error {
// For non-error promise rejection
}
//
// Item
//
class Item {
constructor ( params ) {
Object.assign( this, {
nameSpace: null,
path: null,
title: '',
mimeType: null,
revision: 0,
dirEntry: null,
id: null,
})
Object.assign( this, params )
}
process () {
//~ log( 'Item process', this.path )
return this.storeDirEntry()
}
urlKey () {
return this.nameSpace + this.path
}
titleKey () {
return this.nameSpace + ( this.title || this.path )
}
mimeId () {
return mimeTypeIndex( this.mimeType )
}
async getId () {
if ( ! this.id )
this.id = this.saveItemIndex()
return await this.id
}
async saveItemIndex () {
if ( ! this.path ) {
fatal( 'Item no url', this )
}
const row = [
this.urlKey(),
this.titleKey(),
this.revision,
this.mimeId(),
]
const result = await wikiDb.run(
'INSERT INTO articles ( urlKey, titleKey, revision, mimeId ) VALUES ( ?,?,?,? )',
row
)
const id = result.stmt.lastID
log( 'saveItemIndex', id, this )
return id
}
// Article Entry
// Field Name Type Offset Length Description
// mimetype integer 0 2 MIME type number as defined in the MIME type list
// parameter len byte 2 1 (not used) length of extra paramters
// namespace char 3 1 defines to which namespace this directory entry belongs
// revision integer 4 4 (optional) identifies a revision of the contents of this directory entry, needed to identify updates or revisions in the original history
// cluster number integer 8 4 cluster number in which the data of this directory entry is stored
// blob number integer 12 4 blob number inside the compressed cluster where the contents are stored
// url string 16 zero terminated string with the URL as refered in the URL pointer list
// title string n/a zero terminated string with an title as refered in the Title pointer list or empty; in case it is empty, the URL is used as title
// parameter data see parameter len (not used) extra parameters
async storeDirEntry ( clusterIdx, blobIdx, redirectTarget ) {
if ( clusterIdx == null ) {
fatal( 'storeDirEntry error: clusterIdx == null', this )
return
}
header.articleCount++
const mimeId = this.mimeId()
log( 'storeDirEntry', mimeId, this )
const chunks = [
[ mimeId, 2 ],
[ 0, 1 ], // parameters length
this.nameSpace,
[ this.revision, 4 ],
[ clusterIdx || redirectTarget || 0, 4 ], // or redirect target article index
redirectTarget == null ? [ blobIdx, 4 ] : '', // if not a redirect
this.path + '\0',
this.title + '\0',
]
this.dirEntryOffset = await out.write( chunksToBuffer( chunks ))
log( 'storeDirEntry done', this.dirEntryOffset, this.path )
return await this.saveDirEntryIndex()
}
async saveDirEntryIndex ( ) {
const id = await this.getId()
try {
log( 'saveDirEntryIndex', id, this.dirEntryOffset, this.path )
return await wikiDb.run(
'INSERT INTO dirEntries (id, offset) VALUES (?,?)',
[
id,
this.dirEntryOffset.toString(), // BigInt -> String
]
)
} catch ( err ) {
fatal( 'saveDirEntryIndex error', err, this )
}
}
}
//
// class LinkTarget
//
class LinkTarget extends Item {
constructor ( id, path, nameSpace, title ) {
super({
id,
path,
nameSpace,
title,
mimeType: LINKTARGET_MIME,
})
log( 'LinkTarget', nameSpace, path, this )
}
storeDirEntry () {
return super.storeDirEntry( 0, 0 )
}
}
//
// class DeletedEntry
//
class DeletedEntry extends Item {
constructor ( id, path, nameSpace, title ) {
super({
id,
path,
nameSpace,
title,
mimeType: DELETEDENTRY_MIME,
})
log( 'DeletedEntry', nameSpace, path, this )
}
storeDirEntry () {
return super.storeDirEntry( 0, 0 )
}
}
//
// class TargetItem
//
class TargetItem extends Item {
constructor ( params ) {
params.fragment = params.fragment === undefined ? null : params.fragment;
super( params )
}
}
//
// class Redirect
//
class Redirect extends Item {
constructor ( params ) {
// params: path, nameSpace, title, to, revision
// to: path, nameSpace, fragment
let to = params.to
delete params.to
params.mimeType = REDIRECT_MIME
super( params )
if ( typeof to == 'string' )
to = { path: to }
to.nameSpace = to.nameSpace || this.nameSpace
this.target = new TargetItem( to )
log( 'Redirect', this.nameSpace, this.path, to, this )
}
process () {
return this.saveRedirectIndex()
}
async saveRedirectIndex () {
const id = await this.getId()
return wikiDb.run(
'INSERT INTO redirects (id, targetKey, fragment) VALUES (?,?,?)',
[
id,
this.target.urlKey(),
this.target.fragment,
]
)
}
}
//
// class ResolvedRedirect
//
class ResolvedRedirect extends Item {
constructor ( id, nameSpace, path, title, target, revision ) {
super({
path,
nameSpace,
title,
mimeType: REDIRECT_MIME,
revision,
})
this.target = target
this.id = id
}
storeDirEntry () {
// Redirect Entry
// Field Name Type Offset Length Description
// mimetype integer 0 2 0xffff for redirect
// parameter len byte 2 1 (not used) length of extra paramters
// namespace char 3 1 defines which namespace this directory entry belongs to
// revision integer 4 4 (optional) identifies a revision of the contents of this directory entry, needed to identify updates or revisions in the original history
// redirect index integer 8 4 pointer to the directory entry of the redirect target
// url string 12 zero terminated string with the URL as refered in the URL pointer list
// title string n/a zero terminated string with an title as refered in the Title pointer list or empty; in case it is empty, the URL is used as title
// parameter data see parameter len (not used) extra parameters
// redirect dirEntry shorter on 4 byte field
return super.storeDirEntry( 0, 0, this.target )
}
}
//
// DataItem
//
class DataItem extends Item {
constructor ( params ) {
params.data = params.data === undefined ? null : params.data;
super( params )
}
async process () {
//~ log( 'DataItem process', this.path )
try {
await this.store()
await super.process()
} catch ( err ) {
if ( err instanceof NoProcessingRequired )
return
fatal( 'Item process error', this.path, err )
}
}
async store () {
let data = await this.getData()
if ( data == null ) {
fatal( 'DataItem.store error: data == null', this )
}
if ( !( data instanceof Buffer )) {
data = Buffer.from( data )
}
const [ clusterIdx, blobIdx ] = await clusterWriter.append( this.mimeType, data, this.path )
Object.assign( this, { clusterIdx, blobIdx })
}
async getData () {
return await this.data
}
storeDirEntry () {
return super.storeDirEntry( this.clusterIdx, this.blobIdx )
}
}
//
// class File
//
class File extends DataItem {
//~ id ,
//~ mimeId ,
//~ revision ,
//~ urlKey ,
//~ titleKey
async getData () {
if ( this.data == null ) {
this.data = fs.readFile( this.srcPath())
}
const data = await this.data
return await this.preProcess( data )
}
srcPath () {
return fullPath( this.nameSpace + '/' + this.path )
}
preProcess ( data ) {
switch ( this.mimeType ) {
case 'image/jpeg':
return this.processJpeg( data )
//~ case 'image/gif':
case 'image/png':
return this.processImage( data )
default:
return data
}
}
async processJpeg ( data ) {
if ( ! command.optimg )
return data
this.mimeType = 'image/jpeg'
try {
return await spawn(
mozjpeg,
[ '-quality', command.jpegquality, data.length < 20000 ? '-baseline' : '-progressive' ],
data
)
} catch ( err ) {
log( 'Error otimizing jpeg', err, this )
return data
}
}
async processImage ( data ) {
if ( ! command.optimg )
return data
try {
const image = sharp( data )
const metadata = await image.metadata()
if ( metadata.format == 'gif' && isAnimated( data )) {
return data
}
if ( metadata.hasAlpha && metadata.channels == 1 ) {
log( 'metadata.channels == 1', this.path )
} else if ( metadata.hasAlpha && metadata.channels > 1 ) {
if ( data.length > 20000 ) {
// Is this rather opaque?
const alpha = await image
.clone()
.extractChannel( metadata.channels - 1 )
.raw()
.toBuffer()
const opaqueAlpha = Buffer.alloc( alpha.length, 0xff )
const isOpaque = alpha.equals( opaqueAlpha )
if ( isOpaque ) { // convert to JPEG
log( 'isOpaque', this.path )
if ( metadata.format == 'gif' )
data = await image.toBuffer()
return this.processJpeg ( data )
}
}
}
if ( metadata.format == 'gif' )
return data
return await image.toBuffer() // so to catch an error
} catch ( err ) {
log( 'Error otimizing image', err, this )
return data
}
}
}
//
// class RawFile
//
class RawFile extends File {
constructor ( path ) {
const mimeType = mimeFromPath( path )
const nameSpace = getNameSpace( mimeType )
super({
path,
mimeType,
nameSpace,
})
}
srcPath () {
return fullPath( this.path )
}
async preProcess ( data ) {
if ( ! this.mimeType ) {
this.mimeType = await mimeFromData( data )
this.nameSpace = this.nameSpace || getNameSpace( this.mimeType )
}
if ( command.inflateHtml && this.mimeType == 'text/html' ) {
data = await zlib.inflate( data ) // inflateData
}
await this.preProcessHtml( data )
return super.preProcess( data )
}
async preProcessHtml ( data ) {
const dom = ( this.mimeType == 'text/html' ) && cheerio.load( data.toString())
if ( dom ) {
const title = dom( 'title' ).text()
this.title = this.title || title
const redirectTarget = this.isRedirect( dom )
if ( redirectTarget ) { // convert to redirect
const redirect = new Redirect({
path: this.path,
nameSpace: this.nameSpace,
title: this.title,
to: redirectTarget,
})
await redirect.process()
return Promise.reject( new NoProcessingRequired())
}
if ( this.alterLinks( dom ))
data = Buffer.from( dom.html())
}
return data
}
alterLinks ( dom ) {
var base = '/' + this.path
var nsBase = '/' + this.nameSpace + base
var baseSplit = nsBase.split( '/' )
var baseDepth = baseSplit.length - 1
var changes = 0
function toRelativeLink ( elem, attr ) {
try {
var link = url.parse( elem.attribs[ attr ], true, true )
} catch ( err ) {
console.warn( 'alterLinks error', err.message, elem.attribs[ attr ], 'at', base )
return
}
var path = link.pathname
if ( link.protocol || link.host || ! path )