datasync-blob 1.1.29 → 1.1.30

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,510 @@
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
+ if (true || this.debugging) {
149
+ alert(`Debugging : pixel is ${width} x ${height}`);
150
+ console.log("imageSource = ", imageSource);
151
+ }
152
+ var canvas = document.createElement('canvas'),
153
+ context,
154
+ width = imageSource.width,
155
+ height = imageSource.height;
156
+
157
+ //Exact size props are set
158
+ if (this.props.width && this.props.height) {
159
+ //Check image size
160
+ if (width > this.props.width || height > this.props.height) {
161
+ let msg = `L'image est trop grande, le format requis est ${this.props.width} x ${this.props.height}`;
162
+ alert(msg);
163
+ console.error(msg);
164
+ return;
165
+ }
166
+
167
+ //Check image size
168
+ if (width < this.props.width || height < this.props.height) {
169
+ let msg = `L'image est trop petite, le format requis est ${this.props.width} x ${this.props.height}`;
170
+ alert(msg);
171
+ console.error(msg);
172
+ return;
173
+ }
174
+ }
175
+
176
+ //Max size props are set
177
+ if (this.props.maxWidth && this.props.maxHeight) {
178
+ if (width > height) {
179
+ //This is a landscape picture orientation
180
+ //Check width overflow
181
+ if (width > this.props.maxWidth) {
182
+ //Check wether resize is enabled
183
+ if (this.props.reduceImage) {
184
+ //resize picture
185
+ height *= this.props.maxWidth / width;
186
+ width = this.props.maxWidth;
187
+ } else {
188
+ let msg = `L'image est trop large ! la largeur maximale est de ${this.props.maxWidth} pixels !`;
189
+ alert(msg);
190
+ console.error(msg);
191
+ return;
192
+ }
193
+ }
194
+ } else {
195
+ //This is a portrait picture orientation
196
+ //Check height overflow
197
+ if (height > this.props.maxHeight) {
198
+ //Check resize is enabled
199
+ if (this.props.reduceImage) {
200
+ //resize picture
201
+ width *= this.props.maxHeight / height;
202
+ height = this.props.maxHeight;
203
+ } else {
204
+ let msg = `L'image est trop haute, la hauteur maximale est de ${this.props.maxHeight} pixels`;
205
+ alert(msg);
206
+ console.error(msg);
207
+ return;
208
+ }
209
+ }
210
+ }
211
+ }
212
+
213
+ //Compute jpeg compression ratio
214
+ let jpegCompressionRatio = this.props.jpegQuality && this.props.jpegQuality > 0 && this.props.jpegQuality < 1 ? this.props.jpegQuality : 1;
215
+
216
+ //Build 2d picture
217
+ canvas.width = width;
218
+ canvas.height = height;
219
+ context = canvas.getContext('2d');
220
+ context.drawImage(imageSource, 0, 0, width, height);
221
+ if (this.props.cloud_storage) {
222
+ canvas.toBlob(async blob => {
223
+ if (blob) {
224
+ console.log("Binary blob created, size:", blob.size);
225
+ if (this.debugging) console.log("jpegCompressionRatio->", jpegCompressionRatio, " blob.size = ", blob.size);
226
+
227
+ // Fallback: use blob URL for display but keep binary data
228
+ const blobUrl = URL.createObjectURL(blob);
229
+
230
+ // Convert blob to ArrayBuffer to maintain genuine binary data
231
+ const reader = new FileReader();
232
+ reader.onload = () => {
233
+ const binaryData = reader.result; // ArrayBuffer - genuine binary data
234
+ console.log("Fallback: Using binary data, size:", binaryData.byteLength);
235
+
236
+ //Call the upload callback with both blob URL for display and binary data for upload
237
+ this.convert_blob_picture_into_cloud_file({
238
+ data: blobUrl,
239
+ // For display in img tag
240
+ binaryData: binaryData,
241
+ // Genuine JPEG binary stream
242
+ cloud_url_prefix: this.props.cloud_url_prefix,
243
+ // Pass cloud URL prefix if needed for parent component
244
+ isBlobUrl: true // Flag to track blob URLs for cleanup
245
+ });
246
+ };
247
+ reader.readAsArrayBuffer(blob);
248
+ } else {
249
+ console.error("Failed to create blob from canvas");
250
+ }
251
+ }, 'image/jpeg', jpegCompressionRatio);
252
+ } else {
253
+ //Jpeg conversion
254
+
255
+ let canvasData = canvas.toDataURL('image/jpg', jpegCompressionRatio); //Jpeg conversion
256
+
257
+ if (this.debugging) console.log("jpegCompressionRatio->", jpegCompressionRatio, " canvasData.length = ", canvasData.length);
258
+ const processedData = canvasData ? canvasData : "";
259
+ this.setData(processedData);
260
+
261
+ //Keep base 64 prefix as it is
262
+ this.props.uploadPicture({
263
+ data: processedData
264
+ });
265
+ }
266
+ };
267
+
268
+ //-----------------------------------------------------------------------------------------------------------------------------------------
269
+ storeBase64ImageToImg = e => {
270
+ var DOM_image = document.createElement('img');
271
+ DOM_image.onload = this.reduceBase64Image;
272
+ console.log("storeBase64ImageToImg:e.currentTarget.result = ", e.currentTarget.result);
273
+ DOM_image.src = e.currentTarget.result;
274
+ };
275
+
276
+ //-----------------------------------------------------------------------------------------------------------------------------------------
277
+ readImageAsBase64 = async aPictureFile => {
278
+ let _reader = new FileReader();
279
+ console.log("readImageAsBase64:aPictureFile = ", aPictureFile);
280
+ _reader.onload = this.storeBase64ImageToImg;
281
+ _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.
282
+ };
283
+
284
+ //-----------------------------------------------------------------------------------------------------------------------------------------
285
+ resetUpload = () => {
286
+ // Clean up any blob URLs before resetting
287
+ this.cleanupBlobUrl();
288
+ this.setData("", null);
289
+ this.props.uploadPicture({
290
+ data: "",
291
+ cloud_url_prefix: this.props.cloud_url_prefix,
292
+ isBlobUrl: false
293
+ });
294
+ //this.props.uploadPicture({data:"",cloud_url_prefix:this.props.cloud_url_prefix, isBlobUrl:true});
295
+ };
296
+
297
+ //-----------------------------------------------------------------------------------------------------------------------------------------
298
+ cleanupBlobUrl = () => {
299
+ // Only show alert if not in test environment
300
+ if (typeof jest === 'undefined') {
301
+ console.log("cleanupBlobUrl !");
302
+ }
303
+ // Revoke blob URL if it exists to prevent memory leaks
304
+ if (this.state.data && this.state.data.startsWith('blob:')) {
305
+ URL.revokeObjectURL(this.state.data);
306
+ console.log("Blob URL cleaned up:", this.state.data);
307
+ }
308
+ };
309
+
310
+ //-----------------------------------------------------------------------------------------------------------------------------------------
311
+ componentDidUpdate(prevProps) {
312
+ // Sync state with prop changes from parent
313
+ if (prevProps.data !== this.props.data) {
314
+ this.setState({
315
+ data: this.props.data || ""
316
+ });
317
+ }
318
+ if (prevProps.binaryData !== this.props.binaryData) {
319
+ this.setState({
320
+ binaryData: this.props.binaryData || null
321
+ });
322
+ }
323
+ }
324
+
325
+ //-----------------------------------------------------------------------------------------------------------------------------------------
326
+ componentWillUnmount() {
327
+ // Cleanup blob URLs when component unmounts
328
+ this.cleanupBlobUrl();
329
+ }
330
+
331
+ //-----------------------------------------------------------------------------------------------------------------------------------------
332
+ onInputChange = e => {
333
+ const errs = [];
334
+ const files = Array.from(e.target.files);
335
+ const types = ['image/png', 'image/jpeg', 'image/gif'];
336
+ const _1Mo = 1024 * 1024;
337
+ const SizeLimit = 9;
338
+
339
+ //Reset input cache value - to assure trigger if user select the same file again
340
+ e.target.value = null;
341
+ if (this.debugging) console.log("onInputChange");
342
+ if (files.length > 1) {
343
+ const msg = 'Pas plus d\'une image à la fois';
344
+ alert(msg);
345
+ return;
346
+ }
347
+ files.forEach((file, i) => {
348
+ let errCount = errs.length;
349
+ if (types.every(type => file.type !== type)) {
350
+ errs.push(`'${file.type}' : format non supporté`);
351
+ }
352
+ if (file.size > SizeLimit * _1Mo) {
353
+ errs.push(`'${file.name}' image trop volumineuse (max:${SizeLimit}Méga-octets)`);
354
+ }
355
+ if (this.debugging) console.log(`errCount = ${errCount} vs errs.length = ${errs.length}`);
356
+ if (errCount == errs.length) {
357
+ //None new error occurs
358
+ if (this.debugging) console.log("readImageAsBase64::", file.name);
359
+ this.readImageAsBase64(file);
360
+ }
361
+ });
362
+ if (errs.length) {
363
+ return errs.forEach(err => alert(err));
364
+ }
365
+ };
366
+
367
+ //-----------------------------------------------------------------------------------------------------------------------------------------
368
+ getImageSrc = () => {
369
+ if (!this.state.data) return "";
370
+
371
+ // Check if it's already a complete URL (cloud storage URL or blob URL)
372
+ if (this.state.data.startsWith('http://') || this.state.data.startsWith('https://') || this.state.data.startsWith('blob:')) {
373
+ return this.state.data;
374
+ }
375
+
376
+ // Check if it's already a data URL (base64)
377
+ if (this.state.data.startsWith('data:')) {
378
+ return this.state.data;
379
+ }
380
+
381
+ // Otherwise, treat as base64 and add appropriate prefix
382
+ return this.state.data;
383
+ };
384
+
385
+ //-----------------------------------------------------------------------------------------------------------------------------------------
386
+ getBinaryData = () => {
387
+ // Return the genuine JPEG binary stream (ArrayBuffer)
388
+ // This can be used by parent components for uploading or processing
389
+ return this.state.binaryData || this.props.binaryData || null;
390
+ };
391
+
392
+ //-----------------------------------------------------------------------------------------------------------------------------------------
393
+ // Data getter and setter methods for read-write access
394
+ getData = () => {
395
+ return this.state.data;
396
+ };
397
+ setData = (data, binaryData = null) => {
398
+ this.setState({
399
+ data: data || "",
400
+ binaryData: binaryData
401
+ });
402
+ };
403
+
404
+ //-----------------------------------------------------------------------------------------------------------------------------------------
405
+ getImageType = () => {
406
+ // Return the type of image data being used
407
+ if (this.props.isCloudUrl) return 'cloud';
408
+ if (this.props.isBlobUrl) return 'blob';
409
+ if (this.state.data && this.state.data.startsWith('data:')) return 'base64';
410
+ return 'unknown';
411
+ };
412
+ render() {
413
+ const upload_picture_label = {
414
+ cursor: "pointer"
415
+ };
416
+ const upload_picture_label_input = {
417
+ opacity: "0",
418
+ width: "0px",
419
+ height: "0px"
420
+ };
421
+ const div_show_image_hover = {
422
+ position: "relative",
423
+ margin: "0px",
424
+ opacity: "0.5"
425
+ };
426
+ const div_show_image = {
427
+ position: "relative",
428
+ margin: "0px"
429
+ };
430
+ const div_show_image_hover_input = {
431
+ display: "block",
432
+ top: "0px",
433
+ left: "0px",
434
+ position: "absolute"
435
+ };
436
+ const div_show_image_input = {
437
+ position: "absolute",
438
+ display: "none",
439
+ cursor: "pointer"
440
+ };
441
+ return /*#__PURE__*/_react.default.createElement("div", null, !this.state.data && /*#__PURE__*/_react.default.createElement("label", {
442
+ id: "upload-picture-label",
443
+ className: this.props.buttonStyle,
444
+ style: upload_picture_label
445
+ }, this.props.Caption, /*#__PURE__*/_react.default.createElement("input", {
446
+ style: upload_picture_label_input,
447
+ id: "nested-input",
448
+ type: "file",
449
+ accept: "image/*",
450
+ onChange: this.onInputChange,
451
+ multiple: true
452
+ })), this.state.data && this.state.data.length > 0 && /*#__PURE__*/_react.default.createElement("div", {
453
+ class: "show-image",
454
+ style: div_show_image,
455
+ onMouseOver: () => {
456
+ this.setState({
457
+ hover_input: true,
458
+ hover_image: true
459
+ }, () => {
460
+ if (this.debugging) console.log("onMouseOver");
461
+ });
462
+ },
463
+ onMouseLeave: () => {
464
+ this.setState({
465
+ hover_input: false,
466
+ hover_image: false
467
+ }, () => {
468
+ if (this.debugging) console.log("onMouseLeave");
469
+ });
470
+ }
471
+ }, /*#__PURE__*/_react.default.createElement("img", {
472
+ style: this.state.hover_image ? div_show_image_hover : div_show_image,
473
+ src: this.getImageSrc(),
474
+ className: this.props.pictureStyle
475
+ }), !this.props.readOnly && /*#__PURE__*/_react.default.createElement("input", {
476
+ style: this.state.hover_input ? div_show_image_hover_input : div_show_image_input,
477
+ className: "btn btn-primary delete",
478
+ type: "button",
479
+ value: "Effacer",
480
+ onClick: this.resetUpload
481
+ })));
482
+ }
483
+ }
484
+ exports.DsBlob = DsBlob;
485
+ DsBlob.propTypes = {
486
+ // Image handling props (note: data and binaryData are managed as read-write state internally)
487
+ data: _propTypes.default.string,
488
+ binaryData: _propTypes.default.object,
489
+ // Upload callback
490
+ uploadPicture: _propTypes.default.func.isRequired,
491
+ // Image size constraints
492
+ width: _propTypes.default.number,
493
+ height: _propTypes.default.number,
494
+ maxWidth: _propTypes.default.number,
495
+ maxHeight: _propTypes.default.number,
496
+ // Image processing options
497
+ reduceImage: _propTypes.default.bool,
498
+ jpegQuality: _propTypes.default.number,
499
+ // Cloud storage options
500
+ cloud_storage: _propTypes.default.bool,
501
+ cloud_url_prefix: _propTypes.default.string,
502
+ // UI props
503
+ Caption: _propTypes.default.string,
504
+ buttonStyle: _propTypes.default.string,
505
+ pictureStyle: _propTypes.default.string,
506
+ readOnly: _propTypes.default.bool,
507
+ // Status flags
508
+ isCloudUrl: _propTypes.default.bool,
509
+ isBlobUrl: _propTypes.default.bool
510
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "datasync-blob",
3
- "version": "1.1.29",
3
+ "version": "1.1.30",
4
4
  "description": "Datasync Blob component",
5
5
  "main": "./dist/components/DsBlob.js",
6
6
  "files": [