datasync-blob 1.1.26 → 1.1.27

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