-
Notifications
You must be signed in to change notification settings - Fork 369
/
file.ts
3423 lines (3148 loc) · 109 KB
/
file.ts
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
/*!
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
BodyResponseCallback,
DecorateRequestOptions,
GetConfig,
Interceptor,
Metadata,
ServiceObject,
util,
} from '@google-cloud/common';
import {promisifyAll} from '@google-cloud/promisify';
import compressible = require('compressible');
import concat = require('concat-stream');
import * as crypto from 'crypto';
import * as dateFormat from 'date-and-time';
import * as extend from 'extend';
import * as fs from 'fs';
const hashStreamValidation = require('hash-stream-validation');
import * as mime from 'mime';
import * as once from 'onetime';
import * as os from 'os';
const pumpify = require('pumpify');
import * as resumableUpload from 'gcs-resumable-upload';
import {Duplex, Writable, Readable} from 'stream';
import * as streamEvents from 'stream-events';
import * as through from 'through2';
import * as xdgBasedir from 'xdg-basedir';
import * as querystring from 'querystring';
import * as zlib from 'zlib';
import * as url from 'url';
import * as http from 'http';
import {Storage} from './storage';
import {Bucket} from './bucket';
import {Acl} from './acl';
import {
ResponseBody,
ApiError,
Duplexify,
DuplexifyConstructor,
} from '@google-cloud/common/build/src/util';
const duplexify: DuplexifyConstructor = require('duplexify');
import {normalize, objectEntries} from './util';
import {GaxiosError, Headers, request as gaxiosRequest} from 'gaxios';
export type GetExpirationDateResponse = [Date];
export interface GetExpirationDateCallback {
(
err: Error | null,
expirationDate?: Date | null,
apiResponse?: Metadata
): void;
}
export interface GetSignedUrlConfig {
action: 'read' | 'write' | 'delete' | 'resumable';
version?: 'v2' | 'v4';
cname?: string;
contentMd5?: string;
contentType?: string;
expires: string | number | Date;
extensionHeaders?: http.OutgoingHttpHeaders;
promptSaveAs?: string;
responseDisposition?: string;
responseType?: string;
}
interface GetSignedUrlConfigInternal {
expiration: number;
method: string;
name: string;
resource?: string;
extensionHeaders?: http.OutgoingHttpHeaders;
contentMd5?: string;
contentType?: string;
promptSaveAs?: string;
responseType?: string;
responseDisposition?: string;
cname?: string;
}
export enum ActionToHTTPMethod {
read = 'GET',
write = 'PUT',
delete = 'DELETE',
resumable = 'POST',
}
export type GetSignedUrlResponse = [string];
export interface GetSignedUrlCallback {
(err: Error | null, url?: string): void;
}
export interface PolicyDocument {
expiration: string;
conditions: Array<Array<string | number>>;
string: string;
}
export type GetSignedPolicyResponse = [PolicyDocument];
export interface GetSignedPolicyCallback {
(err: Error | null, policy?: PolicyDocument): void;
}
export interface GetSignedPolicyOptions {
equals?: string[] | string[][];
expires: string | number | Date;
startsWith?: string[] | string[][];
acl?: string;
successRedirect?: string;
successStatus?: string;
contentLengthRange?: {min?: number; max?: number};
}
export interface GetFileMetadataOptions {
userProject?: string;
}
export type GetFileMetadataResponse = [Metadata, Metadata];
export interface GetFileMetadataCallback {
(err: Error | null, metadata?: Metadata, apiResponse?: Metadata): void;
}
export interface GetFileOptions extends GetConfig {
userProject?: string;
}
export type GetFileResponse = [File, Metadata];
export interface GetFileCallback {
(err: Error | null, file?: File, apiResponse?: Metadata): void;
}
export interface FileExistsOptions {
userProject?: string;
}
export type FileExistsResponse = [boolean];
export interface FileExistsCallback {
(err: Error | null, exists?: boolean): void;
}
export interface DeleteFileOptions {
userProject?: string;
}
export type DeleteFileResponse = [Metadata];
export interface DeleteFileCallback {
(err: Error | null, apiResponse?: Metadata): void;
}
export type PredefinedAcl =
| 'authenticatedRead'
| 'bucketOwnerFullControl'
| 'bucketOwnerRead'
| 'private'
| 'projectPrivate'
| 'publicRead';
export interface CreateResumableUploadOptions {
configPath?: string;
metadata?: Metadata;
origin?: string;
offset?: number;
predefinedAcl?: PredefinedAcl;
private?: boolean;
public?: boolean;
uri?: string;
userProject?: string;
}
export type CreateResumableUploadResponse = [string];
export interface CreateResumableUploadCallback {
(err: Error | null, uri?: string): void;
}
export interface CreateWriteStreamOptions extends CreateResumableUploadOptions {
contentType?: string;
gzip?: string | boolean;
resumable?: boolean;
validation?: string | boolean;
}
export interface MakeFilePrivateOptions {
strict?: boolean;
userProject?: string;
}
export type MakeFilePrivateResponse = [Metadata];
export interface MakeFilePrivateCallback extends SetFileMetadataCallback {}
export interface IsPublicCallback {
(err: Error | null, resp?: boolean): void;
}
export type IsPublicResponse = [boolean];
export type MakeFilePublicResponse = [Metadata];
export interface MakeFilePublicCallback {
(err?: Error | null, apiResponse?: Metadata): void;
}
export type MoveResponse = [Metadata];
export interface MoveCallback {
(
err: Error | null,
destinationFile?: File | null,
apiResponse?: Metadata
): void;
}
export interface MoveOptions {
userProject?: string;
}
export type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions;
export interface EncryptionKeyOptions {
encryptionKey?: string | Buffer;
kmsKeyName?: string;
}
export interface RotateEncryptionKeyCallback extends CopyCallback {}
export type RotateEncryptionKeyResponse = CopyResponse;
/**
* Custom error type for errors related to creating a resumable upload.
*
* @private
*/
class ResumableUploadError extends Error {
name = 'ResumableUploadError';
}
/**
* Custom error type for errors related to getting signed errors and policies.
*
* @private
*/
class SigningError extends Error {
name = 'SigningError';
}
/**
* @const {string}
* @private
*/
const STORAGE_DOWNLOAD_BASE_URL = 'https://storage.googleapis.com';
/**
* @const {string}
* @private
*/
const STORAGE_UPLOAD_BASE_URL =
'https://www.googleapis.com/upload/storage/v1/b';
/**
* @const {RegExp}
* @private
*/
const GS_URL_REGEXP = /^gs:\/\/([a-z0-9_.-]+)\/(.+)$/;
export interface FileOptions {
encryptionKey?: string | Buffer;
generation?: number | string;
kmsKeyName?: string;
userProject?: string;
}
export interface CopyOptions {
destinationKmsKeyName?: string;
keepAcl?: string;
predefinedAcl?: string;
token?: string;
userProject?: string;
}
export type CopyResponse = [File, Metadata];
export interface CopyCallback {
(err: Error | null, file?: File | null, apiResponse?: Metadata): void;
}
export type DownloadResponse = [Buffer];
export type DownloadCallback = (
err: RequestError | null,
contents: Buffer
) => void;
export interface DownloadOptions extends CreateReadStreamOptions {
destination?: string;
}
interface CopyQuery {
sourceGeneration?: number;
rewriteToken?: string;
userProject?: string;
destinationKmsKeyName?: string;
}
interface FileQuery {
alt: string;
generation?: number;
userProject?: string;
}
interface SignedUrlQuery {
generation?: number;
'response-content-type'?: string;
'response-content-disposition'?: string;
}
interface V2SignedUrlQuery extends SignedUrlQuery {
GoogleAccessId: string;
Expires: number;
Signature: string;
}
interface V4UrlQuery extends SignedUrlQuery {
'X-Goog-Algorithm': string;
'X-Goog-Credential': string;
'X-Goog-Date': string;
'X-Goog-Expires': number;
'X-Goog-SignedHeaders': string;
}
interface V4SignedUrlQuery extends V4UrlQuery {
'X-Goog-Signature': string;
}
export interface CreateReadStreamOptions {
userProject?: string;
validation?: 'md5' | 'crc32c' | false | true;
start?: number;
end?: number;
}
export interface SaveOptions extends CreateWriteStreamOptions {}
export interface SaveCallback {
(err?: Error | null): void;
}
export interface SetFileMetadataOptions {
userProject?: string;
}
export interface SetFileMetadataCallback {
(err?: Error | null, apiResponse?: Metadata): void;
}
export type SetFileMetadataResponse = [Metadata];
export type SetStorageClassResponse = [Metadata];
export interface SetStorageClassOptions {
userProject?: string;
}
interface SetStorageClassRequest extends SetStorageClassOptions {
storageClass?: string;
}
export interface SetStorageClassCallback {
(err?: Error | null, apiResponse?: Metadata): void;
}
class RequestError extends Error {
code?: string;
errors?: Error[];
}
type ValueOf<T> = T[keyof T];
type HeaderValue = ValueOf<http.OutgoingHttpHeaders>;
const SEVEN_DAYS = 604800;
/*
* Default signing version for getSignedUrl is 'v2'.
*/
const DEFAULT_SIGNING_VERSION = 'v2';
/**
* A File object is created from your {@link Bucket} object using
* {@link Bucket#file}.
*
* @class
*/
class File extends ServiceObject<File> {
/**
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share objects with other
* users and allow other users to access your buckets and objects.
*
* An ACL consists of one or more entries, where each entry grants permissions
* to an entity. Permissions define the actions that can be performed against
* an object or bucket (for example, `READ` or `WRITE`); the entity defines
* who the permission applies to (for example, a specific user or group of
* users).
*
* The `acl` object on a File instance provides methods to get you a list of
* the ACLs defined on your bucket, as well as set, update, and delete them.
*
* @see [About Access Control lists]{@link http://goo.gl/6qBBPO}
*
* @name File#acl
* @mixes Acl
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
* //-
* // Make a file publicly readable.
* //-
* const options = {
* entity: 'allUsers',
* role: storage.acl.READER_ROLE
* };
*
* file.acl.add(options, function(err, aclObject) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
*/
acl: Acl;
bucket: Bucket;
storage: Storage;
kmsKeyName?: string;
userProject?: string;
name: string;
generation?: number;
parent!: Bucket;
private encryptionKey?: string | Buffer;
private encryptionKeyBase64?: string;
private encryptionKeyHash?: string;
private encryptionKeyInterceptor?: Interceptor;
/**
* @typedef {object} FileOptions Options passed to the File constructor.
* @property {string} [encryptionKey] A custom encryption key.
* @property {number} [generation] Generation to scope the file to.
* @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this
* object, if the object is encrypted by such a key. Limited availability;
* usable only by enabled projects.
* @property {string} [userProject] The ID of the project which will be
* billed for all requests made from File object.
*/
/**
* Constructs a file object.
*
* @param {Bucket} bucket The Bucket instance this file is
* attached to.
* @param {string} name The name of the remote file.
* @param {FileOptions} [options] Configuration options.
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
*/
constructor(bucket: Bucket, name: string, options: FileOptions = {}) {
name = name.replace(/^\/+/, '');
const requestQueryObject: {generation?: number; userProject?: string} = {};
let generation: number;
if (options.generation != null) {
if (typeof options.generation === 'string') {
generation = Number(options.generation);
} else {
generation = options.generation;
}
if (!isNaN(generation)) {
requestQueryObject.generation = generation;
}
}
const userProject = options.userProject || bucket.userProject;
if (typeof userProject === 'string') {
requestQueryObject.userProject = userProject;
}
const methods = {
/**
* @typedef {array} DeleteFileResponse
* @property {object} 0 The full API response.
*/
/**
* @callback DeleteFileCallback
* @param {?Error} err Request error, if any.
* @param {object} apiResponse The full API response.
*/
/**
* Delete the file.
*
* @see [Objects: delete API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/delete}
*
* @method File#delete
* @param {object} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {DeleteFileCallback} [callback] Callback function.
* @returns {Promise<DeleteFileResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
* file.delete(function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.delete().then(function(data) {
* const apiResponse = data[0];
* });
*
* @example <caption>include:samples/files.js</caption>
* region_tag:storage_delete_file
* Another example:
*/
delete: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* @typedef {array} FileExistsResponse
* @property {boolean} 0 Whether the {@link File} exists.
*/
/**
* @callback FileExistsCallback
* @param {?Error} err Request error, if any.
* @param {boolean} exists Whether the {@link File} exists.
*/
/**
* Check if the file exists.
*
* @method File#exists
* @param {options} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {FileExistsCallback} [callback] Callback function.
* @returns {Promise<FileExistsResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
*
* file.exists(function(err, exists) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.exists().then(function(data) {
* const exists = data[0];
* });
*/
exists: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* @typedef {array} GetFileResponse
* @property {File} 0 The {@link File}.
* @property {object} 1 The full API response.
*/
/**
* @callback GetFileCallback
* @param {?Error} err Request error, if any.
* @param {File} file The {@link File}.
* @param {object} apiResponse The full API response.
*/
/**
* Get a file object and its metadata if it exists.
*
* @method File#get
* @param {options} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {GetFileCallback} [callback] Callback function.
* @returns {Promise<GetFileResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
*
* file.get(function(err, file, apiResponse) {
* // file.metadata` has been populated.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.get().then(function(data) {
* const file = data[0];
* const apiResponse = data[1];
* });
*/
get: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* @typedef {array} GetFileMetadataResponse
* @property {object} 0 The {@link File} metadata.
* @property {object} 1 The full API response.
*/
/**
* @callback GetFileMetadataCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The {@link File} metadata.
* @param {object} apiResponse The full API response.
*/
/**
* Get the file's metadata.
*
* @see [Objects: get API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/get}
*
* @method File#getMetadata
* @param {object} [options] Configuration options.
* @param {string} [options.userProject] The ID of the project which will be
* billed for the request.
* @param {GetFileMetadataCallback} [callback] Callback function.
* @returns {Promise<GetFileMetadataResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
*
* file.getMetadata(function(err, metadata, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.getMetadata().then(function(data) {
* const metadata = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/files.js</caption>
* region_tag:storage_get_metadata
* Another example:
*/
getMetadata: {
reqOpts: {
qs: requestQueryObject,
},
},
/**
* @typedef {object} SetFileMetadataOptions Configuration options for File#setMetadata().
* @param {string} [userProject] The ID of the project which will be billed for the request.
*/
/**
* @callback SetFileMetadataCallback
* @param {?Error} err Request error, if any.
* @param {object} apiResponse The full API response.
*/
/**
* @typedef {array} SetFileMetadataResponse
* @property {object} 0 The full API response.
*/
/**
* Merge the given metadata with the current remote file's metadata. This
* will set metadata if it was previously unset or update previously set
* metadata. To unset previously set metadata, set its value to null.
*
* You can set custom key/value pairs in the metadata key of the given
* object, however the other properties outside of this object must adhere
* to the [official API documentation](https://goo.gl/BOnnCK).
*
* NOTE: multiple calls to setMetadata in parallel might result in
* unpredictable results. See [issue]{@link
* https://github.com/googleapis/nodejs-storage/issues/274}.
*
* See the examples below for more information.
*
* @see [Objects: patch API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/patch}
*
* @method File#setMetadata
* @param {object} [metadata] The metadata you wish to update.
* @param {SetFileMetadataOptions} [options] Configuration options.
* @param {SetFileMetadataCallback} [callback] Callback function.
* @returns {Promise<SetFileMetadataResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
*
* const metadata = {
* contentType: 'application/x-font-ttf',
* metadata: {
* my: 'custom',
* properties: 'go here'
* }
* };
*
* file.setMetadata(metadata, function(err, apiResponse) {});
*
* // Assuming current metadata = { hello: 'world', unsetMe: 'will do' }
* file.setMetadata({
* metadata: {
* abc: '123', // will be set.
* unsetMe: null, // will be unset (deleted).
* hello: 'goodbye' // will be updated from 'world' to 'goodbye'.
* }
* }, function(err, apiResponse) {
* // metadata should now be { abc: '123', hello: 'goodbye' }
* });
*
* //-
* // Set a temporary hold on this file from its bucket's retention period
* // configuration.
* //
* file.setMetadata({
* temporaryHold: true
* }, function(err, apiResponse) {});
*
* //-
* // Alternatively, you may set a temporary hold. This will follow the
* // same behavior as an event-based hold, with the exception that the
* // bucket's retention policy will not renew for this file from the time
* // the hold is released.
* //-
* file.setMetadata({
* eventBasedHold: true
* }, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.setMetadata(metadata).then(function(data) {
* const apiResponse = data[0];
* });
*/
setMetadata: {
reqOpts: {
qs: requestQueryObject,
},
},
};
super({
parent: bucket,
baseUrl: '/o',
id: encodeURIComponent(name),
methods,
});
this.bucket = bucket;
// tslint:disable-next-line:no-any
this.storage = (bucket as any).parent as Storage;
// @TODO Can this duplicate code from above be avoided?
if (options.generation != null) {
let generation: number;
if (typeof options.generation === 'string') {
generation = Number(options.generation);
} else {
generation = options.generation;
}
if (!isNaN(generation)) {
this.generation = generation;
}
}
this.kmsKeyName = options.kmsKeyName;
this.userProject = userProject;
this.name = name;
if (options.encryptionKey) {
this.setEncryptionKey(options.encryptionKey);
}
this.acl = new Acl({
request: this.request.bind(this),
pathPrefix: '/acl',
});
}
copy(destination: string | Bucket | File): Promise<CopyResponse>;
copy(destination: string | Bucket | File, callback: CopyCallback): void;
copy(
destination: string | Bucket | File,
options: CopyOptions,
callback: CopyCallback
): void;
/**
* @typedef {array} CopyResponse
* @property {File} 0 The copied {@link File}.
* @property {object} 1 The full API response.
*/
/**
* @callback CopyCallback
* @param {?Error} err Request error, if any.
* @param {File} copiedFile The copied {@link File}.
* @param {object} apiResponse The full API response.
*/
/**
* @typedef {object} CopyOptions Configuration options for File#copy(). See an
* [Object
* resource](https://cloud.google.com/storage/docs/json_api/v1/objects#resource).
* @property {string} [destinationKmsKeyName] Resource name of the Cloud
* KMS key, of the form
* `projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key`,
* that will be used to encrypt the object. Overwrites the object
* metadata's `kms_key_name` value, if any.
* @property {string} [keepAcl] Retain the ACL for the new file.
* @property {string} [predefinedAcl] Set the ACL for the new file.
* @property {string} [token] A previously-returned `rewriteToken` from an
* unfinished rewrite request.
* @property {string} [userProject] The ID of the project which will be
* billed for the request.
*/
/**
* Copy this file to another file. By default, this will copy the file to the
* same bucket, but you can choose to copy it to another Bucket by providing
* a Bucket or File object or a URL starting with "gs://".
*
* @see [Objects: rewrite API Documentation]{@link https://cloud.google.com/storage/docs/json_api/v1/objects/rewrite}
*
* @throws {Error} If the destination file is not provided.
*
* @param {string|Bucket|File} destination Destination file.
* @param {CopyOptions} [options] Configuration options. See an
* @param {CopyCallback} [callback] Callback function.
* @returns {Promise<CopyResponse>}
*
* @example
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
*
* //-
* // You can pass in a variety of types for the destination.
* //
* // For all of the below examples, assume we are working with the following
* // Bucket and File objects.
* //-
* const bucket = storage.bucket('my-bucket');
* const file = bucket.file('my-image.png');
*
* //-
* // If you pass in a string for the destination, the file is copied to its
* // current bucket, under the new name provided.
* //-
* file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) {
* // `my-bucket` now contains:
* // - "my-image.png"
* // - "my-image-copy.png"
*
* // `copiedFile` is an instance of a File object that refers to your new
* // file.
* });
*
* //-
* // If you pass in a string starting with "gs://" for the destination, the
* // file is copied to the other bucket and under the new name provided.
* //-
* const newLocation = 'gs://another-bucket/my-image-copy.png';
* file.copy(newLocation, function(err, copiedFile, apiResponse) {
* // `my-bucket` still contains:
* // - "my-image.png"
* //
* // `another-bucket` now contains:
* // - "my-image-copy.png"
*
* // `copiedFile` is an instance of a File object that refers to your new
* // file.
* });
*
* //-
* // If you pass in a Bucket object, the file will be copied to that bucket
* // using the same name.
* //-
* const anotherBucket = storage.bucket('another-bucket');
* file.copy(anotherBucket, function(err, copiedFile, apiResponse) {
* // `my-bucket` still contains:
* // - "my-image.png"
* //
* // `another-bucket` now contains:
* // - "my-image.png"
*
* // `copiedFile` is an instance of a File object that refers to your new
* // file.
* });
*
* //-
* // If you pass in a File object, you have complete control over the new
* // bucket and filename.
* //-
* const anotherFile = anotherBucket.file('my-awesome-image.png');
* file.copy(anotherFile, function(err, copiedFile, apiResponse) {
* // `my-bucket` still contains:
* // - "my-image.png"
* //
* // `another-bucket` now contains:
* // - "my-awesome-image.png"
*
* // Note:
* // The `copiedFile` parameter is equal to `anotherFile`.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.copy(newLocation).then(function(data) {
* const newFile = data[0];
* const apiResponse = data[1];
* });
*
* @example <caption>include:samples/files.js</caption>
* region_tag:storage_copy_file
* Another example:
*/
copy(
destination: string | Bucket | File,
optionsOrCallback?: CopyOptions | CopyCallback,
callback?: CopyCallback
): Promise<CopyResponse> | void {
const noDestinationError = new Error(
'Destination file should have a name.'
);
if (!destination) {
throw noDestinationError;
}
let options: CopyOptions = {};
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
} else if (optionsOrCallback) {
options = optionsOrCallback;
}
options = extend(true, {}, options);
callback = callback || util.noop;
let destBucket: Bucket;
let destName: string;
let newFile: File;
if (typeof destination === 'string') {
const parsedDestination = GS_URL_REGEXP.exec(destination);
if (parsedDestination !== null && parsedDestination.length === 3) {
destBucket = this.storage.bucket(parsedDestination[1]);
destName = parsedDestination[2];