@chat21/chat21-web-widget 5.1.20-rc1 → 5.1.20-rc2

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/CHANGELOG.md CHANGED
@@ -6,6 +6,10 @@
6
6
  ### **Copyrigth**:
7
7
  *Tiledesk SRL*
8
8
 
9
+ # 5.1.20-rc2
10
+ - **changed**: API for upload a file/iamges
11
+ - **changed**: marked pipe do not render /n
12
+
9
13
  # 5.1.20-rc1
10
14
  - **changed**: API for upload a file/iamges
11
15
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@chat21/chat21-web-widget",
3
3
  "author": "Tiledesk SRL",
4
- "version": "5.1.20-rc1",
4
+ "version": "5.1.20-rc2",
5
5
  "license": "MIT",
6
6
  "homepage": "https://www.tiledesk.com",
7
7
  "repository": {
@@ -317,7 +317,7 @@ export class ConversationFooterComponent implements OnInit, OnChanges {
317
317
  // });
318
318
  // this.resetLoadImage();
319
319
 
320
- this.uploadService.upload(this.senderId, currentUpload).then(data => {
320
+ this.uploadService.uploadFile(this.senderId, currentUpload).then(data => {
321
321
  that.logger.log('[CONV-FOOTER] AppComponent::uploadSingle:: downloadURL', data);
322
322
  that.logger.log(`[CONV-FOOTER] Successfully uploaded file and got download link - ${data}`);
323
323
 
@@ -18,7 +18,23 @@ export class MarkedPipe implements PipeTransform {
18
18
  typeof value === 'string'
19
19
  ? value
20
20
  : (value === null || value === undefined) ? '' : String(value);
21
- const safeInput = htmlEntities(input);
21
+
22
+ // Converti i \n letterali in newline reali prima di htmlEntities
23
+ // così il markdown con breaks: true li renderizzerà correttamente
24
+ const inputWithNewlines = input.replace(/\\n/g, '\n');
25
+
26
+ // Proteggi i > usati per i blockquote markdown (all'inizio di riga)
27
+ // sostituendoli temporaneamente con un placeholder
28
+ const BLOCKQUOTE_PLACEHOLDER = '___MARKDOWN_BLOCKQUOTE___';
29
+ const protectedInput = inputWithNewlines.replace(/^(\s*)>/gm, (match, spaces) => {
30
+ return spaces + BLOCKQUOTE_PLACEHOLDER;
31
+ });
32
+
33
+ // Applica htmlEntities (che codificherà tutti gli altri >)
34
+ let safeInput = htmlEntities(protectedInput);
35
+
36
+ // Ripristina i > dei blockquote
37
+ safeInput = safeInput.replace(new RegExp(BLOCKQUOTE_PLACEHOLDER, 'g'), '>');
22
38
 
23
39
  const renderer = new marked.Renderer();
24
40
  renderer.link = function({ href, title, tokens }) {
@@ -27,9 +27,13 @@ export abstract class UploadService {
27
27
  abstract BSStateUpload: BehaviorSubject<any>;
28
28
 
29
29
  // functions
30
- abstract initialize(projectId: string): void;
30
+ abstract initialize(projectId?: string): void;
31
31
  abstract upload(userId: string, upload: UploadModel): Promise<{downloadURL: string, src: string}>;
32
+ abstract uploadFile(userId: string, upload: UploadModel): Promise<{downloadURL: string, src: string}>;
33
+ abstract uploadAsset(userId: string, upload: UploadModel, expiration?: number): Promise<{downloadURL: string, src: string}>;
32
34
  abstract uploadProfile(userId: string, upload: UploadModel): Promise<any>;
33
35
  abstract delete(userId: string, path: string): Promise<any>;
36
+ abstract deleteFile(userId: string, path: string): Promise<any>;
37
+ abstract deleteAsset(userId: string, path: string): Promise<any>
34
38
  abstract deleteProfile(userId: string, path: string): Promise<any>
35
39
  }
@@ -96,14 +96,115 @@ export class FirebaseUploadService extends UploadService {
96
96
  }, async function complete() {
97
97
  // Handle successful uploads on complete
98
98
  that.logger.debug('[FIREBASEUploadSERVICE] Upload is complete', upload);
99
-
99
+
100
+ const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
101
+ resolve({downloadURL: downloadURL, src: downloadURL})
102
+ // that.BSStateUpload.next({upload: upload});
103
+
104
+ });
105
+ })
106
+
107
+ }
108
+
109
+ public uploadFile(userId: string, upload: UploadModel): Promise<{downloadURL: string, src: any}> {
110
+ const that = this;
111
+ const uid = this.createGuid();
112
+ const urlImagesNodeFirebase = '/public/images/' + userId + '/' + uid + '/' + upload.file.name;
113
+ this.logger.debug('[FIREBASEUploadSERVICE] pushUpload ', urlImagesNodeFirebase, upload.file);
114
+
115
+ // Create a root reference
116
+ const storageRef = this.firebase.storage().ref();
117
+ this.logger.debug('[FIREBASEUploadSERVICE] storageRef', storageRef);
118
+
119
+ // Create a reference to 'mountains.jpg'
120
+ const mountainsRef = storageRef.child(urlImagesNodeFirebase);
121
+ this.logger.debug('[FIREBASEUploadSERVICE] mountainsRef ', mountainsRef);
122
+
123
+ // const metadata = {};
124
+ const metadata = { name: upload.file.name, contentType: upload.file.type, contentDisposition: 'attachment; filename=' + upload.file.name };
125
+
126
+ let uploadTask = mountainsRef.put(upload.file, metadata);
127
+
128
+ return new Promise((resolve, reject) => {
129
+ uploadTask.on('state_changed', function progress(snapshot) {
130
+ // Observe state change events such as progress, pause, and resume
131
+ // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
132
+ var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
133
+ that.logger.debug('[FIREBASEUploadSERVICE] Upload is ' + progress + '% done');
134
+
135
+ // ----------------------------------------------------------------------------------------------------------------------------------------------
136
+ // BehaviorSubject publish the upload progress state - the subscriber is in ion-conversastion-detail.component.ts > listenToUploadFileProgress()
137
+ // ----------------------------------------------------------------------------------------------------------------------------------------------
138
+
139
+ that.BSStateUpload.next({ upload: progress, type: upload.file.type });
140
+
141
+ switch (snapshot.state) {
142
+ case that.firebase.storage.TaskState.PAUSED: // or 'paused'
143
+ that.logger.debug('[FIREBASEUploadSERVICE] Upload is paused');
144
+
145
+ break;
146
+ case that.firebase.storage.TaskState.RUNNING: // or 'running'
147
+ that.logger.debug('[FIREBASEUploadSERVICE] Upload is running');
148
+
149
+ break;
150
+ }
151
+ }, function error(error) {
152
+ // Handle unsuccessful uploads
153
+ reject(error)
154
+ }, async function complete() {
155
+ // Handle successful uploads on complete
156
+ that.logger.debug('[FIREBASEUploadSERVICE] Upload is complete', upload);
157
+
100
158
  const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
101
- resolve({downloadURL : downloadURL, src: downloadURL})
159
+ resolve({downloadURL: downloadURL, src: downloadURL})
102
160
  // that.BSStateUpload.next({upload: upload});
103
161
 
104
162
  });
105
163
  })
164
+ }
165
+
166
+ public uploadAsset(userId: string, upload: UploadModel, expiration: number = 60): Promise<{downloadURL: string, src: any}> {
167
+ // expiration is ignored on Firebase, but kept for API compatibility with NativeUploadService
168
+ const that = this;
169
+ const uid = this.createGuid();
170
+ const urlAssetsNodeFirebase = '/public/assets/' + userId + '/' + uid + '/' + upload.file.name;
171
+ this.logger.debug('[FIREBASEUploadSERVICE] uploadAsset ', urlAssetsNodeFirebase, upload.file, 'expiration:', expiration);
106
172
 
173
+ // Create a root reference
174
+ const storageRef = this.firebase.storage().ref();
175
+ this.logger.debug('[FIREBASEUploadSERVICE] storageRef', storageRef);
176
+
177
+ const assetRef = storageRef.child(urlAssetsNodeFirebase);
178
+ this.logger.debug('[FIREBASEUploadSERVICE] assetRef ', assetRef);
179
+
180
+ const metadata = { name: upload.file.name, contentType: upload.file.type, contentDisposition: 'attachment; filename=' + upload.file.name };
181
+
182
+ let uploadTask = assetRef.put(upload.file, metadata);
183
+
184
+ return new Promise((resolve, reject) => {
185
+ uploadTask.on('state_changed', function progress(snapshot) {
186
+ var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
187
+ that.logger.debug('[FIREBASEUploadSERVICE] uploadAsset is ' + progress + '% done');
188
+
189
+ that.BSStateUpload.next({ upload: progress, type: upload.file.type });
190
+
191
+ switch (snapshot.state) {
192
+ case that.firebase.storage.TaskState.PAUSED:
193
+ that.logger.debug('[FIREBASEUploadSERVICE] uploadAsset is paused');
194
+ break;
195
+ case that.firebase.storage.TaskState.RUNNING:
196
+ that.logger.debug('[FIREBASEUploadSERVICE] uploadAsset is running');
197
+ break;
198
+ }
199
+ }, function error(error) {
200
+ reject(error)
201
+ }, async function complete() {
202
+ that.logger.debug('[FIREBASEUploadSERVICE] uploadAsset is complete', upload);
203
+
204
+ const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
205
+ resolve({downloadURL: downloadURL, src: downloadURL})
206
+ });
207
+ })
107
208
  }
108
209
 
109
210
  public uploadProfile(userId: string, upload: UploadModel): Promise<any> {
@@ -154,7 +255,9 @@ export class FirebaseUploadService extends UploadService {
154
255
  // Handle successful uploads on complete
155
256
  that.logger.debug('[FIREBASEUploadSERVICE] Upload is complete', upload);
156
257
 
157
- resolve(uploadTask.snapshot.ref.getDownloadURL())
258
+ const downloadURL = uploadTask.snapshot.ref.getDownloadURL();
259
+ resolve({downloadURL : downloadURL, url: downloadURL})
260
+
158
261
  // that.BSStateUpload.next({upload: upload});
159
262
 
160
263
  });
@@ -192,6 +295,40 @@ export class FirebaseUploadService extends UploadService {
192
295
  })
193
296
  }
194
297
 
298
+ public async deleteFile(userId: string, path: string): Promise<any>{
299
+ const that = this;
300
+ const file_name_photo = 'photo.jpg';
301
+ const file_name_thumb_photo = 'thumb_photo.jpg';
302
+
303
+ that.logger.debug('[FIREBASEUploadSERVICE] delete image for USER', userId, path);
304
+
305
+ let uid = path.split(userId)[1].split('%2F')[1]; // get the UID of the image
306
+ let imageName = path.split(uid + '%2F')[1].split('?')[0];
307
+
308
+ // Create a root reference
309
+ const storageRef = this.firebase.storage().ref();
310
+ const ref = storageRef.child('public/images/' + userId + '/'+ uid + '/')
311
+ let arrayPromise = []
312
+ await ref.listAll().then((dir => {
313
+ dir.items.forEach(fileRef => arrayPromise.push(this.deleteFile(ref.fullPath, fileRef.name)));
314
+ })).catch(error => {
315
+ that.logger.error('[FIREBASEUploadSERVICE] delete: listAll error', error)
316
+ })
317
+
318
+ //AWAIT to return ALL the promise delete()
319
+ return new Promise((resolve, reject)=> {
320
+ Promise.all(arrayPromise).then(()=>{
321
+ resolve(true)
322
+ }).catch((error)=>{
323
+ reject(error)
324
+ })
325
+ })
326
+ }
327
+
328
+ public async deleteAsset(userId: string, path: string): Promise<any>{
329
+ return this.deleteProfile(userId, path);
330
+ }
331
+
195
332
  public async deleteProfile(userId: string, path: string): Promise<any>{
196
333
  const that = this;
197
334
  const file_name_photo = 'photo.jpg';
@@ -219,13 +356,5 @@ export class FirebaseUploadService extends UploadService {
219
356
  })
220
357
  }
221
358
 
222
- // // ------------------------------------
223
- // // Delete the file photo
224
- // // ------------------------------------
225
- private deleteFile(pathToFile, fileName){
226
- const ref = this.firebase.storage().ref(pathToFile);
227
- const childRef = ref.child(fileName);
228
- return childRef.delete()
229
- }
230
359
 
231
360
  }
