datasync-blob 1.1.29 → 1.1.31

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.
@@ -0,0 +1,509 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.DsBlob = void 0;
7
+ var _react = _interopRequireWildcard(require("react"));
8
+ var _propTypes = _interopRequireDefault(require("prop-types"));
9
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
10
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
11
+ class DsBlob extends _react.Component {
12
+ constructor(props) {
13
+ super(props);
14
+ this.state = {
15
+ hover_input: false,
16
+ hover_image: false,
17
+ data: props.data || "",
18
+ binaryData: props.binaryData || null
19
+ };
20
+ this.debugging = true;
21
+ }
22
+
23
+ //-----------------------------------------
24
+ /**
25
+ * PROTOTYPE : uploadToDatasyncCloud
26
+ * Purpose : Upload binary data to My Custom Cloud server using Datasync SncPushCloud endpoint and return the accessible URL for the uploaded file.
27
+ * @param base64Data
28
+ * @param fileName
29
+ */
30
+ uploadToDatasyncCloud = async pictureBlob => {
31
+ try {
32
+ const formData = new FormData();
33
+ let cloud_filename = pictureBlob.cloud_url_prefix.split('/').pop(); // Extract filename from cloud_url_prefix
34
+
35
+ console.log("Uploading to Datasync Cloud with filename:", cloud_filename);
36
+ formData.append('action', "syncPushCloud");
37
+ //formData.append('filename', `${CGUID()}.jpg`);
38
+ formData.append('filename', cloud_filename); // Extract filename from cloud_url_prefix
39
+
40
+ // Convert blob URL to actual binary data
41
+ let binaryString;
42
+ if (pictureBlob.isBlobUrl && pictureBlob.data.startsWith('blob:')) {
43
+ // Fetch the blob URL to get actual file content
44
+ console.log('Fetching blob URL:', pictureBlob.data);
45
+ const blobResponse = await fetch(pictureBlob.data);
46
+ const blob = await blobResponse.blob();
47
+
48
+ // Convert blob to ArrayBuffer then to Uint8Array
49
+ const arrayBuffer = await blob.arrayBuffer(); // Raw binary JPEG data
50
+ const uint8Array = new Uint8Array(arrayBuffer); // ← THIS CONTAINS THE GENUINE JPEG FILE BINARY DATA
51
+
52
+ // Convert to base64 string for transmission (chunked to avoid stack overflow)
53
+ let binaryStr = '';
54
+ const chunkSize = 8192; // Process in 8KB chunks to avoid stack overflow
55
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
56
+ const chunk = uint8Array.slice(i, i + chunkSize);
57
+ binaryStr += String.fromCharCode(...chunk);
58
+ }
59
+ binaryString = btoa(binaryStr); // ← THIS CONTAINS THE GENUINE JPEG FILE AS BASE64 STRING
60
+
61
+ console.log('Converted blob URL to binary data, size:', uint8Array.length);
62
+ } else if (Array.isArray(pictureBlob.binaryData)) {
63
+ // Convert Uint8Array or regular array to base64 string
64
+ const uint8Array = new Uint8Array(pictureBlob.binaryData);
65
+ let binaryStr = '';
66
+ const chunkSize = 8192;
67
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
68
+ const chunk = uint8Array.slice(i, i + chunkSize);
69
+ binaryStr += String.fromCharCode(...chunk);
70
+ }
71
+ binaryString = btoa(binaryStr);
72
+ } else if (pictureBlob.binaryData instanceof Uint8Array) {
73
+ // Already a Uint8Array, convert to base64
74
+ let binaryStr = '';
75
+ const chunkSize = 8192;
76
+ for (let i = 0; i < pictureBlob.binaryData.length; i += chunkSize) {
77
+ const chunk = pictureBlob.binaryData.slice(i, i + chunkSize);
78
+ binaryStr += String.fromCharCode(...chunk);
79
+ }
80
+ binaryString = btoa(binaryStr);
81
+ } else {
82
+ // Assume it's already a string
83
+ binaryString = pictureBlob.binaryData || "";
84
+ }
85
+ formData.append('binary', binaryString);
86
+ console.log("binaryString ->", binaryString.substring(0, 100) + '...'); // Log the beginning of the base64 string for debugging
87
+
88
+ const results = await fetch('http://localhost:8888/datasync-service/Sync.php', {
89
+ method: 'POST',
90
+ body: formData
91
+ });
92
+ if (!results.ok) {
93
+ throw new Error(`HTTP error! status: ${response.statusText}`);
94
+ }
95
+ let sync_push_cloud_response = await results.json();
96
+
97
+ // Try to parse as JSON
98
+ try {
99
+ if (!sync_push_cloud_response.state) throw new Error(`syncPushCloud returned error: ${sync_push_cloud_response.message}`);else console.log('syncPushCloud upload response:', sync_push_cloud_response.message);
100
+ return true; // Return true on successful upload
101
+ } catch (parseError) {
102
+ console.error('syncPushCloud : JSON parse error:', parseError);
103
+ throw new Error(`syncPushCloud raised error: ${parseError}`);
104
+ }
105
+ } catch (error) {
106
+ if (true) {
107
+ console.error('syncPushCloud upload error details:', error);
108
+ }
109
+ throw error;
110
+ }
111
+ };
112
+
113
+ //-----------------------------------------
114
+ convert_blob_picture_into_cloud_file = async pictureBlob => {
115
+ try {
116
+ console.log("Received pictureBlob in uploadPicture:cloud_url_prefix -> ", pictureBlob.cloud_url_prefix);
117
+ if (!pictureBlob || !pictureBlob.data) {
118
+ //Reset picture
119
+ this.setPicture("");
120
+ return;
121
+ }
122
+ if (pictureBlob.isBlobUrl && pictureBlob.data.startsWith('blob:') && pictureBlob.cloud_url_prefix) {
123
+ let updloadSucces = await this.uploadToDatasyncCloud(pictureBlob); // Upload the image to custom Datasync cloud
124
+ if (updloadSucces) {
125
+ //Clear the data URL to free memory since the image is now uploaded and accessible via cloud URL
126
+ if (pictureBlob.data && pictureBlob.data.startsWith('blob:')) {
127
+ URL.revokeObjectURL(pictureBlob.data);
128
+ }
129
+ this.setData(pictureBlob.cloud_url_prefix);
130
+ //inform parent component of the new cloud URL for the uploaded image
131
+ this.props.uploadPicture({
132
+ data: pictureBlob.cloud_url_prefix
133
+ });
134
+ } else {
135
+ console.error("Upload to Datasync cloud failed - no success response received");
136
+ throw new Error("Upload to Datasync cloud failed - no success response received");
137
+ }
138
+ }
139
+ } catch (error) {
140
+ console.error("Upload error:", error);
141
+ }
142
+ };
143
+
144
+ //-----------------------------------------------------------------------------------------------------------------------------------------
145
+ reduceBase64Image = e => {
146
+ let imageSource = e.path && e.path[0] || e.srcElement; //Safari compliancy
147
+
148
+ var canvas = document.createElement('canvas'),
149
+ context,
150
+ width = imageSource.width,
151
+ height = imageSource.height;
152
+ if (true || this.debugging) {
153
+ alert(`Debugging : pixel is ${width} x ${height}`);
154
+ console.log("imageSource = ", imageSource);
155
+ }
156
+ //Exact size props are set
157
+ if (this.props.width && this.props.height) {
158
+ //Check image size
159
+ if (width > this.props.width || height > this.props.height) {
160
+ let msg = `L'image est trop grande, le format requis est ${this.props.width} x ${this.props.height}`;
161
+ alert(msg);
162
+ console.error(msg);
163
+ return;
164
+ }
165
+
166
+ //Check image size
167
+ if (width < this.props.width || height < this.props.height) {
168
+ let msg = `L'image est trop petite, le format requis est ${this.props.width} x ${this.props.height}`;
169
+ alert(msg);
170
+ console.error(msg);
171
+ return;
172
+ }
173
+ }
174
+
175
+ //Max size props are set
176
+ if (this.props.maxWidth && this.props.maxHeight) {
177
+ if (width > height) {
178
+ //This is a landscape picture orientation
179
+ //Check width overflow
180
+ if (width > this.props.maxWidth) {
181
+ //Check wether resize is enabled
182
+ if (this.props.reduceImage) {
183
+ //resize picture
184
+ height *= this.props.maxWidth / width;
185
+ width = this.props.maxWidth;
186
+ } else {
187
+ let msg = `L'image est trop large ! la largeur maximale est de ${this.props.maxWidth} pixels !`;
188
+ alert(msg);
189
+ console.error(msg);
190
+ return;
191
+ }
192
+ }
193
+ } else {
194
+ //This is a portrait picture orientation
195
+ //Check height overflow
196
+ if (height > this.props.maxHeight) {
197
+ //Check resize is enabled
198
+ if (this.props.reduceImage) {
199
+ //resize picture
200
+ width *= this.props.maxHeight / height;
201
+ height = this.props.maxHeight;
202
+ } else {
203
+ let msg = `L'image est trop haute, la hauteur maximale est de ${this.props.maxHeight} pixels`;
204
+ alert(msg);
205
+ console.error(msg);
206
+ return;
207
+ }
208
+ }
209
+ }
210
+ }
211
+
212
+ //Compute jpeg compression ratio
213
+ let jpegCompressionRatio = this.props.jpegQuality && this.props.jpegQuality > 0 && this.props.jpegQuality < 1 ? this.props.jpegQuality : 1;
214
+
215
+ //Build 2d picture
216
+ canvas.width = width;
217
+ canvas.height = height;
218
+ context = canvas.getContext('2d');
219
+ context.drawImage(imageSource, 0, 0, width, height);
220
+ if (this.props.cloud_storage) {
221
+ canvas.toBlob(async blob => {
222
+ if (blob) {
223
+ console.log("Binary blob created, size:", blob.size);
224
+ if (this.debugging) console.log("jpegCompressionRatio->", jpegCompressionRatio, " blob.size = ", blob.size);
225
+
226
+ // Fallback: use blob URL for display but keep binary data
227
+ const blobUrl = URL.createObjectURL(blob);
228
+
229
+ // Convert blob to ArrayBuffer to maintain genuine binary data
230
+ const reader = new FileReader();
231
+ reader.onload = () => {
232
+ const binaryData = reader.result; // ArrayBuffer - genuine binary data
233
+ console.log("Fallback: Using binary data, size:", binaryData.byteLength);
234
+
235
+ //Call the upload callback with both blob URL for display and binary data for upload
236
+ this.convert_blob_picture_into_cloud_file({
237
+ data: blobUrl,
238
+ // For display in img tag
239
+ binaryData: binaryData,
240
+ // Genuine JPEG binary stream
241
+ cloud_url_prefix: this.props.cloud_url_prefix,
242
+ // Pass cloud URL prefix if needed for parent component
243
+ isBlobUrl: true // Flag to track blob URLs for cleanup
244
+ });
245
+ };
246
+ reader.readAsArrayBuffer(blob);
247
+ } else {
248
+ console.error("Failed to create blob from canvas");
249
+ }
250
+ }, 'image/jpeg', jpegCompressionRatio);
251
+ } else {
252
+ //Jpeg conversion
253
+
254
+ let canvasData = canvas.toDataURL('image/jpg', jpegCompressionRatio); //Jpeg conversion
255
+
256
+ if (this.debugging) console.log("jpegCompressionRatio->", jpegCompressionRatio, " canvasData.length = ", canvasData.length);
257
+ const processedData = canvasData ? canvasData : "";
258
+ this.setData(processedData);
259
+
260
+ //Keep base 64 prefix as it is
261
+ this.props.uploadPicture({
262
+ data: processedData
263
+ });
264
+ }
265
+ };
266
+
267
+ //-----------------------------------------------------------------------------------------------------------------------------------------
268
+ storeBase64ImageToImg = e => {
269
+ var DOM_image = document.createElement('img');
270
+ DOM_image.onload = this.reduceBase64Image;
271
+ console.log("storeBase64ImageToImg:e.currentTarget.result = ", e.currentTarget.result);
272
+ DOM_image.src = e.currentTarget.result;
273
+ };
274
+
275
+ //-----------------------------------------------------------------------------------------------------------------------------------------
276
+ readImageAsBase64 = async aPictureFile => {
277
+ let _reader = new FileReader();
278
+ console.log("readImageAsBase64:aPictureFile = ", aPictureFile);
279
+ _reader.onload = this.storeBase64ImageToImg;
280
+ _reader.readAsDataURL(aPictureFile); //The readAsDataURL() method of the FileReader interface is used to read the contents of the specified file's data as a base64 encoded string.
281
+ };
282
+
283
+ //-----------------------------------------------------------------------------------------------------------------------------------------
284
+ resetUpload = () => {
285
+ // Clean up any blob URLs before resetting
286
+ this.cleanupBlobUrl();
287
+ this.setData("", null);
288
+ this.props.uploadPicture({
289
+ data: "",
290
+ cloud_url_prefix: this.props.cloud_url_prefix,
291
+ isBlobUrl: false
292
+ });
293
+ //this.props.uploadPicture({data:"",cloud_url_prefix:this.props.cloud_url_prefix, isBlobUrl:true});
294
+ };
295
+
296
+ //-----------------------------------------------------------------------------------------------------------------------------------------
297
+ cleanupBlobUrl = () => {
298
+ // Only show alert if not in test environment
299
+ if (typeof jest === 'undefined') {
300
+ console.log("cleanupBlobUrl !");
301
+ }
302
+ // Revoke blob URL if it exists to prevent memory leaks
303
+ if (this.state.data && this.state.data.startsWith('blob:')) {
304
+ URL.revokeObjectURL(this.state.data);
305
+ console.log("Blob URL cleaned up:", this.state.data);
306
+ }
307
+ };
308
+
309
+ //-----------------------------------------------------------------------------------------------------------------------------------------
310
+ componentDidUpdate(prevProps) {
311
+ // Sync state with prop changes from parent
312
+ if (prevProps.data !== this.props.data) {
313
+ this.setState({
314
+ data: this.props.data || ""
315
+ });
316
+ }
317
+ if (prevProps.binaryData !== this.props.binaryData) {
318
+ this.setState({
319
+ binaryData: this.props.binaryData || null
320
+ });
321
+ }
322
+ }
323
+
324
+ //-----------------------------------------------------------------------------------------------------------------------------------------
325
+ componentWillUnmount() {
326
+ // Cleanup blob URLs when component unmounts
327
+ this.cleanupBlobUrl();
328
+ }
329
+
330
+ //-----------------------------------------------------------------------------------------------------------------------------------------
331
+ onInputChange = e => {
332
+ const errs = [];
333
+ const files = Array.from(e.target.files);
334
+ const types = ['image/png', 'image/jpeg', 'image/gif'];
335
+ const _1Mo = 1024 * 1024;
336
+ const SizeLimit = 9;
337
+
338
+ //Reset input cache value - to assure trigger if user select the same file again
339
+ e.target.value = null;
340
+ if (this.debugging) console.log("onInputChange");
341
+ if (files.length > 1) {
342
+ const msg = 'Pas plus d\'une image à la fois';
343
+ alert(msg);
344
+ return;
345
+ }
346
+ files.forEach((file, i) => {
347
+ let errCount = errs.length;
348
+ if (types.every(type => file.type !== type)) {
349
+ errs.push(`'${file.type}' : format non supporté`);
350
+ }
351
+ if (file.size > SizeLimit * _1Mo) {
352
+ errs.push(`'${file.name}' image trop volumineuse (max:${SizeLimit}Méga-octets)`);
353
+ }
354
+ if (this.debugging) console.log(`errCount = ${errCount} vs errs.length = ${errs.length}`);
355
+ if (errCount == errs.length) {
356
+ //None new error occurs
357
+ if (this.debugging) console.log("readImageAsBase64::", file.name);
358
+ this.readImageAsBase64(file);
359
+ }
360
+ });
361
+ if (errs.length) {
362
+ return errs.forEach(err => alert(err));
363
+ }
364
+ };
365
+
366
+ //-----------------------------------------------------------------------------------------------------------------------------------------
367
+ getImageSrc = () => {
368
+ if (!this.state.data) return "";
369
+
370
+ // Check if it's already a complete URL (cloud storage URL or blob URL)
371
+ if (this.state.data.startsWith('http://') || this.state.data.startsWith('https://') || this.state.data.startsWith('blob:')) {
372
+ return this.state.data;
373
+ }
374
+
375
+ // Check if it's already a data URL (base64)
376
+ if (this.state.data.startsWith('data:')) {
377
+ return this.state.data;
378
+ }
379
+
380
+ // Otherwise, treat as base64 and add appropriate prefix
381
+ return this.state.data;
382
+ };
383
+
384
+ //-----------------------------------------------------------------------------------------------------------------------------------------
385
+ getBinaryData = () => {
386
+ // Return the genuine JPEG binary stream (ArrayBuffer)
387
+ // This can be used by parent components for uploading or processing
388
+ return this.state.binaryData || this.props.binaryData || null;
389
+ };
390
+
391
+ //-----------------------------------------------------------------------------------------------------------------------------------------
392
+ // Data getter and setter methods for read-write access
393
+ getData = () => {
394
+ return this.state.data;
395
+ };
396
+ setData = (data, binaryData = null) => {
397
+ this.setState({
398
+ data: data || "",
399
+ binaryData: binaryData
400
+ });
401
+ };
402
+
403
+ //-----------------------------------------------------------------------------------------------------------------------------------------
404
+ getImageType = () => {
405
+ // Return the type of image data being used
406
+ if (this.props.isCloudUrl) return 'cloud';
407
+ if (this.props.isBlobUrl) return 'blob';
408
+ if (this.state.data && this.state.data.startsWith('data:')) return 'base64';
409
+ return 'unknown';
410
+ };
411
+ render() {
412
+ const upload_picture_label = {
413
+ cursor: "pointer"
414
+ };
415
+ const upload_picture_label_input = {
416
+ opacity: "0",
417
+ width: "0px",
418
+ height: "0px"
419
+ };
420
+ const div_show_image_hover = {
421
+ position: "relative",
422
+ margin: "0px",
423
+ opacity: "0.5"
424
+ };
425
+ const div_show_image = {
426
+ position: "relative",
427
+ margin: "0px"
428
+ };
429
+ const div_show_image_hover_input = {
430
+ display: "block",
431
+ top: "0px",
432
+ left: "0px",
433
+ position: "absolute"
434
+ };
435
+ const div_show_image_input = {
436
+ position: "absolute",
437
+ display: "none",
438
+ cursor: "pointer"
439
+ };
440
+ return /*#__PURE__*/_react.default.createElement("div", null, !this.state.data && /*#__PURE__*/_react.default.createElement("label", {
441
+ id: "upload-picture-label",
442
+ className: this.props.buttonStyle,
443
+ style: upload_picture_label
444
+ }, this.props.Caption, /*#__PURE__*/_react.default.createElement("input", {
445
+ style: upload_picture_label_input,
446
+ id: "nested-input",
447
+ type: "file",
448
+ accept: "image/*",
449
+ onChange: this.onInputChange,
450
+ multiple: true
451
+ })), this.state.data && this.state.data.length > 0 && /*#__PURE__*/_react.default.createElement("div", {
452
+ class: "show-image",
453
+ style: div_show_image,
454
+ onMouseOver: () => {
455
+ this.setState({
456
+ hover_input: true,
457
+ hover_image: true
458
+ }, () => {
459
+ if (this.debugging) console.log("onMouseOver");
460
+ });
461
+ },
462
+ onMouseLeave: () => {
463
+ this.setState({
464
+ hover_input: false,
465
+ hover_image: false
466
+ }, () => {
467
+ if (this.debugging) console.log("onMouseLeave");
468
+ });
469
+ }
470
+ }, /*#__PURE__*/_react.default.createElement("img", {
471
+ style: this.state.hover_image ? div_show_image_hover : div_show_image,
472
+ src: this.getImageSrc(),
473
+ className: this.props.pictureStyle
474
+ }), !this.props.readOnly && /*#__PURE__*/_react.default.createElement("input", {
475
+ style: this.state.hover_input ? div_show_image_hover_input : div_show_image_input,
476
+ className: "btn btn-primary delete",
477
+ type: "button",
478
+ value: "Effacer",
479
+ onClick: this.resetUpload
480
+ })));
481
+ }
482
+ }
483
+ exports.DsBlob = DsBlob;
484
+ DsBlob.propTypes = {
485
+ // Image handling props (note: data and binaryData are managed as read-write state internally)
486
+ data: _propTypes.default.string,
487
+ binaryData: _propTypes.default.object,
488
+ // Upload callback
489
+ uploadPicture: _propTypes.default.func.isRequired,
490
+ // Image size constraints
491
+ width: _propTypes.default.number,
492
+ height: _propTypes.default.number,
493
+ maxWidth: _propTypes.default.number,
494
+ maxHeight: _propTypes.default.number,
495
+ // Image processing options
496
+ reduceImage: _propTypes.default.bool,
497
+ jpegQuality: _propTypes.default.number,
498
+ // Cloud storage options
499
+ cloud_storage: _propTypes.default.bool,
500
+ cloud_url_prefix: _propTypes.default.string,
501
+ // UI props
502
+ Caption: _propTypes.default.string,
503
+ buttonStyle: _propTypes.default.string,
504
+ pictureStyle: _propTypes.default.string,
505
+ readOnly: _propTypes.default.bool,
506
+ // Status flags
507
+ isCloudUrl: _propTypes.default.bool,
508
+ isBlobUrl: _propTypes.default.bool
509
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "datasync-blob",
3
- "version": "1.1.29",
3
+ "version": "1.1.31",
4
4
  "description": "Datasync Blob component",
5
5
  "main": "./dist/components/DsBlob.js",
6
6
  "files": [