Files: ce27463164a9c7dab3164e59e793ace39b8ac23d / index.js
2522 bytesRaw
1 | const { createCipher, createDecipher } = require('crypto'); |
2 | const { createGzip, createGunzip } = require('zlib'); |
3 | const combiner = require('stream-combiner'); |
4 | |
5 | const copy = require('./copy'); |
6 | const utils = require('./utils'); |
7 | |
8 | module.exports = function sync(source, target, crypt, decrypt) { |
9 | return new Promise(async (resolve, reject) => { |
10 | |
11 | // Generate crypt and decrypt streams |
12 | const transformStreams = []; |
13 | |
14 | if (crypt) { |
15 | |
16 | // Set stream to zip |
17 | transformStreams.push(createGzip()); |
18 | |
19 | // Set stream to crypt |
20 | transformStreams.push(createCipher(crypt.algorithm, crypt.password)); |
21 | } else if (decrypt) { |
22 | |
23 | // Set stream to decrypt |
24 | transformStreams.push(createDecipher(decrypt.algorithm, decrypt.password)); |
25 | |
26 | // Set stream to unzip |
27 | transformStreams.push(createGunzip()); |
28 | } |
29 | |
30 | const combinedStreams = combiner(transformStreams); |
31 | |
32 | try { |
33 | await syncAction(source, target, combinedStreams); |
34 | |
35 | return resolve(); |
36 | } catch (err) { |
37 | return reject(err); |
38 | } |
39 | }); |
40 | }; |
41 | |
42 | function syncAction(source, target, cryptDecryptTransform) { |
43 | return new Promise(async (resolve, reject) => { |
44 | try { |
45 | |
46 | // Get stats of source and target |
47 | const [ statSource, statTarget ] = await Promise.all([ utils.getStats(source), utils.getStats(target) ]); |
48 | |
49 | // Source does not exists and target exists, delete target |
50 | if (statSource === null && statTarget !== null) { |
51 | await utils.delete(target); |
52 | |
53 | return resolve(); |
54 | } |
55 | |
56 | // Dost not exists in the target, copy |
57 | if (statSource !== null && statTarget === null) { |
58 | await copy(source, target, cryptDecryptTransform); |
59 | |
60 | return resolve(); |
61 | } |
62 | |
63 | if (statSource.isDirectory() && statTarget.isDirectory()) { |
64 | |
65 | // Verify if both are directories |
66 | const nextPaths = await utils.readRecursive(source, target); |
67 | |
68 | for (let index = 0; index < nextPaths.length; index++) { |
69 | const [ nextSource, nextTarget ] = nextPaths[index]; |
70 | |
71 | // Start to sync next paths |
72 | await syncAction(nextSource, nextTarget, cryptDecryptTransform); |
73 | } |
74 | } else if (statSource.isFile() && statTarget.isFile()) { |
75 | |
76 | // Verify if both are files |
77 | if (statSource.mtime <= statTarget.mtime) { |
78 | |
79 | // Source is newer, copy the new version to the target |
80 | await copy(source, target, cryptDecryptTransform); |
81 | } |
82 | } |
83 | |
84 | return resolve(); |
85 | } catch (err) { |
86 | return reject(err); |
87 | } |
88 | }); |
89 | } |
Built with git-ssb-web