@@ -15,6 +15,7 @@ export class NativeUploadService extends UploadService {
15
15
 
16
16
  private tiledeskToken: string;
17
17
  private URL_TILEDESK_FILE: string;
18
+ private URL_TILEDESK_UPLOAD: string;
18
19
  private logger: LoggerService = LoggerInstance.getInstance()
19
20
 
20
21
  constructor(
@@ -24,9 +25,12 @@ export class NativeUploadService extends UploadService {
24
25
  super();
25
26
  }
26
27
 
27
- initialize(projectId: string): void {
28
+ initialize(projectId?: string): void {
28
29
  this.logger.info('[NATIVE UPLOAD] initialize', this.getBaseUrl())
29
- this.URL_TILEDESK_FILE = this.getBaseUrl() + projectId + '/files'
30
+ if (projectId) {
31
+ this.URL_TILEDESK_FILE = this.getBaseUrl() + projectId + '/files'
32
+ }
33
+ this.URL_TILEDESK_UPLOAD = this.getBaseUrl();
30
34
  this.tiledeskToken = this.appStorage.getItem('tiledeskToken')
31
35
  }
32
36
 
@@ -41,51 +45,93 @@ export class NativeUploadService extends UploadService {
41
45
  const formData = new FormData();
42
46
  formData.append('file', upload.file);
43
47
 
48
+ const that = this;
49
+ if ((upload.file.type.startsWith('image') && (!upload.file.type.includes('svg')))) {
50
+ //USE IMAGE API
51
+ const url = this.URL_TILEDESK_UPLOAD + 'images/users'
52
+ return new Promise((resolve, reject) => {
53
+ that.http.post(url, formData, requestOptions).pipe(first()).subscribe({
54
+ next: (data) => {
55
+ const downloadURL = this.URL_TILEDESK_UPLOAD + 'images?path=' + encodeURIComponent(data?.['filename']);
56
+ resolve({downloadURL : downloadURL, src: downloadURL})
57
+ // that.BSStateUpload.next({upload: upload});
58
+ },
59
+ error: (error) => {
60
+ reject(error)
61
+ }
62
+ });
63
+ });
64
+ } else {
65
+ //USE FILE API
66
+ const url = this.URL_TILEDESK_UPLOAD + 'files/users'
67
+ return new Promise((resolve, reject) => {
68
+ that.http.post(url, formData, requestOptions).pipe(first()).subscribe({
69
+ next: (data) => {
70
+ const src = this.URL_TILEDESK_UPLOAD + 'files?path=' + encodeURIComponent(data['filename']);
71
+ const downloadURL = this.URL_TILEDESK_UPLOAD + 'files/download' + '?path=' + encodeURIComponent(data['filename']);
72
+ resolve({downloadURL : downloadURL, src: src})
73
+ // that.BSStateUpload.next({upload: upload});
74
+ },
75
+ error: (error) => {
76
+ this.logger.error('[NATIVE UPLOAD] - ERROR upload new file ', error)
77
+ reject(error)
78
+ }
79
+ });
80
+ });
81
+ }
82
+
83
+ }
84
+
85
+ uploadFile(userId: string, upload: UploadModel): Promise<{downloadURL: string, src: string}> {
86
+ this.logger.log('[NATIVE UPLOAD] - upload new image/file ... upload', upload)
87
+ const headers = new HttpHeaders({
88
+ Authorization: this.tiledeskToken,
89
+ //'Content-Type': 'multipart/form-data',
90
+ });
91
+ const requestOptions = { headers: headers };
92
+ const formData = new FormData();
93
+ formData.append('file', upload.file);
94
+
44
95
  const that = this;
45
96
  const url = this.URL_TILEDESK_FILE + '/chat'
46
97
  return new Promise((resolve, reject) => {
47
98
  that.http.post(url, formData, requestOptions).pipe(first()).subscribe({
48
99
  next: (data) => {
49
- const downloadURL = this.getBaseUrl() + 'files' + '?path=' + data['filename'];
50
- resolve({downloadURL : downloadURL, src: downloadURL})
100
+ const src = this.URL_TILEDESK_UPLOAD + 'files?path=' + encodeURIComponent(data['filename']);
101
+ const downloadURL = this.URL_TILEDESK_UPLOAD + 'files/download?path=' + encodeURIComponent(data['filename']);
102
+ resolve({downloadURL : downloadURL, src: src})
51
103
  },
52
104
  error: (error) => {
53
105
  reject(error)
54
106
  }
55
107
  });
108
+ });
109
+ }
110
+
111
+ uploadAsset(userId: string, upload: UploadModel, expiration: number = 60): Promise<{downloadURL: string, src: string}> {
112
+ this.logger.log('[NATIVE UPLOAD] - upload new asset ... upload', upload, 'expiration:', expiration)
113
+ const headers = new HttpHeaders({
114
+ Authorization: this.tiledeskToken,
56
115
  });
116
+ const requestOptions = { headers: headers };
117
+ const formData = new FormData();
118
+ formData.append('file', upload.file);
57
119
 
58
- //old_implemenation
59
- // if ((upload.file.type.startsWith('image') && (!upload.file.type.includes('svg')))) {
60
- // this.logger.log('[NATIVE UPLOAD] - upload new image', this.URL_TILEDESK_IMAGES)
61
- // //USE IMAGE API
62
- // const url = this.URL_TILEDESK_IMAGES + '/users'
63
- // return new Promise((resolve, reject) => {
64
- // that.http.post(url, formData, requestOptions).subscribe(data => {
65
- // const downloadURL = this.URL_TILEDESK_IMAGES + '?path=' + data['filename'];
66
- // resolve({downloadURL : downloadURL, src: downloadURL})
67
- // // that.BSStateUpload.next({upload: upload});
68
- // }, (error) => {
69
- // reject(error)
70
- // });
71
- // });
72
- // } else {
73
- // this.logger.log('[NATIVE UPLOAD] - upload new file', this.URL_TILEDESK_FILE)
74
- // //USE FILE API
75
- // const url = this.URL_TILEDESK_FILE + '/users'
76
- // return new Promise((resolve, reject) => {
77
- // that.http.post(url, formData, requestOptions).subscribe(data => {
78
- // const src = this.URL_TILEDESK_FILE + '?path=' + encodeURI(data['filename']);
79
- // const downloadURL = this.URL_TILEDESK_FILE + '/download' + '?path=' + encodeURI(data['filename']);
80
- // resolve({downloadURL : downloadURL, src: src})
81
- // // that.BSStateUpload.next({upload: upload});
82
- // }, (error) => {
83
- // this.logger.error('[NATIVE UPLOAD] - ERROR upload new file ', error)
84
- // reject(error)
85
- // });
86
- // });
87
- // }
88
-
120
+ const that = this;
121
+ const queryString = expiration !== undefined ? `?expiration=${encodeURIComponent(String(expiration))}` : ''
122
+ const url = this.URL_TILEDESK_FILE + `/assets${queryString}`
123
+ return new Promise((resolve, reject) => {
124
+ that.http.post(url, formData, requestOptions).pipe(first()).subscribe({
125
+ next: (data) => {
126
+ const src = this.URL_TILEDESK_UPLOAD + 'files?path=' + data['filename'];
127
+ const downloadURL = this.URL_TILEDESK_UPLOAD + 'files/download?path=' + encodeURIComponent(data['filename']);
128
+ resolve({downloadURL : downloadURL, src: src})
129
+ },
130
+ error: (error) => {
131
+ reject(error)
132
+ }
133
+ });
134
+ });
89
135
  }
90
136
 
91
137
  uploadProfile(userId: string, upload: UploadModel): Promise<any> {
@@ -100,8 +146,8 @@ export class NativeUploadService extends UploadService {
100
146
 
101
147
  // USE IMAGE API
102
148
  const that = this;
103
- const botId = userId?.startsWith('bot_') ? userId.substring('bot_'.length) : userId
104
- const url = this.URL_TILEDESK_FILE + `/users/photo?bot_id=${botId}`
149
+ const queryString = userId?.startsWith('bot_') ? `?bot_id=${encodeURIComponent(userId.substring('bot_'.length))}` : ''
150
+ const url = this.URL_TILEDESK_FILE + `/users/photo${queryString}`
105
151
  return new Promise((resolve, reject) => {
106
152
  that.http.put(url, formData, requestOptions).pipe(first()).subscribe({
107
153
  next: (data) => {
@@ -124,6 +170,31 @@ export class NativeUploadService extends UploadService {
124
170
  });
125
171
  const requestOptions = { headers: headers };
126
172
 
173
+ //USE IMAGE API
174
+ const that = this;
175
+ const url = this.URL_TILEDESK_UPLOAD + 'images/users' + '?path=' + path.split('path=')[1]
176
+ return new Promise((resolve, reject) => {
177
+ that.http.delete(url, requestOptions).pipe(first()).subscribe({
178
+ next: (data) => {
179
+ // const downloadURL = this.URL_TILEDESK_IMAGES + '?path=' + data['filename'];
180
+ resolve(true)
181
+ // that.BSStateUpload.next({upload: upload});
182
+ },
183
+ error: (error) => {
184
+ reject(error)
185
+ }
186
+ });
187
+ });
188
+ }
189
+
190
+ deleteFile(userId: string, path: string): Promise<any>{
191
+ this.logger.log('[NATIVE UPLOAD] - delete image ... upload', userId)
192
+ const headers = new HttpHeaders({
193
+ Authorization: this.tiledeskToken,
194
+ //'Content-Type': 'multipart/form-data',
195
+ });
196
+ const requestOptions = { headers: headers };
197
+
127
198
  //USE IMAGE API
128
199
  const that = this;
129
200
  const url = this.URL_TILEDESK_FILE + '?path=' + path.split('path=')[1]
@@ -141,6 +212,10 @@ export class NativeUploadService extends UploadService {
141
212
  });
142
213
  }
143
214
 
215
+ deleteAsset(userId: string, path: string): Promise<any>{
216
+ return this.deleteFile(userId, path);
217
+ }
218
+
144
219
  deleteProfile(userId: string, path: string): Promise<any>{
145
220
  this.logger.log('[NATIVE UPLOAD] - delete image ... upload', userId)
146
221
  const headers = new HttpHeaders({