@d0whc3r/node-gdrive 3.4.1 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +174 -92
- package/bin/cli.js +2 -634
- package/dist/auth.d.ts +25 -0
- package/dist/config.d.ts +16 -0
- package/dist/crypto.d.ts +4 -0
- package/dist/gdrive.cjs.js +1 -1
- package/dist/gdrive.esm.mjs +802 -0
- package/dist/index.d.ts +65 -48
- package/dist/retry.d.ts +3 -0
- package/dist/types.d.ts +96 -0
- package/package.json +83 -139
- package/CHANGELOG.md +0 -10
- package/dist/gdrive.esm.js +0 -1
package/bin/cli.js
CHANGED
|
@@ -1,636 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';
|
|
2
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let l=require("node:util"),u=require("command-line-args");u=c(u);let d=require("command-line-usage");d=c(d);let f=require("node:fs");f=c(f);let p=require("node:os");p=c(p);let m=require("node:path");m=c(m);let h=require("dayjs");h=c(h);let g=require("mysqldump");g=c(g);let _=require("node:stream/promises"),v=require("@googleapis/drive"),y=require("archiver"),b=require("mime-types");b=c(b);let x=require("node:crypto");x=c(x);let S=require("node:http");S=c(S);let C=require("google-auth-library");var w={name:`@d0whc3r/node-gdrive`,version:`3.4.1`,keywords:[`backup`,`compress`,`copy`,`drive`,`gdrive`,`google`,`googleapi`,`node`,`upload`],license:`MIT`,author:{name:`d0whc3r`,email:`d0whc3r@gmail.com`,url:`https://github.com/d0whc3r`},repository:{type:`git`,url:`https://github.com/d0whc3r/node-gdrive.git`},bin:{"node-gdrive":`./bin/cli.js`},files:[`dist`,`bin`],main:`dist/gdrive.cjs.js`,module:`dist/gdrive.esm.mjs`,types:`dist/index.d.ts`,exports:{".":{types:`./dist/index.d.ts`,import:`./dist/gdrive.esm.mjs`,require:`./dist/gdrive.cjs.js`}},publishConfig:{access:`public`,registry:`https://registry.npmjs.org`},scripts:{clean:`node -e "import('node:fs').then(fs => ['dist','bin','build','coverage','node-gdrive','node-gdrive.exe'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"cli:dev":`node --env-file=.env cli/cli.ts`,cli:`node cli/cli.ts`,typecheck:`tsc --noEmit`,"build:clean":`node -e "import('node:fs').then(fs => ['dist','bin'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"build:lib":`vite build --config vite.config.mts`,"build:cli":`vite build --config vite.cli.config.mts`,"build:dts":`tsc -p tsconfig.build.json --emitDeclarationOnly`,"build:base":`pnpm build:clean && pnpm build:lib && pnpm build:cli && pnpm build:dts`,"build:sea":`vite build --config vite.sea.config.mts && node scripts/build-sea.mjs`,build:`pnpm build:base && pnpm build:sea`,test:`vitest run`,"test:unit":`vitest run --exclude tests/gdrive.integration.spec.ts`,"test:integration":`vitest run tests/gdrive.integration.spec.ts`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:fix":`oxlint --fix`,format:`oxfmt --write`,"format:check":`oxfmt --check`,prepare:`husky`,"semantic-release":`semantic-release`},dependencies:{"@googleapis/drive":`^27.1.0`,archiver:`^8.0.0`,"command-line-args":`^6.0.2`,"command-line-usage":`^7.0.4`,dayjs:`^1.11.23`,"google-auth-library":`^11.3.4`,"mime-types":`^3.0.2`,mysqldump:`^3.2.0`},devDependencies:{"@commitlint/cli":`^21.2.4`,"@commitlint/config-conventional":`^21.2.4`,"@semantic-release/changelog":`^7.0.0`,"@semantic-release/commit-analyzer":`^13.0.1`,"@semantic-release/git":`^11.0.1`,"@semantic-release/github":`^12.0.11`,"@semantic-release/npm":`^13.2.0`,"@semantic-release/release-notes-generator":`^14.1.1`,"@types/archiver":`^8.0.0`,"@types/command-line-args":`^5.2.3`,"@types/command-line-usage":`^5.0.4`,"@types/mime-types":`^3.0.1`,"@types/node":`^26.6.10`,"@vitest/coverage-v8":`^5.1.2`,husky:`^9.1.7`,"lint-staged":`^17.6.2`,oxfmt:`^0.80.0`,oxlint:`^1.95.0`,"semantic-release":`^26.0.1`,typescript:`^7.0.2`,vite:`^8.3.8`,vitest:`^5.1.2`},"lint-staged":{"{src,cli,tests}/**/*.ts":[`pnpm lint:fix`,`pnpm format`]},engines:{node:`>=26.0.0`},packageManager:`pnpm@12.16.1`},T=[{name:`list`,alias:`l`,multiple:!1,type:Boolean,description:`List all files and folders`},{name:`backup`,alias:`b`,typeLabel:`{underline file*}`,defaultOption:!0,multiple:!0,type:String,description:`Backup files, directories, or globs`},{name:`download`,typeLabel:`{underline fileId|name}`,multiple:!1,type:String,description:`Download/restore a file from Google Drive`},{name:`output`,alias:`o`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Local destination path for --download`},{name:`zip`,alias:`z`,typeLabel:`{underline zipname.zip}`,multiple:!1,type:String,description:`Zip backup files before uploading`},{name:`replace`,alias:`r`,multiple:!1,type:Boolean,description:`Replace files if already exists when uploading`},{name:`create`,alias:`c`,multiple:!1,type:Boolean,description:`Create destination upload folder if missing`},{name:`folder`,alias:`f`,typeLabel:`{underline foldername}`,multiple:!1,type:String,description:`Destination or target folder path (supports nested paths like a/b/c)`},{name:`delete`,alias:`d`,typeLabel:`{underline folder=duration} OR {underline duration}`,multiple:!0,type:String,description:`Clean files older than duration (e.g. 7d, 1M, 30m)`},{name:`keep-last`,typeLabel:`{underline N}`,multiple:!1,type:Number,description:`Always keep the newest N files when cleaning older files`},{name:`mysql`,alias:`m`,multiple:!1,type:Boolean,description:`MySQL backup using environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)`},{name:`stdin`,multiple:!1,type:Boolean,description:`Read upload content from stdin (requires --name)`},{name:`name`,typeLabel:`{underline filename}`,multiple:!1,type:String,description:`Target filename when uploading from --stdin`},{name:`encrypt`,multiple:!1,type:Boolean,description:`Encrypt uploads / decrypt downloads with AES-256-GCM using $BACKUP_ENCRYPTION_KEY`},{name:`exclude`,typeLabel:`{underline glob}`,multiple:!0,type:String,description:`Exclude glob pattern(s) when backing up files`},{name:`dry-run`,multiple:!1,type:Boolean,description:`Preview uploads or deletions without modifying Google Drive`},{name:`drive-id`,typeLabel:`{underline id}`,multiple:!1,type:String,description:`Google Shared Drive ID`},{name:`service-account`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Path to Google Service Account JSON key file`},{name:`json`,multiple:!1,type:Boolean,description:`Output command results as JSON`},{name:`quiet`,alias:`q`,multiple:!1,type:Boolean,description:`Suppress non-essential log output`},{name:`version`,alias:`v`,multiple:!1,type:Boolean,description:`Print version number`},{name:`help`,alias:`h`,description:`Print this usage guide`,type:Boolean}];function E(){return w.version}function D(){let e=`node-gdrive`,t=[{header:`Help for ${e} v${w.version}`,content:`Usage of {italic ${e}} in command line.`},{header:`Options`,optionList:T},{header:`Examples`,content:[{desc:`1. List files (or JSON output).`,example:`$ ${e} -l --json`},{desc:`2. Backup multiple files to nested folder.`,example:`$ ${e} -b src/index.ts -b images/logo.png -f backups/app -c`},{desc:`3. Backup files as encrypted zip excluding logs.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${e} -b ./data/* --exclude "*.log" -z backup.zip -f backups -c -r --encrypt`},{desc:`4. Stream stdin directly to Google Drive.`,example:`$ pg_dump mydb | ${e} --stdin --name mydb.sql -f backups/pg -c`},{desc:`5. Download and decrypt a backup.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${e} --download backup.zip.enc -f backups -o ./backup.zip --encrypt`},{desc:`6. Clean files older than 7 days while keeping the 5 newest (dry run).`,example:`$ ${e} -f backups -d 7d --keep-last 5 --dry-run`},{desc:`7. Generate MySQL dump, zip, and upload to "mysql-backup" folder.`,example:`$ ${e} -f mysql-backup -m -z -c`}]}];return(0,d.default)(t)}function O(e){let t=(0,u.default)(T,e?{argv:e}:void 0);if(t[`keep-last`]!==void 0){let e=t[`keep-last`];if(!Number.isInteger(e)||e<0)throw Error(`Invalid --keep-last value "${String(e)}": expected a non-negative integer.`)}if(t.stdin&&!t.name)throw Error(`Option --stdin requires --name <filename>.`);return t}var k=c(o(((e,t,n)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self).dayjs_plugin_isSameOrBefore=r()})(n,(function(){"use strict";return function(e,t){t.prototype.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)}}}))}))()),A=class{static _tokenFile;static _credentialsFile;static _serviceAccountFile;static _tag;static get TOKEN_FILE(){return this._tokenFile??process.env.TOKEN_FILE??`./secrets/token.json`}static set TOKEN_FILE(e){this._tokenFile=e}static get CREDENTIALS_FILE(){return this._credentialsFile??process.env.CREDENTIALS_FILE??`./secrets/credentials.json`}static set CREDENTIALS_FILE(e){this._credentialsFile=e}static get SERVICE_ACCOUNT_FILE(){return this._serviceAccountFile??process.env.SERVICE_ACCOUNT_FILE??process.env.GOOGLE_APPLICATION_CREDENTIALS}static set SERVICE_ACCOUNT_FILE(e){this._serviceAccountFile=e}static get BACKUP_ENCRYPTION_KEY(){return process.env.BACKUP_ENCRYPTION_KEY||void 0}static get TAG(){return this._tag??`[node-gdrive]`}static set TAG(e){this._tag=e}static reset(){this._tokenFile=void 0,this._credentialsFile=void 0,this._serviceAccountFile=void 0,this._tag=void 0}},ee=[`https://www.googleapis.com/auth/drive`],j=class{ready=!0;scopes;tokenFile;credentialsFile;serviceAccountFile;useADC;logger;_oAuth2Client;_googleAuth;constructor(e={}){this.tokenFile=e.tokenFile??A.TOKEN_FILE,this.credentialsFile=e.credentialsFile??A.CREDENTIALS_FILE,this.serviceAccountFile=e.serviceAccountFile??A.SERVICE_ACCOUNT_FILE,this.useADC=e.useADC??!1,this.scopes=e.scopes??ee,this.logger=e.logger??console,this.serviceAccountFile?f.existsSync(this.serviceAccountFile)||(this.ready=!1,this.logger.error((0,l.styleText)([`bold`,`red`],`${A.TAG} ERROR: Service account file not found in ${this.serviceAccountFile}`))):!this.useADC&&!this.existsCredentials&&(this.ready=!1,this.logger.error((0,l.styleText)([`bold`,`red`],`${A.TAG} ERROR: Credentials file not found in ${this.credentialsFile}`)))}get isServiceAccountOrADC(){return!!this.serviceAccountFile||this.useADC}get existsToken(){return f.existsSync(this.tokenFile)}get existsCredentials(){return f.existsSync(this.credentialsFile)}async initiate(){if(!this.ready){let e=this.serviceAccountFile??this.credentialsFile;throw Error(`${A.TAG} Credentials file not found in ${e}`)}return this.isServiceAccountOrADC?(this.googleAuthClient(),!0):this.existsToken?(this.oAuth2Client(!0),!0):this.generateAccessToken()}getAuthClient(){return this.isServiceAccountOrADC?this.googleAuthClient():this.oAuth2Client(!0)}googleAuthClient(){if(!this._googleAuth){if(this.serviceAccountFile){let e=JSON.parse(f.readFileSync(this.serviceAccountFile,`utf8`));this._googleAuth=new C.GoogleAuth({credentials:e,scopes:this.scopes})}else this._googleAuth=new C.GoogleAuth({scopes:this.scopes})}return this._googleAuth}oAuth2Client(e=!0,t){if(!this._oAuth2Client){let n=JSON.parse(f.readFileSync(this.credentialsFile,`utf8`)),r=n.installed??n.web;if(!r)throw Error(`${A.TAG} Invalid credentials file format in ${this.credentialsFile}`);let{client_secret:i,client_id:a,redirect_uris:o}=r;if(this._oAuth2Client=new C.OAuth2Client(a,i,t??o?.[0]??`http://127.0.0.1`),this.attachTokenListener(this._oAuth2Client),e&&this.existsToken){let e=JSON.parse(f.readFileSync(this.tokenFile,`utf8`));this._oAuth2Client.setCredentials(e)}}return this._oAuth2Client}attachTokenListener(e){e.on(`tokens`,e=>{try{let t={};this.existsToken&&(t=JSON.parse(f.readFileSync(this.tokenFile,`utf8`)));let n={...t,...e,refresh_token:e.refresh_token??t.refresh_token};this.persistTokenSync(n)}catch(e){this.logger.warn(`${A.TAG} Failed to persist refreshed token:`,e)}})}persistTokenSync(e){f.mkdirSync(m.default.dirname(this.tokenFile),{recursive:!0,mode:448}),f.writeFileSync(this.tokenFile,JSON.stringify(e,null,2),{mode:384}),f.chmodSync(this.tokenFile,384)}async generateAccessToken(){let e=x.default.randomBytes(16).toString(`hex`),t=x.default.randomBytes(32).toString(`base64url`),n=x.default.createHash(`sha256`).update(t).digest(`base64url`);return new Promise((r,i)=>{let a=S.default.createServer(),o=!1,s=e=>{o||(o=!0,a.close(),e())};a.on(`error`,e=>{s(()=>i(Error(`${A.TAG} OAuth loopback server failed`,{cause:e})))}),a.on(`request`,(n,o)=>{(async()=>{try{let c=new URL(n.url??`/`,`http://127.0.0.1`);if(c.pathname!==`/oauth2callback`){o.writeHead(404,{"Content-Type":`text/plain`}),o.end(`Not found`);return}let l=c.searchParams.get(`state`),u=c.searchParams.get(`code`),d=c.searchParams.get(`error`);if(d){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Authorization failed: ${d}`),s(()=>i(Error(`${A.TAG} OAuth authorization error: ${d}`)));return}if(!l||l!==e){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Invalid OAuth state parameter`),s(()=>i(Error(`${A.TAG} OAuth state mismatch`)));return}if(!u){o.writeHead(400,{"Content-Type":`text/plain`}),o.end(`Missing authorization code`),s(()=>i(Error(`${A.TAG} Missing OAuth authorization code`)));return}let f=`http://127.0.0.1:${a.address().port}/oauth2callback`,p=this.oAuth2Client(!1,f),{tokens:m}=await p.getToken({code:u,codeVerifier:t,redirect_uri:f});p.setCredentials(m),this.persistTokenSync(m),o.writeHead(200,{"Content-Type":`text/plain`}),o.end(`Authentication successful! You can close this window.`),this.logger.info(`${A.TAG} Token stored to`,this.tokenFile),s(()=>r(!0))}catch(e){o.writeHead(500,{"Content-Type":`text/plain`}),o.end(`Error exchanging OAuth authorization code.`),s(()=>i(e instanceof Error?e:Error(String(e))))}})()}),a.listen(0,`127.0.0.1`,()=>{let t=`http://127.0.0.1:${a.address().port}/oauth2callback`,r=this.oAuth2Client(!1,t).generateAuthUrl({access_type:`offline`,prompt:`consent`,scope:this.scopes,redirect_uri:t,state:e,code_challenge:n,code_challenge_method:C.CodeChallengeMethod.S256});this.logger.info(`${A.TAG} Authorize this app by visiting this url:`,r)})})}},M=Buffer.from(`NGDE`,`ascii`),N=1,P=16,F=12,I=16,L=32,R=M.length+1+P+F;function z(e,t){if(!e)throw Error(`Encryption passphrase must not be empty`);return x.default.scryptSync(e,t,L)}async function B(e,t,n){let r=x.default.randomBytes(P),i=x.default.randomBytes(F),a=z(n,r),o=Buffer.concat([M,Buffer.from([N]),r,i]);f.default.mkdirSync(m.default.dirname(t),{recursive:!0,mode:448});let s=x.default.createCipheriv(`aes-256-gcm`,a,i),c=f.default.createReadStream(e),l=f.default.createWriteStream(t,{mode:384});try{l.write(o),await(0,_.pipeline)(c,s,l,{end:!1});let e=s.getAuthTag();return await new Promise((t,n)=>{l.once(`error`,n),l.end(e,()=>t())}),t}catch(n){throw c.destroy(),l.destroy(),f.default.rmSync(t,{force:!0}),Error(`Failed to encrypt file "${e}"`,{cause:n})}}async function V(e,t,n){let r=f.default.statSync(e);if(r.size<R+I)throw Error(`Encrypted file is too short or corrupted`);let i=f.default.openSync(e,`r`),a=Buffer.alloc(R),o=Buffer.alloc(I);try{f.default.readSync(i,a,0,R,0),f.default.readSync(i,o,0,I,r.size-I)}finally{f.default.closeSync(i)}if(!a.subarray(0,M.length).equals(M))throw Error(`Invalid encrypted file header`);let s=a[M.length];if(s!==N)throw Error(`Unsupported encryption format version: ${String(s)}`);let c=M.length+1,l=c+P,u=a.subarray(c,l),d=a.subarray(l,R),p=z(n,u),h=x.default.createDecipheriv(`aes-256-gcm`,p,d);h.setAuthTag(o),f.default.mkdirSync(m.default.dirname(t),{recursive:!0,mode:448});let g=r.size-R-I,v=f.default.createWriteStream(t,{mode:384});try{if(g===0){let e=h.final();await new Promise((t,n)=>{v.once(`error`,n),v.end(e,()=>t())})}else{let t=f.default.createReadStream(e,{start:R,end:r.size-I-1});await(0,_.pipeline)(t,h,v)}return t}catch(n){throw v.destroy(),f.default.rmSync(t,{force:!0}),Error(`Failed to decrypt file "${e}"`,{cause:n})}}var H=new Set([429,500,502,503,504]),U=new Set([`ECONNRESET`,`ETIMEDOUT`,`ENOTFOUND`,`EAI_AGAIN`,`EPIPE`,`UND_ERR_CONNECT_TIMEOUT`]);function W(e){return new Promise(t=>{setTimeout(t,e)})}function G(e){if(!e||typeof e!=`object`)return!1;let t=e,n=typeof t.status==`number`?t.status:typeof t.code==`number`?t.code:typeof t.response?.status==`number`?t.response.status:void 0;if(n!==void 0&&H.has(n))return!0;let r=typeof t.code==`string`?t.code:void 0;return!!(r&&U.has(r))}async function K(e,t={}){let{maxRetries:n=4,baseDelayMs:r=500,maxDelayMs:i=16e3,jitter:a=!0,sleep:o=W}=t,s=0;for(;;)try{return await e()}catch(e){if(s>=n||!G(e))throw e;let t=Math.min(i,r*2**s),c=a?Math.round(t*(.5+Math.random()*.5)):t;s+=1,await o(c)}}var q=`appProperties.capabilities.contentHints.createdTime.description.explicitlyTrashed.fileExtension.folderColorRgb.fullFileExtension.hasAugmentedPermissions.hasThumbnail.headRevisionId.iconLink.id.imageMediaMetadata.isAppAuthorized.lastModifyingUser.md5Checksum.mimeType.modifiedByMe.modifiedByMeTime.modifiedTime.name.originalFilename.ownedByMe.owners.parents.properties.quotaBytesUsed.shared.sharedWithMeTime.sharingUser.size.spaces.starred.teamDriveId.thumbnailLink.thumbnailVersion.trashed.trashedTime.trashingUser.version.videoMediaMetadata.viewedByMe.viewedByMeTime.viewersCanCopyContent.webContentLink.webViewLink.writersCanShare`.split(`.`);h.default.extend(k.default);var J=new Set(q),Y=/^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/,X={s:`second`,second:`second`,seconds:`second`,m:`minute`,minute:`minute`,minutes:`minute`,h:`hour`,hour:`hour`,hours:`hour`,d:`day`,day:`day`,days:`day`,w:`week`,week:`week`,weeks:`week`,M:`month`,month:`month`,months:`month`,y:`year`,year:`year`,years:`year`};function Z(e){return e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}function Q(e){let t=Y.exec(e);if(!t)throw Error(`${A.TAG} Invalid timeSpace "${e}". Expected "<number><unit>" where unit is one of: s, m, h, d, w, M, y, second(s), minute(s), hour(s), day(s), week(s), month(s), year(s).`);let n=Number(t[1]),r=X[t[2]];if(!Number.isFinite(n)||n<=0||!r)throw Error(`${A.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);return{amount:n,unit:r}}async function $(e,t,n){let r=Math.max(1,Math.floor(t)),i=Array.from({length:e.length}),a=0;async function o(){for(;a<e.length;){let t=a;a+=1,i[t]=await n(e[t])}}let s=Array.from({length:Math.min(r,e.length)},()=>o());return await Promise.all(s),i}var te=class{DEFAULT_FIELDS=[`createdTime`,`id`,`md5Checksum`,`mimeType`,`name`,`parents`,`trashed`];MIME_FOLDER=`application/vnd.google-apps.folder`;gdriveAuth;injectedAuth;sharedDriveId;defaultDryRun;defaultConcurrency;defaultCompressionLevel;defaultOnProgress;retryOptions;logger;_drive;_initPromise;constructor(e={}){this.logger=e.logger??console,this.sharedDriveId=e.sharedDriveId,this.defaultDryRun=e.dryRun??!1,this.defaultConcurrency=e.concurrency??4,this.defaultCompressionLevel=e.compressionLevel??6,this.defaultOnProgress=e.onProgress,this.retryOptions=e.retry??{},e.drive&&(this._drive=e.drive),e.auth&&(this.injectedAuth=e.auth),!e.drive&&!e.auth&&(this.gdriveAuth=new j({credentialsFile:e.credentialsFile,tokenFile:e.tokenFile,serviceAccountFile:e.serviceAccountFile,useADC:e.useADC,scopes:e.scopes,logger:this.logger}))}ensureInitiated(){return this._drive||this.injectedAuth?Promise.resolve(!0):(this._initPromise||=this.gdriveAuth.initiate().catch(e=>{throw this._initPromise=void 0,e}),this._initPromise)}get auth(){return this.injectedAuth?this.injectedAuth:this.gdriveAuth.getAuthClient()}get drive(){return this._drive||=(0,v.drive)({version:`v3`,auth:this.auth}),this._drive}get sharedDriveListParams(){return this.sharedDriveId?{supportsAllDrives:!0,includeItemsFromAllDrives:!0,corpora:`drive`,driveId:this.sharedDriveId}:{}}get sharedDriveItemParams(){return this.sharedDriveId?{supportsAllDrives:!0}:{}}get rootParentId(){return this.sharedDriveId??`root`}isFolder(e){if(Object.hasOwn(e,`mimeType`))return e.mimeType===this.MIME_FOLDER}isDeleted(e){return Object.hasOwn(e,`trashed`)?!!e.trashed:!1}async listFiles(e,t=1e3,n){await this.ensureInitiated();let r;if(!e)r=this.DEFAULT_FIELDS;else if(e===!0)r=q;else{for(let t of e)if(!J.has(t))throw Error(`${A.TAG} Invalid Drive file field: "${t}"`);r=e}let i={pageSize:t,fields:`kind, nextPageToken, incompleteSearch, files(${r.join(`, `)})`,prettyPrint:!1,...this.sharedDriveListParams};return n&&(i.q=n),this.getListFiles(i)}async getFile(e){if(await this.ensureInitiated(),!e)throw this.genericError(Error(`${A.TAG} File id not found`));let t={fileId:e,...this.sharedDriveItemParams};try{let{data:e}=await K(()=>this.drive.files.get(t),this.retryOptions);return e}catch(e){throw this.genericError(e)}}async downloadFile(e,t,n={}){if(await this.ensureInitiated(),!e)throw Error(`${A.TAG} File id or name is required for download`);let r=e;if(n.folderName){let t=await this.findFolderId(n.folderName,!1),i=await this.findFile(e,t);if(!i?.id)throw Error(`${A.TAG} File "${e}" not found in folder "${n.folderName}"`);r=i.id}else try{let t=await K(()=>this.drive.files.get({fileId:e,fields:`id, name, mimeType`,...this.sharedDriveItemParams}),this.retryOptions);t.data.id&&(r=t.data.id)}catch{let t=await this.findFile(e);if(!t?.id)throw Error(`${A.TAG} File "${e}" not found`);r=t.id}f.default.mkdirSync(m.default.dirname(m.default.resolve(t)),{recursive:!0});let i,a=n.decryptKey?(i=this.createPrivateTempDir(),m.default.join(i,`download.enc`)):t;try{let e=await K(()=>this.drive.files.get({fileId:r,alt:`media`,...this.sharedDriveItemParams},{responseType:`stream`}),this.retryOptions),i=f.default.createWriteStream(a,{mode:n.decryptKey?384:420});return await(0,_.pipeline)(e.data,i),n.decryptKey&&await V(a,t,n.decryptKey),t}catch(e){throw n.decryptKey||f.default.rmSync(t,{force:!0}),this.genericError(e)}finally{i&&f.default.rmSync(i,{recursive:!0,force:!0})}}async emptyTrash(){return await this.ensureInitiated(),K(()=>this.drive.files.emptyTrash(),this.retryOptions)}async deleteFile(e){if(await this.ensureInitiated(),e.id)try{let{data:t}=await K(()=>this.drive.files.delete({fileId:e.id,...this.sharedDriveItemParams}),this.retryOptions);return e.name&&this.logger.warn(`${A.TAG} Deleted ${e.isFolder?`folder`:`file`}: ${e.name}`),t}catch(e){throw this.genericError(e)}}async uploadFile(e,t,n={}){await this.ensureInitiated();let{create:r=!0,replace:i=!1,encryptKey:a}=n,o=n.dryRun??this.defaultDryRun,s=n.onProgress??this.defaultOnProgress,c=m.default.basename(e),l=a&&!c.endsWith(`.enc`)?`${c}.enc`:c,u={name:l,mimeType:a?`application/octet-stream`:b.default.contentType(c)||void 0},d=await this.getUploadFolderId(t||!1,r,u,o);if(o)return this.logger.info(`${A.TAG} [dry-run] Would upload "${l}"${t&&typeof t==`string`?` to "${t}"`:``}`),this.parseFileMeta(u);await this.replaceExistingFile(i,l,d);let p,h=e;a&&(p=this.createPrivateTempDir(),h=m.default.join(p,l),await B(e,h,a));try{let e=f.default.statSync(h).size,{data:t}=await K(async()=>{let t=f.default.createReadStream(h);t.on(`error`,e=>{this.logger.error(`${A.TAG} Read stream error for "${h}":`,e)});let n={requestBody:u,media:{body:t},fields:`kind, ${this.DEFAULT_FIELDS.join(`, `)}`,...this.sharedDriveItemParams},r=t=>{let n=e===0?100:Math.min(100,t.bytesRead/e*100);s?.({fileName:l,bytesRead:t.bytesRead,totalBytes:e,percentage:n}),n>=100&&this.logger.warn(`${A.TAG} Upload ${l}: ${Math.round(n)}% complete`)};try{return await this.drive.files.create(n,{onUploadProgress:r})}finally{t.destroy()}},this.retryOptions);return this.parseFileMeta(t)}catch(e){throw this.genericError(e)}finally{p&&f.default.rmSync(p,{recursive:!0,force:!0})}}async uploadStream(e,t,n,r={}){await this.ensureInitiated();let i=this.sanitizeFilename(t),a=this.createPrivateTempDir(),o=m.default.join(a,i);try{let t=f.default.createWriteStream(o,{mode:384});return await(0,_.pipeline)(e,t),await this.uploadFile(o,n,r)}finally{f.default.rmSync(a,{recursive:!0,force:!0})}}async uploadFiles(e,t,n={}){await this.ensureInitiated();let{compress:r,replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c,exclude:l,followSymlinks:u=!1}=n,d=n.concurrency??this.defaultConcurrency,p=n.compressionLevel??this.defaultCompressionLevel,g=Array.isArray(e)?e:[e],_=this.expandFileInputs(g,{exclude:l,followSymlinks:u}),v,y=_;try{if(r){let e=typeof r==`string`?r:`zipped_${(0,h.default)().format(`YYYY-MM-DD.HHmmss`)}.zip`,{zipPath:t,tempDir:n}=await this.compressFiles(_,e,{compressionLevel:p,followSymlinks:u});v=n,y=[t]}t&&typeof t==`string`&&y.length>0&&!(o??this.defaultDryRun)&&await this.findFolderId(t,a??!0);let e={};return await $(y,d,async n=>{let r=await this.uploadFile(n,t,{replace:i,create:a,dryRun:o,encryptKey:s,onProgress:c}),l=r.name||m.default.basename(n);e[l]=r}),e}finally{v&&f.default.rmSync(v,{recursive:!0,force:!0})}}async cleanOlder(e,t,n={}){let{amount:r,unit:i}=Q(e);await this.ensureInitiated();let a=``;return t&&(a=await this.findFolderId(t,!1)),this.deleteOlder(r,i,a,n)}expandFileInputs(e,t){let{exclude:n=[],followSymlinks:r=!1}=t,i=[],a=e=>{if(e.includes(`*`)){let t=f.default.globSync(e,{exclude:n});for(let e of t)a(e);return}if(n.some(t=>m.default.matchesGlob(e,t)||m.default.matchesGlob(m.default.basename(e),t)))return;let t=f.default.lstatSync(e);if(t.isSymbolicLink()&&!r)this.logger.warn(`${A.TAG} Skipping symlink: ${e}`);else if((t.isSymbolicLink()?f.default.statSync(e):t).isDirectory()){let t=f.default.readdirSync(e).map(t=>m.default.join(e,t));for(let e of t)a(e)}else i.push(e)};for(let t of e)a(t);return i}async getListFiles(e){let t=[],n;try{do{let r=n?{...e,pageToken:n}:{...e},{data:i}=await K(()=>this.drive.files.list(r),this.retryOptions);i.files?.length&&t.push(...i.files),n=i.nextPageToken??void 0}while(n);return this.parseFilesMeta(t)}catch(e){throw this.genericError(e)}}async replaceExistingFile(e,t,n){let r=await this.findFile(t,n);if(r){if(!e)throw Error(`${A.TAG} File "${t}" already exists and will not be replaced`);this.logger.warn(`${A.TAG} File "${t}" already exists and will be deleted before upload`),await this.deleteFile(r)}}async getUploadFolderId(e,t,n,r=!1){if(e&&typeof e==`string`){let i=await this.findFolderId(e,t&&!r);return n.parents=[i],i}return this.sharedDriveId&&(n.parents=[this.sharedDriveId]),``}async deleteOlder(e,t,n,r={}){let i=r.dryRun??this.defaultDryRun,a=Math.max(0,r.keepLast??0),o=r.concurrency??this.defaultConcurrency,s=(0,h.default)().subtract(e,t),c=[`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`];n&&c.push(`'${Z(n)}' in parents`),a===0&&c.push(`createdTime <= '${s.toISOString()}'`);let l=(await this.listFiles(void 0,1e3,c.join(` and `))).filter(e=>!e.isDeleted&&!e.isFolder).filter(e=>!n||!!e.parents?.includes(n)).sort((e,t)=>{let n=e.createdTime?(0,h.default)(e.createdTime).valueOf():0;return(t.createdTime?(0,h.default)(t.createdTime).valueOf():0)-n}),u=(a>0?l.slice(a):l).filter(e=>e.createdTime&&(0,h.default)(e.createdTime).isSameOrBefore(s));if(i){for(let e of u)this.logger.info(`${A.TAG} [dry-run] Would delete file: ${e.name??e.id??`unknown`}`);return u}return await $(u,o,async e=>{await this.deleteFile(e)}),u}parseFileMeta(e){return{...e,isDeleted:this.isDeleted(e),isFolder:!!this.isFolder(e)}}parseFilesMeta(e){return e.map(e=>this.parseFileMeta(e))}genericError(e){return this.logger.error(`${A.TAG} The API returned an error: ${String(e)}`),e}inFlightFolders=new Map;findFolderId(e,t=!1){let n=`${e}::${t}`,r=this.inFlightFolders.get(n);if(r)return r;let i=this.resolveFolderId(e,t).finally(()=>{this.inFlightFolders.delete(n)});return this.inFlightFolders.set(n,i),i}async resolveFolderId(e,t=!1){let n=e.split(`/`).map(e=>e.trim()).filter(Boolean);if(n.length===0)throw Error(`${A.TAG} Invalid folder path "${e}"`);let r=this.rootParentId;for(let i of n){let n=[`name = '${Z(i)}'`,`mimeType = '${this.MIME_FOLDER}'`,`trashed = false`,`'${Z(r)}' in parents`].join(` and `),a=(await this.listFiles(void 0,100,n)).find(e=>e.isFolder&&!e.isDeleted&&e.name===i&&e.id);if(a?.id)r=a.id;else if(t){let e=await this.createFolder(i,r);if(!e.id)throw Error(`${A.TAG} Failed to create folder "${i}"`);r=e.id}else throw Error(`${A.TAG} Folder "${e}" does not exist and will not be created`)}return r}async findFile(e,t){let n=t||this.rootParentId,r=[`name = '${Z(e)}'`,`mimeType != '${this.MIME_FOLDER}'`,`trashed = false`,`'${Z(n)}' in parents`].join(` and `);return(await this.listFiles(void 0,100,r)).find(n=>!n.isFolder&&!n.isDeleted&&n.name===e&&(!t||!!n.parents?.includes(t)))??null}async createFolder(e,t){let n={name:e,mimeType:this.MIME_FOLDER};t&&t!==`root`&&(n.parents=[t]);try{let{data:t}=await K(()=>this.drive.files.create({requestBody:n,fields:`id`,...this.sharedDriveItemParams}),this.retryOptions);return t?.id&&this.logger.warn(`${A.TAG} Created folder "${e}" with id: "${t.id}"`),t}catch(e){throw this.genericError(e)}}createPrivateTempDir(){let e=f.default.mkdtempSync(m.default.join(p.default.tmpdir(),`node-gdrive-`));return f.default.chmodSync(e,448),e}sanitizeFilename(e){let t=m.default.basename(e);if(!t||t===`.`||t===`..`)throw Error(`${A.TAG} Invalid output filename: "${e}"`);return t}compressFiles(e,t,n={}){let r=this.sanitizeFilename(t),i=this.createPrivateTempDir(),a=m.default.join(i,r),o=n.compressionLevel??this.defaultCompressionLevel,s=n.followSymlinks??!1;return new Promise((t,n)=>{let r=f.default.createWriteStream(a,{mode:384}),c=[],l=!1,u=e=>{if(!l){l=!0;for(let e of c)e.destroy();r.destroy(),f.default.rmSync(i,{recursive:!0,force:!0}),n(e instanceof Error?e:Error(String(e)))}},d=new y.ZipArchive({zlib:{level:o}});r.on(`error`,e=>{u(e)}),r.on(`close`,()=>{l||(l=!0,t({zipPath:a,tempDir:i}))}),d.on(`warning`,e=>{this.logger.warn(`${A.TAG} Warning compressing file`,e),e.code!==`ENOENT`&&u(e)}),d.on(`error`,e=>{this.logger.error(`${A.TAG} Error compressing file`,e),u(e)}),d.pipe(r);try{for(let t of e){let e=f.default.lstatSync(t);if(e.isSymbolicLink()&&!s)this.logger.warn(`${A.TAG} Skipping symlink: ${t}`);else if((e.isSymbolicLink()?f.default.statSync(t):e).isDirectory())d.directory(t,m.default.basename(t));else{let e=m.default.basename(t),n=f.default.createReadStream(t);n.on(`error`,e=>{u(e)}),d.append(n,{name:e}),c.push(n)}}}catch(e){u(e);return}d.finalize().catch(e=>{u(e)}).finally(()=>{for(let e of c)e.destroy()})})}};function ne(e){return e?{info:()=>{},warn:()=>{},error:(...e)=>console.error(...e)}:console}var re=class{opts;logger;gdrive;constructor(e,t,n){this.opts=e;let r=!!(e.quiet||e.json);this.logger=n??ne(r),this.gdrive=t??new te({sharedDriveId:e[`drive-id`],serviceAccountFile:e[`service-account`],dryRun:e[`dry-run`],logger:this.logger})}getEncryptionKey(){if(!this.opts.encrypt)return;let e=A.BACKUP_ENCRYPTION_KEY;if(!e)throw Error(`${A.TAG} --encrypt requires BACKUP_ENCRYPTION_KEY environment variable to be set.`);return e}async parseOptions(e=process.stdin){if(this.opts.version){console.info(E());return}if(this.opts.help||Object.keys(this.opts).length===0){console.info(D());return}let t=this.opts.zip,n=this.opts.folder,r=this.opts.replace,i=this.opts.create,a=this.opts[`dry-run`],o=this.opts.exclude;this.opts.list&&await this.showList(),this.opts.backup&&await this.backup(this.opts.backup,{zip:t,folder:n,replace:r,create:i,dryRun:a,exclude:o}),this.opts.stdin&&await this.uploadFromStdin(e,this.opts.name,{folder:n,replace:r,create:i,dryRun:a}),this.opts.download&&await this.download(this.opts.download,this.opts.output,n),this.opts.delete&&await this.delete(this.opts.delete,n,{dryRun:a,keepLast:this.opts[`keep-last`]}),this.opts.mysql&&await this.dumpMysql({zip:t,folder:n,replace:r,create:i,dryRun:a})}async showList(){let e=(await this.gdrive.listFiles()).filter(e=>!e.isDeleted);return this.opts.json?(console.info(JSON.stringify(e,null,2)),e):(e.length?(this.logger.info(`${A.TAG} File list: ${e.length}`),this.beautifulFiles(e)):this.logger.info(`${A.TAG} No files found.`),e)}async delete(e,t,n={}){let r=(Array.isArray(e)?e:[e]).map(e=>{let n=this.parseDelete(e);return{folder:n.folder??t??void 0,timeSpace:n.timeSpace}}),i=[];for(let e of r){let t=await this.gdrive.cleanOlder(e.timeSpace,e.folder,{dryRun:n.dryRun,keepLast:n.keepLast});i.push(...t)}return this.opts.json&&console.info(JSON.stringify(i,null,2)),i}async backup(e,t){let{zip:n,folder:r,replace:i,create:a,dryRun:o,exclude:s}=t,c=this.getEncryptionKey(),l=Array.isArray(e)?e:[e],u=await this.gdrive.uploadFiles(l,r||!1,{compress:n||n===null,replace:i,create:a,dryRun:o,encryptKey:c,exclude:s});return this.opts.json&&console.info(JSON.stringify(u,null,2)),u}async uploadFromStdin(e,t,n){let r=this.getEncryptionKey(),i=await this.gdrive.uploadStream(e,t,n.folder||!1,{replace:n.replace,create:n.create,dryRun:n.dryRun,encryptKey:r});return this.opts.json&&console.info(JSON.stringify(i,null,2)),i}async download(e,t,n){let r=this.getEncryptionKey(),i=r&&e.endsWith(`.enc`)?e.slice(0,-4):m.default.basename(e),a=t??i,o=await this.gdrive.downloadFile(e,a,{decryptKey:r,folderName:n});return this.opts.json?console.info(JSON.stringify({downloaded:o},null,2)):this.logger.info(`${A.TAG} Downloaded to ${o}`),o}async dumpMysql(e){let{dumpPath:t,tempDir:n}=await this.createDumpFile();try{return await this.backup(t,e)}finally{f.default.rmSync(n,{recursive:!0,force:!0})}}parseDelete(e){let t=e.lastIndexOf(`=`);return t>0?{folder:e.slice(0,t),timeSpace:e.slice(t+1)}:{folder:null,timeSpace:e}}beautifulFiles(e){let t=new Map;for(let n of e)n.id&&n.name&&t.set(n.id,n.name);let n=e.map(e=>{let n=e.parents?.[0];return{...e,parentFolder:n?t.get(n):void 0}});n.sort((e,t)=>{if(e.isFolder!==t.isFolder)return e.isFolder?-1:1;let n=!!e.parentFolder;return n===!!t.parentFolder?e.parentFolder&&t.parentFolder&&e.parentFolder!==t.parentFolder?e.parentFolder.localeCompare(t.parentFolder):(e.name??``).localeCompare(t.name??``):n?-1:1});for(let e of n){let t=e.isFolder?this.showFolder(e.name):e.name,n=e.parentFolder?this.showFolder(`${e.parentFolder}/`):``;this.logger.info(`${n}${t||``}`)}}showFolder(e){return e?(0,l.styleText)([`bold`,`cyan`],e):``}async createDumpFile(){let e=process.env.MYSQL_HOST||`localhost`,t=Number(process.env.MYSQL_PORT||3306),n=process.env.MYSQL_USER||``,r=process.env.MYSQL_PASSWORD||``,i=process.env.MYSQL_DATABASE||``;if(!n||!r||!i)throw Error(`${A.TAG} Missing required MySQL environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)`);let{dump:a}=await(0,g.default)({connection:{host:e,port:t,user:n,password:r,database:i}}),o=f.default.mkdtempSync(m.default.join(p.default.tmpdir(),`node-gdrive-mysql-`));f.default.chmodSync(o,448);let s=m.default.join(o,`mysqldump-${(0,h.default)().format(`YYYY-MM-DD.HHmmss`)}.sql`),c=Object.values(a).filter(e=>!!e).map(e=>e.replace(/^# /gm,`-- `)).join(`
|
|
3
3
|
|
|
4
|
-
function
|
|
5
|
-
return a && typeof a === 'object' && 'default' in a ? a.default : a;
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
var commandLineArgs = _interopDefault(require('command-line-args')), commandLineUsage = _interopDefault(require('command-line-usage')),
|
|
9
|
-
googleapis = require('googleapis'), fs = require('fs'), fs__default = _interopDefault(fs), mime = _interopDefault(require('mime-types')),
|
|
10
|
-
path2 = require('path'), path2__default = _interopDefault(path2), archiver2 = _interopDefault(require('archiver')),
|
|
11
|
-
moment2 = _interopDefault(require('moment')), glob2 = _interopDefault(require('glob')), readline2 = _interopDefault(require('readline')),
|
|
12
|
-
colors2 = _interopDefault(require('colors')), os2 = _interopDefault(require('os')), mysqldump2 = _interopDefault(require('mysqldump'));
|
|
13
|
-
const optionDefinitions = [
|
|
14
|
-
{ name: 'list', alias: 'l', multiple: !1, type: Boolean, description: 'List all files and folders' },
|
|
15
|
-
{ name: 'backup', alias: 'b', typeLabel: '{underline file*} ', defaultOption: !0, multiple: !0, type: String, description: 'Backup files' },
|
|
16
|
-
{ name: 'zip', alias: 'z', typeLabel: '{underline zipname.zip}', multiple: !1, type: String, description: 'Zip backup files' },
|
|
17
|
-
{ name: 'replace', alias: 'r', multiple: !1, type: Boolean, description: 'Replace files if already exists when backup upload' },
|
|
18
|
-
{ name: 'create', alias: 'c', multiple: !1, type: Boolean, description: 'Create destination upload folder' },
|
|
19
|
-
{ name: 'folder', alias: 'f', typeLabel: '{underline foldername}', multiple: !1, type: String, description: 'Folder name to upload file/s' },
|
|
20
|
-
{
|
|
21
|
-
name: 'delete',
|
|
22
|
-
alias: 'd',
|
|
23
|
-
typeLabel: '{underline foldername=duration} OR {underline duration}',
|
|
24
|
-
multiple: !0,
|
|
25
|
-
type: String,
|
|
26
|
-
description: 'Clean files older than duration in foldername'
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
name: 'mysql',
|
|
30
|
-
alias: 'm',
|
|
31
|
-
multiple: !1,
|
|
32
|
-
type: Boolean,
|
|
33
|
-
description: 'Mysql backup using environment variables to connect mysql server ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)'
|
|
34
|
-
},
|
|
35
|
-
{ name: 'help', alias: 'h', description: 'Print this usage guide.', type: Boolean }];
|
|
36
|
-
let options = {};
|
|
37
|
-
try {
|
|
38
|
-
options = commandLineArgs(optionDefinitions);
|
|
39
|
-
} catch (a) {
|
|
40
|
-
console.error('[-] Error:', a.message), process.exit(1);
|
|
41
|
-
}
|
|
42
|
-
if (options.help || !Object.keys(options).length) {
|
|
43
|
-
const a = 'node-gdrive', d = [
|
|
44
|
-
{ header: `Help for ${a}`, content: `Usage of npm {italic ${a}} in command line.` }, { header: 'Options', optionList: optionDefinitions }, {
|
|
45
|
-
header: 'Examples', content: [
|
|
46
|
-
{ desc: '1. List files.', example: `$ ${a} -l` },
|
|
47
|
-
{ desc: '2. Backup multiple files to "backupFolder" folder.', example: `$ ${a} -b src/index.ts -b images/logo.png -f backupFolder` },
|
|
48
|
-
{ desc: '3. Backup files using wildcard to "backup" folder.', example: `$ ${a} -b src/* -b images/* -f backup` },
|
|
49
|
-
{
|
|
50
|
-
desc: `4. Backup files using wildcard and zip into "zipped" folder, folder will be created if it doesn't exists.`,
|
|
51
|
-
example: `$ ${a} -b src/* -b images/* -z -f zipped.zip -c`
|
|
52
|
-
},
|
|
53
|
-
{
|
|
54
|
-
desc: `5. Backup files using wildcard and zip using "allfiles.zip" as filename into "zipped" folder, folder will be created if it doesn't exists and zipfile will be replaced if it exists`,
|
|
55
|
-
example: `$ ${a} -b src/* -b images/* -z allfiles.zip -f zipped -c -r`
|
|
56
|
-
},
|
|
57
|
-
{
|
|
58
|
-
desc: '6. Delete files in "uploads" folder older than 2days and files in "monthly" folder older than 1month',
|
|
59
|
-
example: `$ ${a} -d uploads=2d -d monthly=1M`
|
|
60
|
-
},
|
|
61
|
-
{ desc: '7. Delete files in "uploads" folder older than 1minute', example: `$ ${a} -f uploads -d 1m` },
|
|
62
|
-
{ desc: '8. Generate mysql dump file zip it and upload to "mysql-backup" folder', example: `$ ${a} -f mysql-backup -m -z` }]
|
|
63
|
-
}];
|
|
64
|
-
console.info(commandLineUsage(d)), process.exit(0);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
class Config {
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
Config.TOKEN_FILE = process.env.TOKEN_FILE || './secrets/token.json', Config.CREDENTIALS_FILE = process.env.CREDENTIALS_FILE ||
|
|
71
|
-
'./secrets/credentials.json', Config.TAG = '[node-gdrive]';
|
|
72
|
-
|
|
73
|
-
class FileUtils {
|
|
74
|
-
static mkdirp(a) {
|
|
75
|
-
const d = path2.sep, b = path2.isAbsolute(a) ? d : '', c = a.split(d).reduce((f, i) => {
|
|
76
|
-
const g = path2.resolve(f, i);
|
|
77
|
-
return fs.existsSync(g) || fs.mkdirSync(g), g;
|
|
78
|
-
}, b);
|
|
79
|
-
console.info(`${Config.TAG} Result file ${c}`);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
var __async = (a, d, b) => new Promise((c, f) => {
|
|
84
|
-
var i = e => {
|
|
85
|
-
try {
|
|
86
|
-
j(b.next(e));
|
|
87
|
-
} catch (h) {
|
|
88
|
-
f(h);
|
|
89
|
-
}
|
|
90
|
-
}, g = e => {
|
|
91
|
-
try {
|
|
92
|
-
j(b.throw(e));
|
|
93
|
-
} catch (h) {
|
|
94
|
-
f(h);
|
|
95
|
-
}
|
|
96
|
-
}, j = e => e.done ? c(e.value) : Promise.resolve(e.value).then(i, g);
|
|
97
|
-
j((b = b.apply(a, d)).next());
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
class Auth {
|
|
101
|
-
constructor() {
|
|
102
|
-
this.ready = !0, this.SCOPES = [
|
|
103
|
-
'https://www.googleapis.com/auth/drive',
|
|
104
|
-
'https://www.googleapis.com/auth/drive.file',
|
|
105
|
-
'https://www.googleapis.com/auth/drive.metadata',
|
|
106
|
-
'https://www.googleapis.com/auth/drive.metadata.readonly'], this.TOKEN_FILE = Config.TOKEN_FILE, this.CREDENTIALS_FILE = Config.CREDENTIALS_FILE, this.existsCredentials ||
|
|
107
|
-
(this.ready = !1, console.error(colors2.bold(`${Config.TAG} ERROR: Credentials file not found in ${this.CREDENTIALS_FILE}`).red));
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
get existsToken() {
|
|
111
|
-
return fs.existsSync(this.TOKEN_FILE);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
get existsCredentials() {
|
|
115
|
-
return fs.existsSync(this.CREDENTIALS_FILE);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
initiate() {
|
|
119
|
-
return __async(this, [], function* () {
|
|
120
|
-
return this.ready ? this.existsToken ? Promise.resolve(!0) : this.generateAccessToken() : Promise.reject(!1);
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
oAuth2Client(a = !0) {
|
|
125
|
-
if (!this._oAuth2Client) {
|
|
126
|
-
const d = JSON.parse(fs.readFileSync(this.CREDENTIALS_FILE, 'utf8')), { client_secret: b, client_id: c, redirect_uris: f } = d.installed;
|
|
127
|
-
this._oAuth2Client = new googleapis.google.auth.OAuth2(c, b, f[0]);
|
|
128
|
-
if (a) {
|
|
129
|
-
const i = JSON.parse(fs.readFileSync(this.TOKEN_FILE, 'utf8'));
|
|
130
|
-
this._oAuth2Client.setCredentials(i);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
return this._oAuth2Client;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
generateAccessToken() {
|
|
137
|
-
return new Promise((a, d) => {
|
|
138
|
-
const b = this.oAuth2Client(!1).generateAuthUrl({ access_type: 'offline', scope: this.SCOPES });
|
|
139
|
-
console.log(`${Config.TAG} Authorize this app by visiting this url:`, b);
|
|
140
|
-
const c = readline2.createInterface({ input: process.stdin, output: process.stdout });
|
|
141
|
-
c.question(`${Config.TAG} Enter the code from that page here: `, f => {
|
|
142
|
-
c.close(), this.oAuthGetToken(f, { resolve: a, reject: d });
|
|
143
|
-
});
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
oAuthGetToken(a, d) {
|
|
148
|
-
this.oAuth2Client(!1).getToken(a).then(({ tokens: b }) => {
|
|
149
|
-
this.oAuth2Client(!1).setCredentials(b), this.writeToken(b, d);
|
|
150
|
-
}).catch(b => (console.error(colors2.bold(`${Config.TAG} Error retrieving access token`).red, b.message), d.reject(b)));
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
writeToken(a, { resolve: d, reject: b }) {
|
|
154
|
-
fs.writeFile(this.TOKEN_FILE, JSON.stringify(a), c => {
|
|
155
|
-
c ? (console.error(c), void b(c)) : (console.log(`${Config.TAG} Token stored to`, this.TOKEN_FILE), void d(!0));
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
var Params$Resource$Files$Get = googleapis.drive_v3.Params$Resource$Files$Get,
|
|
161
|
-
Params$Resource$Files$List = googleapis.drive_v3.Params$Resource$Files$List,
|
|
162
|
-
Params$Resource$Files$Create = googleapis.drive_v3.Params$Resource$Files$Create;
|
|
163
|
-
const allFileTypes = [
|
|
164
|
-
'appProperties',
|
|
165
|
-
'capabilities',
|
|
166
|
-
'contentHints',
|
|
167
|
-
'createdTime',
|
|
168
|
-
'description',
|
|
169
|
-
'explicitlyTrashed',
|
|
170
|
-
'fileExtension',
|
|
171
|
-
'folderColorRgb',
|
|
172
|
-
'fullFileExtension',
|
|
173
|
-
'hasAugmentedPermissions',
|
|
174
|
-
'hasThumbnail',
|
|
175
|
-
'headRevisionId',
|
|
176
|
-
'iconLink',
|
|
177
|
-
'id',
|
|
178
|
-
'imageMediaMetadata',
|
|
179
|
-
'isAppAuthorized',
|
|
180
|
-
'lastModifyingUser',
|
|
181
|
-
'md5Checksum',
|
|
182
|
-
'mimeType',
|
|
183
|
-
'modifiedByMe',
|
|
184
|
-
'modifiedByMeTime',
|
|
185
|
-
'modifiedTime',
|
|
186
|
-
'name',
|
|
187
|
-
'originalFilename',
|
|
188
|
-
'ownedByMe',
|
|
189
|
-
'owners',
|
|
190
|
-
'parents',
|
|
191
|
-
'properties',
|
|
192
|
-
'quotaBytesUsed',
|
|
193
|
-
'shared',
|
|
194
|
-
'sharedWithMeTime',
|
|
195
|
-
'sharingUser',
|
|
196
|
-
'size',
|
|
197
|
-
'spaces',
|
|
198
|
-
'starred',
|
|
199
|
-
'teamDriveId',
|
|
200
|
-
'thumbnailLink',
|
|
201
|
-
'thumbnailVersion',
|
|
202
|
-
'trashed',
|
|
203
|
-
'trashedTime',
|
|
204
|
-
'trashingUser',
|
|
205
|
-
'version',
|
|
206
|
-
'videoMediaMetadata',
|
|
207
|
-
'viewedByMe',
|
|
208
|
-
'viewedByMeTime',
|
|
209
|
-
'viewersCanCopyContent',
|
|
210
|
-
'webContentLink',
|
|
211
|
-
'webViewLink',
|
|
212
|
-
'writersCanShare'];
|
|
213
|
-
var __assign = Object.assign, __async$1 = (a, d, b) => new Promise((c, f) => {
|
|
214
|
-
var i = e => {
|
|
215
|
-
try {
|
|
216
|
-
j(b.next(e));
|
|
217
|
-
} catch (h) {
|
|
218
|
-
f(h);
|
|
219
|
-
}
|
|
220
|
-
}, g = e => {
|
|
221
|
-
try {
|
|
222
|
-
j(b.throw(e));
|
|
223
|
-
} catch (h) {
|
|
224
|
-
f(h);
|
|
225
|
-
}
|
|
226
|
-
}, j = e => e.done ? c(e.value) : Promise.resolve(e.value).then(i, g);
|
|
227
|
-
j((b = b.apply(a, d)).next());
|
|
228
|
-
});
|
|
229
|
-
|
|
230
|
-
class GDrive {
|
|
231
|
-
constructor() {
|
|
232
|
-
this.DEFAULT_FIELDS = [
|
|
233
|
-
'createdTime',
|
|
234
|
-
'id',
|
|
235
|
-
'md5Checksum',
|
|
236
|
-
'mimeType',
|
|
237
|
-
'name',
|
|
238
|
-
'parents',
|
|
239
|
-
'trashed'], this.MIME_FOLDER = 'application/vnd.google-apps.folder', this.gdriveAuth = new Auth(), this.initiated = this.gdriveAuth.initiate(), this.initiated.catch(
|
|
240
|
-
() => {
|
|
241
|
-
const a = `${Config.TAG} ERROR! could not get credentials file. GDrive will not work`;
|
|
242
|
-
throw console.error(a), new Error(a);
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
get auth() {
|
|
247
|
-
return this.gdriveAuth.oAuth2Client(!0);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
get drive() {
|
|
251
|
-
return googleapis.google.drive({ version: 'v3', auth: this.auth });
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
isFolder(a) {
|
|
255
|
-
return Object.prototype.hasOwnProperty.call(a, 'mimeType') ? a.mimeType === this.MIME_FOLDER : void 0;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
isDeleted(a) {
|
|
259
|
-
return Object.prototype.hasOwnProperty.call(a, 'trashed') ? !!a.trashed : !1;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
listFiles(a, d = 50) {
|
|
263
|
-
return __async$1(this, [], function* () {
|
|
264
|
-
yield this.initiated, a ? a === !0 && (a = allFileTypes) : a = this.DEFAULT_FIELDS;
|
|
265
|
-
const b = { pageSize: d, fields: `kind, nextPageToken, incompleteSearch, files(${a.join(', ')})`, prettyPrint: !0, includeTeamDriveItems: !1 };
|
|
266
|
-
return this.getListFiles(b);
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
getFile(a) {
|
|
271
|
-
return __async$1(this, [], function* () {
|
|
272
|
-
yield this.initiated;
|
|
273
|
-
if (!a) return Promise.reject(this.genericError(new Error('File id not found')));
|
|
274
|
-
const d = { fileId: a }, b = this.drive.files.get(d).then(({ data: c }) => c);
|
|
275
|
-
return b.catch(c => {
|
|
276
|
-
this.genericError(c);
|
|
277
|
-
}), b;
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
emptyTrash() {
|
|
282
|
-
return __async$1(this, [], function* () {
|
|
283
|
-
return yield this.initiated, this.drive.files.emptyTrash();
|
|
284
|
-
});
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
deleteFile(a) {
|
|
288
|
-
return __async$1(this, [], function* () {
|
|
289
|
-
yield this.initiated;
|
|
290
|
-
if (a.id) {
|
|
291
|
-
const d = this.drive.files.delete({ fileId: a.id })
|
|
292
|
-
.then(({ data: b }) => (a.name && console.warn(`${Config.TAG} Deleted ${a.isFolder ? 'folder' : 'file'}: ${a.name}`), b));
|
|
293
|
-
return d.catch(b => {
|
|
294
|
-
this.genericError(b);
|
|
295
|
-
}), d;
|
|
296
|
-
}
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
uploadFile(a, d, b = {}) {
|
|
301
|
-
return __async$1(this, [], function* () {
|
|
302
|
-
yield this.initiated;
|
|
303
|
-
const { create: c = !0, replace: f = !1 } = b, i = path2__default.basename(a), g = mime.contentType(i) || void 0, j = { name: i, mimeType: g };
|
|
304
|
-
let e = null;
|
|
305
|
-
try {
|
|
306
|
-
e = yield this.getUploadFolderId(d || !1, c, j);
|
|
307
|
-
} catch (k) {
|
|
308
|
-
return Promise.reject(k);
|
|
309
|
-
}
|
|
310
|
-
try {
|
|
311
|
-
yield this.replaceExistingFolder(f, i, e);
|
|
312
|
-
} catch (k) {
|
|
313
|
-
return Promise.reject(k);
|
|
314
|
-
}
|
|
315
|
-
const h = fs__default.createReadStream(a), l = { requestBody: j, media: { body: h }, fields: `kind, ${this.DEFAULT_FIELDS.join(', ')}` },
|
|
316
|
-
m = fs__default.statSync(a).size, p = k => {
|
|
317
|
-
const o = k.bytesRead / m * 100;
|
|
318
|
-
o === 100 && console.warn(`${Config.TAG} Upload ${i}: ${Math.round(o)}% complete`);
|
|
319
|
-
}, n = this.drive.files.create(l, { onUploadProgress: p }).then(({ data: k }) => this.parseFileMeta(k)).finally(() => {
|
|
320
|
-
h.destroy();
|
|
321
|
-
});
|
|
322
|
-
return n.catch(k => {
|
|
323
|
-
this.genericError(k);
|
|
324
|
-
}), n;
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
uploadFiles(a, d, b = {}) {
|
|
329
|
-
return __async$1(this, [], function* () {
|
|
330
|
-
yield this.initiated;
|
|
331
|
-
const { compress: c, replace: f, create: i } = b;
|
|
332
|
-
Array.isArray(a) || (a = [a]);
|
|
333
|
-
let g = a;
|
|
334
|
-
if (c) {
|
|
335
|
-
let e = c;
|
|
336
|
-
typeof e !== 'string' && (e = `zipped_${moment2().format('YYYY-MM-DD.HHmmss')}.zip`);
|
|
337
|
-
const h = yield this.compressFiles(a, e);
|
|
338
|
-
g = [h];
|
|
339
|
-
}
|
|
340
|
-
const j = {};
|
|
341
|
-
for (const e of g) if (e.includes('*')) yield this.uploadFiles(glob2.sync(e), d, b); else if (fs__default.lstatSync(e)
|
|
342
|
-
.isDirectory()) yield this.uploadFiles(glob2.sync(`${e}/*`), d, b); else {
|
|
343
|
-
const h = path2__default.basename(e), l = yield this.uploadFile(e, d, { replace: f, create: i });
|
|
344
|
-
j[h] = this.parseFileMeta(l);
|
|
345
|
-
}
|
|
346
|
-
return j;
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
cleanOlder(a, d) {
|
|
351
|
-
return __async$1(this, [], function* () {
|
|
352
|
-
const b = /([0-9]+)(\w+)/.exec(a);
|
|
353
|
-
if (!b) return console.error(`${Config.TAG} Unknown timesSpace "${a}"`), Promise.reject(!1);
|
|
354
|
-
yield this.initiated;
|
|
355
|
-
let c = '';
|
|
356
|
-
if (d) try {
|
|
357
|
-
c = yield this.findFolderId(d, !1);
|
|
358
|
-
} catch (f) {
|
|
359
|
-
return console.error('Could not find folder', d, f), Promise.reject(!1);
|
|
360
|
-
}
|
|
361
|
-
yield this.deleteOlder(b, c);
|
|
362
|
-
});
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
getListFiles(a, d = []) {
|
|
366
|
-
const b = this.drive.files.list(a).then(({ data: c }) => __async$1(this, [], function* () {
|
|
367
|
-
return d = d.concat(c.files), c.nextPageToken ? (a.pageToken = c.nextPageToken, this.getListFiles(a, d)) : d;
|
|
368
|
-
})).then(c => this.parseFilesMeta(c));
|
|
369
|
-
return b.catch(c => {
|
|
370
|
-
this.genericError(c);
|
|
371
|
-
}), b;
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
replaceExistingFolder(a, d, b) {
|
|
375
|
-
return __async$1(this, [], function* () {
|
|
376
|
-
if (a !== void 0) {
|
|
377
|
-
const c = yield this.findFile(d, b);
|
|
378
|
-
if (c) if (a) console.warn(`${Config.TAG} File "${d}" already exists and will be deleted before upload`), yield this.deleteFile(
|
|
379
|
-
c); else throw new Error(`${Config.TAG} File "${d}" already exists and will not be replaced`);
|
|
380
|
-
}
|
|
381
|
-
});
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
getUploadFolderId(a, d, b) {
|
|
385
|
-
return __async$1(this, [], function* () {
|
|
386
|
-
let c = '';
|
|
387
|
-
if (a && typeof a === 'string') {
|
|
388
|
-
c = yield this.findFolderId(a, d === void 0 ? !0 : d);
|
|
389
|
-
if (c) b.parents = [c]; else return Promise.reject(new Error(`${Config.TAG} Folder "${a}" does not exists and will not be created`));
|
|
390
|
-
}
|
|
391
|
-
return Promise.resolve(c);
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
deleteOlder(a, d) {
|
|
396
|
-
return __async$1(this, [], function* () {
|
|
397
|
-
const b = yield this.listFiles();
|
|
398
|
-
if (b && b.length) {
|
|
399
|
-
const [, c, f] = a, i = b.filter(g => !d || d && !g.isFolder).filter(g => !d || d && g.parents && g.parents.includes(d))
|
|
400
|
-
.map(g => __assign(__assign({}, g), { toDelete: moment2(g.createdTime || void 0).isSameOrBefore(moment2().subtract(+c, f)) }))
|
|
401
|
-
.filter(g => g.toDelete);
|
|
402
|
-
if (i && i.length) for (const g of i) yield this.deleteFile(g);
|
|
403
|
-
}
|
|
404
|
-
});
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
parseFileMeta(a) {
|
|
408
|
-
return __assign(__assign({}, a), { isDeleted: this.isDeleted(a), isFolder: !!this.isFolder(a) });
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
parseFilesMeta(a) {
|
|
412
|
-
return [...a].map(d => this.parseFileMeta(d));
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
genericError(a) {
|
|
416
|
-
return console.error(`${Config.TAG} The API returned an error: ${a}`), a;
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
findFolderId(a, d = !1) {
|
|
420
|
-
return __async$1(this, [], function* () {
|
|
421
|
-
const b = (yield this.listFiles()).filter(c => c.isFolder).filter(c => !c.isDeleted).filter(c => c.name === a).map(c => c.id);
|
|
422
|
-
if (b && b.length) return Promise.resolve(b[0] || '');
|
|
423
|
-
if (d) {
|
|
424
|
-
const c = yield this.createFolder(a);
|
|
425
|
-
return Promise.resolve(c.id || '');
|
|
426
|
-
}
|
|
427
|
-
return Promise.reject(!1);
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
findFile(a, d) {
|
|
432
|
-
return __async$1(this, [], function* () {
|
|
433
|
-
const b = (yield this.listFiles()).filter(c => !c.isFolder).filter(c => !c.isDeleted).filter(c => c.name === a)
|
|
434
|
-
.filter(c => !d || c.parents && c.parents.some(f => f === d));
|
|
435
|
-
return b && b.length ? b[0] : null;
|
|
436
|
-
});
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
createFolder(a) {
|
|
440
|
-
return __async$1(this, [], function* () {
|
|
441
|
-
const d = this.drive.files.create({ requestBody: { name: a, mimeType: this.MIME_FOLDER }, fields: 'id' }).then(({ data: c }) => c);
|
|
442
|
-
d.catch(c => {
|
|
443
|
-
this.genericError(c);
|
|
444
|
-
});
|
|
445
|
-
const b = yield d;
|
|
446
|
-
return (b == null ? void 0 : b.id) && console.warn(`${Config.TAG} Created folder "${a}" with id: "${b.id}"`), b;
|
|
447
|
-
});
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
compressFiles(a, d) {
|
|
451
|
-
return new Promise((b, c) => {
|
|
452
|
-
const f = os2.tmpdir(), i = path2__default.resolve(f, d);
|
|
453
|
-
FileUtils.mkdirp(path2__default.dirname(i));
|
|
454
|
-
const g = fs__default.createWriteStream(i), j = [], e = archiver2('zip', { zlib: { level: 9 } });
|
|
455
|
-
g.on('close', () => {
|
|
456
|
-
b(i), g.destroy();
|
|
457
|
-
}), g.on('end', () => {
|
|
458
|
-
b(i), g.destroy();
|
|
459
|
-
}), e.on('warning', h => {
|
|
460
|
-
console.warn(`${Config.TAG} Warning compressing file`, h), h.code !== 'ENOENT' && c(h);
|
|
461
|
-
}), e.on('error', h => {
|
|
462
|
-
console.error(`${Config.TAG} Error compressing file`), c(h);
|
|
463
|
-
}), e.pipe(g), a.forEach(h => {
|
|
464
|
-
if (h.includes('*')) e.glob(h); else if (fs__default.lstatSync(h).isDirectory()) e.directory(h, !1); else {
|
|
465
|
-
const l = path2__default.basename(h), m = fs__default.createReadStream(h);
|
|
466
|
-
e.append(m, { name: l }), j.push(m);
|
|
467
|
-
}
|
|
468
|
-
}), e.finalize().finally(() => {
|
|
469
|
-
j.forEach(h => {
|
|
470
|
-
h.destroy();
|
|
471
|
-
});
|
|
472
|
-
});
|
|
473
|
-
});
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
var __assign$1 = Object.assign, __async$2 = (a, d, b) => new Promise((c, f) => {
|
|
478
|
-
var i = e => {
|
|
479
|
-
try {
|
|
480
|
-
j(b.next(e));
|
|
481
|
-
} catch (h) {
|
|
482
|
-
f(h);
|
|
483
|
-
}
|
|
484
|
-
}, g = e => {
|
|
485
|
-
try {
|
|
486
|
-
j(b.throw(e));
|
|
487
|
-
} catch (h) {
|
|
488
|
-
f(h);
|
|
489
|
-
}
|
|
490
|
-
}, j = e => e.done ? c(e.value) : Promise.resolve(e.value).then(i, g);
|
|
491
|
-
j((b = b.apply(a, d)).next());
|
|
492
|
-
});
|
|
493
|
-
const theme = { folder: 'cyan', error: 'red' };
|
|
494
|
-
colors2.setTheme(theme);
|
|
495
|
-
|
|
496
|
-
class Cli {
|
|
497
|
-
constructor(a = options, d = new GDrive()) {
|
|
498
|
-
this.opts = a, this.gdrive = d;
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
parseOptions() {
|
|
502
|
-
return __async$2(this, [], function* () {
|
|
503
|
-
for (const a in this.opts) if (Object.prototype.hasOwnProperty.call(this.opts, a)) {
|
|
504
|
-
const d = this.opts[a], b = this.opts.zip, c = this.opts.folder, f = this.opts.replace, i = this.opts.create;
|
|
505
|
-
switch (a) {
|
|
506
|
-
case'backup':
|
|
507
|
-
yield this.backup(d, { zip: b, folder: c, replace: f, create: i });
|
|
508
|
-
break;
|
|
509
|
-
case'delete':
|
|
510
|
-
yield this.delete(d, c);
|
|
511
|
-
break;
|
|
512
|
-
case'mysql':
|
|
513
|
-
yield this.dumpMysql({ zip: b, folder: c, replace: f, create: i });
|
|
514
|
-
break;
|
|
515
|
-
case'list':
|
|
516
|
-
yield this.showList();
|
|
517
|
-
break;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
showList() {
|
|
524
|
-
return __async$2(this, [], function* () {
|
|
525
|
-
const a = (yield this.gdrive.listFiles()).filter(d => !d.isDeleted);
|
|
526
|
-
a.length ? (console.info(`${Config.TAG} File list: ${a.length}`), this.beautifulFiles(a)) : console.info(`${Config.TAG} No files found.`);
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
delete(a, d) {
|
|
531
|
-
return __async$2(this, [], function* () {
|
|
532
|
-
Array.isArray(a) || (a = [a]);
|
|
533
|
-
const b = a.map(c => this.parseDelete(c)).map(c => (c.folder || (c.folder = d || null), __assign$1({}, c)));
|
|
534
|
-
try {
|
|
535
|
-
for (const c of b) {
|
|
536
|
-
const { folder: f, timeSpace: i } = c;
|
|
537
|
-
yield this.gdrive.cleanOlder(i, f || void 0);
|
|
538
|
-
}
|
|
539
|
-
} catch (c) {
|
|
540
|
-
console.error(`${Config.TAG} Error in delete files`);
|
|
541
|
-
}
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
backup(a, d) {
|
|
546
|
-
return __async$2(this, [], function* () {
|
|
547
|
-
const { zip: b, folder: c, replace: f, create: i } = d;
|
|
548
|
-
Array.isArray(a) || (a = [a]), yield this.gdrive.uploadFiles(a, c || !1, { compress: b || b === null, replace: f, create: i });
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
dumpMysql(a) {
|
|
553
|
-
return __async$2(this, [], function* () {
|
|
554
|
-
let d = '';
|
|
555
|
-
try {
|
|
556
|
-
d = yield this.createDumpFile();
|
|
557
|
-
} catch (b) {
|
|
558
|
-
console.error(colors2.bold[theme.error](`${Config.TAG} Error mysql ${b}`)), process.exit(-1);
|
|
559
|
-
}
|
|
560
|
-
yield this.backup(d, a);
|
|
561
|
-
});
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
parseDelete(a) {
|
|
565
|
-
let d, b;
|
|
566
|
-
const c = a.split('=');
|
|
567
|
-
return c.length > 1 ? (d = c[0], b = c[1]) : (b = a, d = null), { folder: d, timeSpace: b };
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
findFile(a, d) {
|
|
571
|
-
const b = a.find(c => c.id === d);
|
|
572
|
-
return b ? b.name : null;
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
beautifulFiles(a) {
|
|
576
|
-
const d = a.map(b => {
|
|
577
|
-
const c = b && b.parents && b.parents[0];
|
|
578
|
-
return __assign$1(__assign$1({}, b), { parentFolder: this.findFile(a, c) });
|
|
579
|
-
});
|
|
580
|
-
d.sort((b, c) => this.sortByName(b, c)), d.sort((b, c) => this.sortByParent(b, c)), d.sort((b, c) => this.sortByFolder(b, c)), d.forEach(b => {
|
|
581
|
-
const c = b.isFolder ? this.showFolder(b.name) : b.name, f = b.parentFolder ? this.showFolder(`${b.parentFolder}/`) : '';
|
|
582
|
-
console.info(`${f}${c || ''}`);
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
sortByName(a, d) {
|
|
587
|
-
return a.name && d.name ? a.name.localeCompare(d.name) : 0;
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
sortByFolder(a, d) {
|
|
591
|
-
return a.isFolder && !d.isFolder ? -1 : !a.isFolder && d.isFolder ? 1 : 0;
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
sortByParent(a, d) {
|
|
595
|
-
return a.parentFolder && d.parentFolder || !a.parentFolder && !d.parentFolder ? 0 : !a.parentFolder && d.parentFolder ? 1 : -1;
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
showFolder(a) {
|
|
599
|
-
return a ? colors2.bold[theme.folder](a) : '';
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
createDumpFile() {
|
|
603
|
-
const a = process.env.MYSQL_HOST || 'localhost', d = +(process.env.MYSQL_PORT || 3306), b = process.env.MYSQL_USER || '',
|
|
604
|
-
c = process.env.MYSQL_PASSWORD || '', f = process.env.MYSQL_DATABASE || '';
|
|
605
|
-
return (!b || !c || !f) && (console.error(`${Config.TAG} Error in mysql-dump environment variables not defined`), console.error(
|
|
606
|
-
'$MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT'), process.exit(-1)), mysqldump2(
|
|
607
|
-
{ connection: { host: a, port: d, user: b, password: c, database: f } }).then(({ dump: i }) => {
|
|
608
|
-
const g = `./files/mysqldump-${moment2().format('YYYY-MM-DD.HHmmss')}.sql`;
|
|
609
|
-
FileUtils.mkdirp(path2__default.dirname(g));
|
|
610
|
-
const j = Object.values(i).map(e => e && e.replace(/^# /gm, '-- ')).join(`
|
|
611
|
-
|
|
612
|
-
`);
|
|
613
|
-
return fs__default.writeFileSync(g, j), g;
|
|
614
|
-
});
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
var __async$3 = (a, d, b) => new Promise((c, f) => {
|
|
619
|
-
var i = e => {
|
|
620
|
-
try {
|
|
621
|
-
j(b.next(e));
|
|
622
|
-
} catch (h) {
|
|
623
|
-
f(h);
|
|
624
|
-
}
|
|
625
|
-
}, g = e => {
|
|
626
|
-
try {
|
|
627
|
-
j(b.throw(e));
|
|
628
|
-
} catch (h) {
|
|
629
|
-
f(h);
|
|
630
|
-
}
|
|
631
|
-
}, j = e => e.done ? c(e.value) : Promise.resolve(e.value).then(i, g);
|
|
632
|
-
j((b = b.apply(a, d)).next());
|
|
633
|
-
});
|
|
634
|
-
void (() => __async$3(void 0, [], function* () {
|
|
635
|
-
yield new Cli().parseOptions();
|
|
636
|
-
}))();
|
|
4
|
+
`);return f.default.writeFileSync(s,c,{mode:384}),{dumpPath:s,tempDir:o}}};async function ie(){let e=O(process.argv.slice(2));e.version?(console.info(E()),process.exitCode=0):e.help||Object.keys(e).length===0?(console.info(D()),process.exitCode=0):(await new re(e).parseOptions(),process.exitCode=0)}ie().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error((0,l.styleText)([`bold`,`red`],`[-] Error: ${t}`)),process.exitCode=1});
|