This repository was archived by the owner on May 12, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathattachmentManagement.js
More file actions
1139 lines (1079 loc) · 36.1 KB
/
Copy pathattachmentManagement.js
File metadata and controls
1139 lines (1079 loc) · 36.1 KB
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
const uniqueSlug = require('unique-slug')
const fs = require('fs')
const path = require('path')
const findStorage = require('browser/lib/findStorage')
const mdurl = require('mdurl')
const fse = require('fs-extra')
const escapeStringRegexp = require('escape-string-regexp')
const sander = require('sander')
const url = require('url')
import i18n from 'browser/lib/i18n'
import { isString } from 'lodash'
const STORAGE_FOLDER_PLACEHOLDER = ':storage'
const DESTINATION_FOLDER = 'attachments'
const PATH_SEPARATORS =
escapeStringRegexp(path.posix.sep) + escapeStringRegexp(path.win32.sep)
const IMAGE_EXTENSIONS = [
'.apng',
'.bmp',
'.gif',
'.jpeg',
'.jpg',
'.png',
'.svg',
'.webp'
]
const JPEG_EXTENSIONS = ['.jpeg', '.jpg']
/**
* @description
* Create a Image element to get the real size of image.
* @param {File} file the File object dropped.
* @returns {Promise<Image>} Image element created
*/
function getImage(file) {
if (isString(file)) {
return new Promise(resolve => {
const img = new Image()
img.onload = () => resolve(img)
img.src = file
})
} else {
return new Promise(resolve => {
const reader = new FileReader()
const img = new Image()
img.onload = () => resolve(img)
reader.onload = e => {
img.src = e.target.result
}
reader.readAsDataURL(file)
})
}
}
/**
* @description
* Get the orientation info from iamges's EXIF data.
* case 1: The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
* case 2: The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
* case 3: The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
* case 4: The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
* case 5: The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
* case 6: The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
* case 7: The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
* case 8: The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
* Other: reserved
* ref: http://sylvana.net/jpegcrop/exif_orientation.html
* @param {File} file the File object dropped.
* @returns {Promise<Number>} Orientation info
*/
function getOrientation(file) {
const getData = arrayBuffer => {
const view = new DataView(arrayBuffer)
// Not start with SOI(Start of image) Marker return fail value
if (view.getUint16(0, false) !== 0xffd8) return -2
const length = view.byteLength
let offset = 2
while (offset < length) {
const marker = view.getUint16(offset, false)
offset += 2
// Loop and seed for APP1 Marker
if (marker === 0xffe1) {
// return fail value if it isn't EXIF data
if (view.getUint32((offset += 2), false) !== 0x45786966) {
return -1
}
// Read TIFF header,
// First 2bytes defines byte align of TIFF data.
// If it is 0x4949="II", it means "Intel" type byte align.
// If it is 0x4d4d="MM", it means "Motorola" type byte align
const little = view.getUint16((offset += 6), false) === 0x4949
offset += view.getUint32(offset + 4, little)
const tags = view.getUint16(offset, little) // Get TAG number
offset += 2
for (let i = 0; i < tags; i++) {
// Loop to find Orientation TAG and return the value
if (view.getUint16(offset + i * 12, little) === 0x0112) {
return view.getUint16(offset + i * 12 + 8, little)
}
}
} else if ((marker & 0xff00) !== 0xff00) {
// If not start with 0xFF, not a Marker.
break
} else {
offset += view.getUint16(offset, false)
}
}
return -1
}
return new Promise(resolve => {
const reader = new FileReader()
reader.onload = event => resolve(getData(event.target.result))
reader.readAsArrayBuffer(file.slice(0, 64 * 1024))
})
}
/**
* @description
* Rotate image file to correct direction.
* Create a canvas and draw the image with correct direction, then export to base64 format.
* @param {*} file the File object dropped.
* @return {String} Base64 encoded image.
*/
function fixRotate(file) {
return Promise.all([getImage(file), getOrientation(file)]).then(
([img, orientation]) => {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
if (orientation > 4 && orientation < 9) {
canvas.width = img.height
canvas.height = img.width
} else {
canvas.width = img.width
canvas.height = img.height
}
switch (orientation) {
case 2:
ctx.transform(-1, 0, 0, 1, img.width, 0)
break
case 3:
ctx.transform(-1, 0, 0, -1, img.width, img.height)
break
case 4:
ctx.transform(1, 0, 0, -1, 0, img.height)
break
case 5:
ctx.transform(0, 1, 1, 0, 0, 0)
break
case 6:
ctx.transform(0, 1, -1, 0, img.height, 0)
break
case 7:
ctx.transform(0, -1, -1, 0, img.height, img.width)
break
case 8:
ctx.transform(0, -1, 1, 0, 0, img.width)
break
default:
break
}
ctx.drawImage(img, 0, 0)
return canvas.toDataURL()
}
)
}
/**
* @description
* Copies a copy of an attachment to the storage folder specified by the given key and return the generated attachment name.
* Renames the file to match a unique file name.
*
* @param {String} sourceFilePath The source path of the attachment to be copied
* @param {String} storageKey Storage key of the destination storage
* @param {String} noteKey Key of the current note. Will be used as subfolder in :storage
* @param {boolean} useRandomName determines whether a random filename for the new file is used. If false the source file name is used
* @return {Promise<String>} name (inclusive extension) of the generated file
*/
function copyAttachment(
sourceFilePath,
storageKey,
noteKey,
useRandomName = true
) {
return new Promise((resolve, reject) => {
if (!sourceFilePath) {
reject('sourceFilePath has to be given')
}
if (!storageKey) {
reject('storageKey has to be given')
}
if (!noteKey) {
reject('noteKey has to be given')
}
try {
const isBase64 =
typeof sourceFilePath === 'object' && sourceFilePath.type === 'base64'
if (!isBase64 && !fs.existsSync(sourceFilePath)) {
return reject('source file does not exist')
}
const sourcePath = sourceFilePath.sourceFilePath || sourceFilePath
const sourceURL = url.parse(
/^\w+:\/\//.test(sourcePath) ? sourcePath : 'file:///' + sourcePath
)
let destinationName
if (useRandomName) {
destinationName = `${uniqueSlug()}${path.extname(sourceURL.pathname) ||
'.png'}`
} else {
destinationName = path.basename(sourceURL.pathname)
}
const targetStorage = findStorage.findStorage(storageKey)
const destinationDir = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey
)
createAttachmentDestinationFolder(targetStorage.path, noteKey)
const outputFile = fs.createWriteStream(
path.join(destinationDir, destinationName)
)
if (isBase64) {
const base64Data = sourceFilePath.data.replace(
/^data:image\/\w+;base64,/,
''
)
const dataBuffer = Buffer.from(base64Data, 'base64')
outputFile.write(dataBuffer, () => {
resolve(destinationName)
})
} else {
const inputFileStream = fs.createReadStream(sourceFilePath)
inputFileStream.pipe(outputFile)
inputFileStream.on('end', () => {
resolve(destinationName)
})
}
} catch (e) {
return reject(e)
}
})
}
function createAttachmentDestinationFolder(destinationStoragePath, noteKey) {
let destinationDir = path.join(destinationStoragePath, DESTINATION_FOLDER)
if (!fs.existsSync(destinationDir)) {
fs.mkdirSync(destinationDir)
}
destinationDir = path.join(
destinationStoragePath,
DESTINATION_FOLDER,
noteKey
)
if (!fs.existsSync(destinationDir)) {
fs.mkdirSync(destinationDir)
}
}
/**
* @description Moves attachments from the old location ('/images') to the new one ('/attachments/noteKey)
* @param markdownContent of the current note
* @param storagePath Storage path of the current note
* @param noteKey Key of the current note
*/
function migrateAttachments(markdownContent, storagePath, noteKey) {
if (
noteKey !== undefined &&
sander.existsSync(path.join(storagePath, 'images'))
) {
const attachments = getAttachmentsInMarkdownContent(markdownContent) || []
if (attachments.length) {
createAttachmentDestinationFolder(storagePath, noteKey)
}
for (const attachment of attachments) {
const attachmentBaseName = path.basename(attachment)
const possibleLegacyPath = path.join(
storagePath,
'images',
attachmentBaseName
)
if (sander.existsSync(possibleLegacyPath)) {
const destinationPath = path.join(
storagePath,
DESTINATION_FOLDER,
attachmentBaseName
)
if (!sander.existsSync(destinationPath)) {
sander.copyFileSync(possibleLegacyPath).to(destinationPath)
}
}
}
}
}
/**
* @description Fixes the URLs embedded in the generated HTML so that they again refer actual local files.
* @param {String} renderedHTML HTML in that the links should be fixed
* @param {String} storagePath Path of the current storage
* @returns {String} postprocessed HTML in which all :storage references are mapped to the actual paths.
*/
function fixLocalURLS(renderedHTML, storagePath) {
const encodedWin32SeparatorRegex = /%5C/g
const storageRegex = new RegExp('/?' + STORAGE_FOLDER_PLACEHOLDER, 'g')
const storageUrl =
'file:///' + path.join(storagePath, DESTINATION_FOLDER).replace(/\\/g, '/')
/*
A :storage reference is like `:storage/3b6f8bd6-4edd-4b15-96e0-eadc4475b564/f939b2c3.jpg`.
- `STORAGE_FOLDER_PLACEHOLDER` will match `:storage`
- `(?:(?:\\\/|%5C)[-.\\w]+)+` will match `/3b6f8bd6-4edd-4b15-96e0-eadc4475b564/f939b2c3.jpg`
- `(?:\\\/|%5C)[-.\\w]+` will either match `/3b6f8bd6-4edd-4b15-96e0-eadc4475b564` or `/f939b2c3.jpg`
- `(?:\\\/|%5C)` match the path seperator. `\\\/` for posix systems and `%5C` for windows.
*/
return renderedHTML.replace(
new RegExp(
'/?' + STORAGE_FOLDER_PLACEHOLDER + '(?:(?:\\/|%5C)[-.\\w]+)+',
'g'
),
function(match) {
return match
.replace(encodedWin32SeparatorRegex, '/')
.replace(storageRegex, storageUrl)
}
)
}
/**
* @description Generates the markdown code for a given attachment
* @param {String} fileName Name of the attachment
* @param {String} path Path of the attachment
* @param {Boolean} showPreview Indicator whether the generated markdown should show a preview of the image. Note that at the moment only previews for images are supported
* @returns {String} Generated markdown code
*/
function generateAttachmentMarkdown(fileName, path, showPreview) {
return `${showPreview ? '!' : ''}[${fileName}](${path})`
}
function generateStorageReferencePath(noteKey, fileName) {
return path.posix.join(STORAGE_FOLDER_PLACEHOLDER, noteKey, fileName)
}
function isImageFile(filePath, fileType) {
return (
fileType.startsWith('image') ||
IMAGE_EXTENSIONS.includes(path.extname(filePath).toLowerCase())
)
}
function shouldCheckOrientation(filePath, fileType) {
return (
fileType === 'image/jpeg' ||
JPEG_EXTENSIONS.includes(path.extname(filePath).toLowerCase())
)
}
/**
* @description Handles the drop-event of a file. Includes the necessary markdown code and copies the file to the corresponding storage folder.
* The method calls {CodeEditor#insertAttachmentMd()} to include the generated markdown at the needed place!
* @param {CodeEditor} codeEditor Markdown editor. Its insertAttachmentMd() method will be called to include the markdown code
* @param {String} storageKey Key of the current storage
* @param {String} noteKey Key of the current note
* @param {Event} dropEvent DropEvent
*/
function handleAttachmentDrop(codeEditor, storageKey, noteKey, dropEvent) {
let promise
if (dropEvent.dataTransfer.files.length > 0) {
promise = Promise.all(
Array.from(dropEvent.dataTransfer.files).map(file => {
const filePath = file.path
const fileType = file.type || '' // EX) 'image/gif' or 'text/html'
if (isImageFile(filePath, fileType)) {
if (!shouldCheckOrientation(filePath, fileType)) {
return copyAttachment(filePath, storageKey, noteKey).then(
fileName => ({
fileName,
title: path.basename(filePath),
isImage: true
})
)
} else {
return getOrientation(file)
.then(orientation => {
if (orientation <= 1) {
// The image rotation is correct and does not need adjustment
return copyAttachment(filePath, storageKey, noteKey)
} else {
return fixRotate(file).then(data =>
copyAttachment(
{
type: 'base64',
data: data,
sourceFilePath: filePath
},
storageKey,
noteKey
)
)
}
})
.then(fileName => ({
fileName,
title: path.basename(filePath),
isImage: true
}))
}
} else {
return copyAttachment(filePath, storageKey, noteKey).then(
fileName => ({
fileName,
title: path.basename(filePath),
isImage: false
})
)
}
})
)
} else {
let imageURL = dropEvent.dataTransfer.getData('text/plain')
if (!imageURL) {
const match = /<img[^>]*[\s"']src="([^"]+)"/.exec(
dropEvent.dataTransfer.getData('text/html')
)
if (match) {
imageURL = match[1]
}
}
if (!imageURL) {
return
}
promise = Promise.all([
getImage(imageURL)
.then(image => {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
canvas.width = image.width
canvas.height = image.height
context.drawImage(image, 0, 0)
return copyAttachment(
{
type: 'base64',
data: canvas.toDataURL(),
sourceFilePath: imageURL
},
storageKey,
noteKey
)
})
.then(fileName => ({
fileName,
title: imageURL,
isImage: true
}))
])
}
return promise.then(files => {
const attachments = files
.filter(file => !!file)
.map(file =>
generateAttachmentMarkdown(
file.title,
generateStorageReferencePath(noteKey, file.fileName),
file.isImage
)
)
codeEditor.insertAttachmentMd(attachments.join('\n'))
})
}
/**
* @description Creates a new file in the storage folder belonging to the current note and inserts the correct markdown code
* @param {CodeEditor} codeEditor Markdown editor. Its insertAttachmentMd() method will be called to include the markdown code
* @param {String} storageKey Key of the current storage
* @param {String} noteKey Key of the current note
* @param {DataTransferItem} dataTransferItem Part of the past-event
*/
function handlePasteImageEvent(
codeEditor,
storageKey,
noteKey,
dataTransferItem
) {
if (!codeEditor) {
throw new Error('codeEditor has to be given')
}
if (!storageKey) {
throw new Error('storageKey has to be given')
}
if (!noteKey) {
throw new Error('noteKey has to be given')
}
if (!dataTransferItem) {
throw new Error('dataTransferItem has to be given')
}
const blob = dataTransferItem.getAsFile()
const reader = new FileReader()
let base64data
const targetStorage = findStorage.findStorage(storageKey)
const destinationDir = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey
)
createAttachmentDestinationFolder(targetStorage.path, noteKey)
const imageName = `${uniqueSlug()}.png`
const imagePath = path.join(destinationDir, imageName)
reader.onloadend = function() {
base64data = reader.result.replace(/^data:image\/png;base64,/, '')
base64data += base64data.replace('+', ' ')
const binaryData = new Buffer(base64data, 'base64').toString('binary')
fs.writeFileSync(imagePath, binaryData, 'binary')
const imageReferencePath = generateStorageReferencePath(noteKey, imageName)
const imageMd = generateAttachmentMarkdown(
imageName,
imageReferencePath,
true
)
codeEditor.insertAttachmentMd(imageMd)
}
reader.readAsDataURL(blob)
}
/**
* @description Creates a new file in the storage folder belonging to the current note and inserts the correct markdown code
* @param {CodeEditor} codeEditor Markdown editor. Its insertAttachmentMd() method will be called to include the markdown code
* @param {String} storageKey Key of the current storage
* @param {String} noteKey Key of the current note
* @param {NativeImage} image The native image
*/
function handlePasteNativeImage(codeEditor, storageKey, noteKey, image) {
if (!codeEditor) {
throw new Error('codeEditor has to be given')
}
if (!storageKey) {
throw new Error('storageKey has to be given')
}
if (!noteKey) {
throw new Error('noteKey has to be given')
}
if (!image) {
throw new Error('image has to be given')
}
const targetStorage = findStorage.findStorage(storageKey)
const destinationDir = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey
)
createAttachmentDestinationFolder(targetStorage.path, noteKey)
const imageName = `${uniqueSlug()}.png`
const imagePath = path.join(destinationDir, imageName)
const binaryData = image.toPNG()
fs.writeFileSync(imagePath, binaryData, 'binary')
const imageReferencePath = generateStorageReferencePath(noteKey, imageName)
const imageMd = generateAttachmentMarkdown(
imageName,
imageReferencePath,
true
)
codeEditor.insertAttachmentMd(imageMd)
}
/**
* @description Returns all attachment paths of the given markdown
* @param {String} markdownContent content in which the attachment paths should be found
* @returns {String[]} Array of the relative paths (starting with :storage) of the attachments of the given markdown
*/
function getAttachmentsInMarkdownContent(markdownContent) {
const preparedInput = markdownContent.replace(
new RegExp('[' + PATH_SEPARATORS + ']', 'g'),
path.sep
)
const regexp = new RegExp(
'/?' +
STORAGE_FOLDER_PLACEHOLDER +
'(' +
escapeStringRegexp(path.sep) +
')' +
'?([a-zA-Z0-9]|-)*' +
'(' +
escapeStringRegexp(path.sep) +
')' +
'([a-zA-Z0-9]|\\.)+(\\.[a-zA-Z0-9]+)?',
'g'
)
return preparedInput.match(regexp)
}
/**
* @description Returns an array of the absolute paths of the attachments referenced in the given markdown code
* @param {String} markdownContent content in which the attachment paths should be found
* @param {String} storagePath path of the current storage
* @returns {String[]} Absolute paths of the referenced attachments
*/
function getAbsolutePathsOfAttachmentsInContent(markdownContent, storagePath) {
const temp = getAttachmentsInMarkdownContent(markdownContent) || []
const result = []
for (const relativePath of temp) {
result.push(
relativePath.replace(
new RegExp(STORAGE_FOLDER_PLACEHOLDER, 'g'),
path.join(storagePath, DESTINATION_FOLDER)
)
)
}
return result
}
/**
* @description Copies the attachments to the storage folder and returns the mardown content it should be replaced with
* @param {String} markDownContent content in which the attachment paths should be found
* @param {String} filepath The path of the file with attachments to import
* @param {String} storageKey Storage key of the destination storage
* @param {String} noteKey Key of the current note. Will be used as subfolder in :storage
*/
function importAttachments(markDownContent, filepath, storageKey, noteKey) {
return new Promise((resolve, reject) => {
const nameRegex = /(!\[.*?]\()(.+?\..+?)(\))/g
let attachPath = nameRegex.exec(markDownContent)
const promiseArray = []
const attachmentPaths = []
const groupIndex = 2
while (attachPath) {
let attachmentPath = attachPath[groupIndex]
attachmentPaths.push(attachmentPath)
attachmentPath = path.isAbsolute(attachmentPath)
? attachmentPath
: path.join(path.dirname(filepath), attachmentPath)
promiseArray.push(
this.copyAttachment(attachmentPath, storageKey, noteKey)
)
attachPath = nameRegex.exec(markDownContent)
}
let numResolvedPromises = 0
if (promiseArray.length === 0) {
resolve(markDownContent)
}
for (let j = 0; j < promiseArray.length; j++) {
promiseArray[j]
.then(fileName => {
const newPath = path.join(
STORAGE_FOLDER_PLACEHOLDER,
noteKey,
fileName
)
markDownContent = markDownContent.replace(attachmentPaths[j], newPath)
})
.catch(e => {
console.error('File does not exist in path: ' + attachmentPaths[j])
})
.finally(() => {
numResolvedPromises++
if (numResolvedPromises === promiseArray.length) {
resolve(markDownContent)
}
})
}
})
}
/**
* @description Moves the attachments of the current note to the new location.
* Returns a modified version of the given content so that the links to the attachments point to the new note key.
* @param {String} oldPath Source of the note to be moved
* @param {String} newPath Destination of the note to be moved
* @param {String} noteKey Old note key
* @param {String} newNoteKey New note key
* @param {String} noteContent Content of the note to be moved
* @returns {String} Modified version of noteContent in which the paths of the attachments are fixed
*/
function moveAttachments(oldPath, newPath, noteKey, newNoteKey, noteContent) {
const src = path.join(oldPath, DESTINATION_FOLDER, noteKey)
const dest = path.join(newPath, DESTINATION_FOLDER, newNoteKey)
if (fse.existsSync(src)) {
fse.moveSync(src, dest)
}
return replaceNoteKeyWithNewNoteKey(noteContent, noteKey, newNoteKey)
}
/**
* Modifies the given content so that in all attachment references the oldNoteKey is replaced by the new one
* @param noteContent content that should be modified
* @param oldNoteKey note key to be replaced
* @param newNoteKey note key serving as a replacement
* @returns {String} modified note content
*/
function replaceNoteKeyWithNewNoteKey(noteContent, oldNoteKey, newNoteKey) {
if (noteContent) {
const preparedInput = noteContent.replace(
new RegExp('[' + PATH_SEPARATORS + ']', 'g'),
path.sep
)
return preparedInput.replace(
new RegExp(
STORAGE_FOLDER_PLACEHOLDER + escapeStringRegexp(path.sep) + oldNoteKey,
'g'
),
path.join(STORAGE_FOLDER_PLACEHOLDER, newNoteKey)
)
}
return noteContent
}
/**
* @description replace all :storage references with given destination folder.
* @param input Input in which the references should be replaced
* @param noteKey Key of the current note
* @param destinationFolder Destination folder of the attachements
* @returns {String} Input without the references
*/
function replaceStorageReferences(input, noteKey, destinationFolder) {
return input.replace(
new RegExp('/?' + STORAGE_FOLDER_PLACEHOLDER + '[^"\\)<\\s]+', 'g'),
function(match) {
return match
.replace(new RegExp(mdurl.encode(path.win32.sep), 'g'), path.posix.sep)
.replace(new RegExp(mdurl.encode(path.posix.sep), 'g'), path.posix.sep)
.replace(
new RegExp(escapeStringRegexp(path.win32.sep), 'g'),
path.posix.sep
)
.replace(
new RegExp(escapeStringRegexp(path.posix.sep), 'g'),
path.posix.sep
)
.replace(
new RegExp(
STORAGE_FOLDER_PLACEHOLDER +
'(' +
escapeStringRegexp(path.sep) +
noteKey +
')?',
'g'
),
destinationFolder
)
}
)
}
/**
* @description Deletes the attachment folder specified by the given storageKey and noteKey
* @param storageKey Key of the storage of the note to be deleted
* @param noteKey Key of the note to be deleted
*/
function deleteAttachmentFolder(storageKey, noteKey) {
const storagePath = findStorage.findStorage(storageKey)
const noteAttachmentPath = path.join(
storagePath.path,
DESTINATION_FOLDER,
noteKey
)
sander.rimrafSync(noteAttachmentPath)
}
/**
* @description Deletes all attachments stored in the attachment folder of the give not that are not referenced in the markdownContent
* @param markdownContent Content of the note. All unreferenced notes will be deleted
* @param storageKey StorageKey of the current note. Is used to determine the belonging attachment folder.
* @param noteKey NoteKey of the current note. Is used to determine the belonging attachment folder.
*/
function deleteAttachmentsNotPresentInNote(
markdownContent,
storageKey,
noteKey
) {
if (storageKey == null || noteKey == null || markdownContent == null) {
return
}
const targetStorage = findStorage.findStorage(storageKey)
const attachmentFolder = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey
)
const attachmentsInNote = getAttachmentsInMarkdownContent(markdownContent)
const attachmentsInNoteOnlyFileNames = []
if (attachmentsInNote) {
for (let i = 0; i < attachmentsInNote.length; i++) {
attachmentsInNoteOnlyFileNames.push(
attachmentsInNote[i].replace(
new RegExp(
STORAGE_FOLDER_PLACEHOLDER +
escapeStringRegexp(path.sep) +
noteKey +
escapeStringRegexp(path.sep),
'g'
),
''
)
)
}
}
if (fs.existsSync(attachmentFolder)) {
fs.readdir(attachmentFolder, (err, files) => {
if (err) {
console.error(
'Error reading directory "' + attachmentFolder + '". Error:'
)
console.error(err)
return
}
files.forEach(file => {
if (!attachmentsInNoteOnlyFileNames.includes(file)) {
const absolutePathOfFile = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey,
file
)
fs.unlink(absolutePathOfFile, err => {
if (err) {
console.error('Could not delete "%s"', absolutePathOfFile)
console.error(err)
return
}
console.info(
'File "' +
absolutePathOfFile +
'" deleted because it was not included in the content of the note'
)
})
}
})
})
}
}
/**
* @description Get all existing attachments related to a specific note
including their status (in use or not) and their path. Return null if there're no attachment related to note or specified parametters are invalid
* @param markdownContent markdownContent of the current note
* @param storageKey StorageKey of the current note
* @param noteKey NoteKey of the currentNote
* @return {Promise<Array<{path: String, isInUse: bool}>>} Promise returning the
list of attachments with their properties */
function getAttachmentsPathAndStatus(markdownContent, storageKey, noteKey) {
if (storageKey == null || noteKey == null || markdownContent == null) {
return null
}
let targetStorage = null
try {
targetStorage = findStorage.findStorage(storageKey)
} catch (error) {
console.warn(`No stroage found for: ${storageKey}`)
}
if (!targetStorage) {
return null
}
const attachmentFolder = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey
)
const attachmentsInNote = getAttachmentsInMarkdownContent(markdownContent)
const attachmentsInNoteOnlyFileNames = []
if (attachmentsInNote) {
for (let i = 0; i < attachmentsInNote.length; i++) {
attachmentsInNoteOnlyFileNames.push(
attachmentsInNote[i].replace(
new RegExp(
STORAGE_FOLDER_PLACEHOLDER +
escapeStringRegexp(path.sep) +
noteKey +
escapeStringRegexp(path.sep),
'g'
),
''
)
)
}
}
if (fs.existsSync(attachmentFolder)) {
return new Promise((resolve, reject) => {
fs.readdir(attachmentFolder, (err, files) => {
if (err) {
console.error(
'Error reading directory "' + attachmentFolder + '". Error:'
)
console.error(err)
reject(err)
return
}
const attachments = []
for (const file of files) {
const absolutePathOfFile = path.join(
targetStorage.path,
DESTINATION_FOLDER,
noteKey,
file
)
if (!attachmentsInNoteOnlyFileNames.includes(file)) {
attachments.push({ path: absolutePathOfFile, isInUse: false })
} else {
attachments.push({ path: absolutePathOfFile, isInUse: true })
}
}
resolve(attachments)
})
})
} else {
return null
}
}
/**
* @description Remove all specified attachment paths
* @param attachments attachment paths
* @return {Promise} Promise after all attachments are removed */
function removeAttachmentsByPaths(attachments) {
const promises = []
for (const attachment of attachments) {
const promise = new Promise((resolve, reject) => {
fs.unlink(attachment, err => {
if (err) {
console.error('Could not delete "%s"', attachment)
console.error(err)
reject(err)
return
}
resolve()
})
})
promises.push(promise)
}
return Promise.all(promises)
}
/**
* Clones the attachments of a given note.
* Copies the attachments to their new destination and updates the content of the new note so that the attachment-links again point to the correct destination.
* @param oldNote Note that is being cloned
* @param newNote Clone of the note
*/
function cloneAttachments(oldNote, newNote) {
if (newNote.type === 'MARKDOWN_NOTE') {
const oldStorage = findStorage.findStorage(oldNote.storage)
const newStorage = findStorage.findStorage(newNote.storage)
const attachmentsPaths =
getAbsolutePathsOfAttachmentsInContent(
oldNote.content,
oldStorage.path
) || []
const destinationFolder = path.join(
newStorage.path,
DESTINATION_FOLDER,
newNote.key
)
if (!sander.existsSync(destinationFolder)) {
sander.mkdirSync(destinationFolder)
}
for (const attachment of attachmentsPaths) {
const destination = path.join(
newStorage.path,
DESTINATION_FOLDER,
newNote.key,
path.basename(attachment)
)
sander.copyFileSync(attachment).to(destination)
}
newNote.content = replaceNoteKeyWithNewNoteKey(
newNote.content,
oldNote.key,
newNote.key
)
} else {
console.debug(
'Cloning of the attachment was skipped since it only works for MARKDOWN_NOTEs'
)
}
}
function generateFileNotFoundMarkdown() {