@meltwater/conversations-api-services 1.0.21 → 1.0.23

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,387 @@
1
+ import superagent from 'superagent';
2
+ import { loggerDebug, loggerError, loggerInfo } from '../../lib/logger.helpers.js';
3
+ const LINKEDIN_API = "https://api.linkedin.com/v2";
4
+ const LINKEDIN_API_VERSION = "2.0.0";
5
+ export async function like(token, externalId, socialAccountId, logger) {
6
+ let response;
7
+ let payload = {
8
+ actor: socialAccountId,
9
+ object: externalId
10
+ };
11
+ let query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(externalId)}/likes`;
12
+ try {
13
+ loggerDebug(logger, `Linkedin trying to Like `, {
14
+ query,
15
+ payload: JSON.stringify(payload)
16
+ });
17
+ response = await superagent.post(query).timeout(5000) // 5 seconds
18
+ .set({
19
+ Authorization: `Bearer ${token}`,
20
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
21
+ 'LinkedIn-Version': '202311'
22
+ }).send(payload);
23
+ loggerInfo(logger, `Native Linkedin API Like Mutation Response`, {
24
+ response: JSON.stringify(response)
25
+ });
26
+ } catch (err) {
27
+ loggerError(logger, `Linkedin Like or Unlike Exception`, err);
28
+ throw err;
29
+ }
30
+ return response.connection || response;
31
+ }
32
+ export async function unlike(token, externalId, socialAccountId, logger) {
33
+ let response;
34
+ let payload = {
35
+ actor: socialAccountId,
36
+ object: externalId
37
+ };
38
+ let query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(externalId)}/likes/${fixedEncodeURIComponent(payload.actor)}?actor=${fixedEncodeURIComponent(payload.actor)}`;
39
+ try {
40
+ loggerDebug(logger, `Linkedin trying Delete Previous Like `, {
41
+ query,
42
+ payload: JSON.stringify(payload)
43
+ });
44
+ response = await superagent.delete(query).timeout(5000).set({
45
+ Authorization: `Bearer ${token}`,
46
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
47
+ 'LinkedIn-Version': '202311'
48
+ });
49
+ loggerInfo(logger, `Native Linkedin API UNLike Mutation Response`, {
50
+ response: JSON.stringify(response)
51
+ });
52
+ } catch (err) {
53
+ loggerError(logger, `Linkedin Like or Unlike Exception`, err);
54
+ throw err;
55
+ }
56
+ return response.connection || response;
57
+ }
58
+ export async function deleteMessage(token, externalId, sourceId, inReplyToId, logger) {
59
+ const [, comment] = externalId.split(',');
60
+ const commentId = comment.split(')')[0];
61
+ let response;
62
+ const query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(inReplyToId)}/comments/${commentId}?actor=${fixedEncodeURIComponent(sourceId)}`;
63
+ try {
64
+ loggerDebug(logger, `Linkedin trying Delete `, {
65
+ query
66
+ });
67
+ response = await superagent.delete(query).timeout(5000).set({
68
+ Authorization: `Bearer ${token}`,
69
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
70
+ 'LinkedIn-Version': '202311'
71
+ });
72
+ loggerInfo(logger, `Native Linkedin API Delete Comment Response`, {
73
+ response: JSON.stringify(response)
74
+ });
75
+ } catch (err) {
76
+ loggerError(logger, `Linkedin Delete exception details`, {
77
+ err
78
+ });
79
+ throw err;
80
+ }
81
+ return response;
82
+ }
83
+ export async function comment(token, mediaId, inReplyToId, socialAccountId, messageText, logger) {
84
+ return publish(token, 'qt', mediaId, inReplyToId, socialAccountId, messageText, logger);
85
+ }
86
+ export async function reply(token, mediaId, inReplyToId, socialAccountId, messageText, logger) {
87
+ return publish(token, 're', mediaId, inReplyToId, socialAccountId, messageText, logger);
88
+ }
89
+ async function publish(token, discussionType, mediaId, inReplyToId, socialAccountId, messageText, logger) {
90
+ // for now this is needed to make the urns from the images api work until the docs are updated to reflect how to use these new ids.
91
+ if (mediaId) {
92
+ mediaId = mediaId.replace('urn:li:image:', 'urn:li:digitalmediaAsset:');
93
+ }
94
+ let body = {
95
+ actor: socialAccountId,
96
+ message: {
97
+ attributes: [],
98
+ text: messageText
99
+ }
100
+ };
101
+ if (discussionType === 're') {
102
+ body.parentComment = inReplyToId;
103
+ }
104
+ if (mediaId) {
105
+ body.content = [{
106
+ entity: {
107
+ digitalmediaAsset: mediaId
108
+ },
109
+ type: 'IMAGE'
110
+ }];
111
+ }
112
+ let query = `${LINKEDIN_API}/socialActions/${fixedEncodeURIComponent(inReplyToId)}/comments`;
113
+
114
+ // data-listener -> linkedin_api.client sendComment
115
+ let response;
116
+ let downloadUrl = '';
117
+ try {
118
+ response = await superagent.post(query).timeout(5000).set({
119
+ Authorization: `Bearer ${token}`,
120
+ 'Content-Type': 'application/json',
121
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
122
+ 'LinkedIn-Version': '202311'
123
+ }).send(body);
124
+ loggerInfo(logger, `Native Linkedin API Publish Comment Response`, {
125
+ response: JSON.stringify(response)
126
+ });
127
+ response = {
128
+ status: 200,
129
+ message: JSON.parse(response.text)
130
+ };
131
+ if (mediaId) {
132
+ loggerInfo(logger, `mediaId`, {
133
+ mediaId
134
+ });
135
+ downloadUrl = await getImageMedia(mediaId, token, logger);
136
+ loggerInfo(logger, `downloadUrl`, {
137
+ downloadUrl
138
+ });
139
+ }
140
+ } catch (err) {
141
+ loggerError(logger`Exception in linkedin publish `, err);
142
+ throw err;
143
+ }
144
+ return {
145
+ response,
146
+ downloadUrl
147
+ };
148
+ }
149
+ async function getImageMedia(mediaId, token, logger) {
150
+ let response = {};
151
+ if (mediaId && mediaId.includes('digitalmediaAsset')) {
152
+ mediaId = mediaId.replace('urn:li:digitalmediaAsset:', 'urn:li:image:');
153
+ }
154
+ try {
155
+ response = await superagent.get(LINKEDIN_API + '/images/' + fixedEncodeURIComponent(mediaId)).timeout(5000) // 5 seconds
156
+ .set({
157
+ Authorization: `Bearer ${token}`,
158
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
159
+ 'LinkedIn-Version': '202311'
160
+ });
161
+ } catch (error) {
162
+ loggerError(logger, 'Error in getImageMedia', error);
163
+ }
164
+ let {
165
+ downloadUrl
166
+ } = response.body || {};
167
+ if (downloadUrl) {
168
+ return {
169
+ downloadUrl
170
+ };
171
+ } else {
172
+ loggerError(logger, `Invalid response getting Linkedin media for mediaId: ${mediaId} `, {
173
+ response: JSON.stringify(response)
174
+ });
175
+ return {};
176
+ }
177
+ }
178
+ export async function getVideoMedia(mediaId, token, logger) {
179
+ let response = {};
180
+ let tempValue;
181
+ if (mediaId && mediaId.includes('digitalmediaMediaArtifact')) {
182
+ tempValue = mediaId.split('digitalmediaMediaArtifact:(')[1];
183
+ tempValue = tempValue.split(',urn:li:digitalmediaMediaArtifactClass')[0];
184
+ mediaId = tempValue;
185
+ }
186
+ if (mediaId && mediaId.includes('digitalmediaAsset')) {
187
+ mediaId = mediaId.replace('urn:li:digitalmediaAsset:', 'urn:li:video:');
188
+ }
189
+ try {
190
+ response = await superagent.get(LINKEDIN_API + '/videos/' + fixedEncodeURIComponent(mediaId)).timeout(5000) // 5 seconds
191
+ .set({
192
+ Authorization: `Bearer ${token}`,
193
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
194
+ 'LinkedIn-Version': '202311'
195
+ });
196
+ } catch (error) {
197
+ loggerError(logger, 'Error in getVideoMedia', error);
198
+ }
199
+ let {
200
+ thumbnail,
201
+ downloadUrl
202
+ } = response.body || {};
203
+ if (downloadUrl) {
204
+ return {
205
+ thumbnail,
206
+ downloadUrl
207
+ };
208
+ } else {
209
+ loggerError(logger, `Invalid response getting Linkedin media for mediaId: ${mediaId} `, {
210
+ response: JSON.stringify(response)
211
+ });
212
+ return {};
213
+ }
214
+ }
215
+ export async function getMedia(token, mediaId, type, logger) {
216
+ // needed due to issue with polled data
217
+ if (type.includes('video') && mediaId.includes('image')) {
218
+ type = 'image/jpeg';
219
+ }
220
+ try {
221
+ if (type.includes('image')) {
222
+ const {
223
+ downloadUrl
224
+ } = await getImageMedia(mediaId, token, logger);
225
+ return {
226
+ downloadUrl
227
+ };
228
+ } else if (type.includes('video')) {
229
+ const {
230
+ thumbnail,
231
+ downloadUrl
232
+ } = await getVideoMedia(mediaId, token, logger);
233
+ return {
234
+ thumbnail,
235
+ downloadUrl
236
+ };
237
+ }
238
+ return {};
239
+ } catch (error) {
240
+ loggerError(logger, 'Error in getMedia', error);
241
+ }
242
+ }
243
+ export async function mediaUploadURL(token, socialAccountId, logger) {
244
+ let query = `${LINKEDIN_API}/images?action=initializeUpload`;
245
+ let body = {
246
+ initializeUploadRequest: {
247
+ owner: socialAccountId
248
+ }
249
+ };
250
+ let response;
251
+ try {
252
+ response = await superagent.post(query).timeout(5000).set({
253
+ Authorization: `Bearer ${token}`,
254
+ 'Content-type': 'application/json',
255
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
256
+ 'LinkedIn-Version': '202311'
257
+ }).send(body);
258
+ response = {
259
+ status: 200,
260
+ message: JSON.parse(response.text)
261
+ };
262
+ return response;
263
+ } catch (err) {
264
+ loggerError(logger, `Exception linkedin media register `, err);
265
+ }
266
+ }
267
+ export async function getProfile(urn, token, logger) {
268
+ let [,,, id] = urn.split(':');
269
+ let profile;
270
+ try {
271
+ profile = await superagent.get(`${LINKEDIN_API}/people/(id:${id})`).query({
272
+ projection: '(id,localizedFirstName,localizedLastName,vanityName,profilePicture(displayImage~:playableStreams))'
273
+ }).timeout(5000).set({
274
+ Authorization: `Bearer ${token}`,
275
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
276
+ 'LinkedIn-Version': '202311'
277
+ }).then(result => result.body);
278
+ } catch (error) {
279
+ loggerError(logger, `Failed requesting LinkedIn API for profileId ${urn}`, error);
280
+ return;
281
+ }
282
+ loggerInfo(logger, `Finished requesting LinkedIn API for profileId ${urn}`);
283
+ return profile;
284
+ }
285
+ export async function getOrganization(urn, token, logger) {
286
+ let [,,, id] = urn.split(':');
287
+ let organization;
288
+ try {
289
+ organization = await superagent.get(`${LINKEDIN_API}/organizations/${id}`).query({
290
+ projection: '(id,localizedName,vanityName,logoV2(original~:playableStreams))'
291
+ }).timeout(5000) // 5 seconds
292
+ .set({
293
+ Authorization: `Bearer ${token}`,
294
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
295
+ 'LinkedIn-Version': '202311'
296
+ }).then(result => result.body);
297
+ } catch (error) {
298
+ if (error.response.body.message.includes('ADMIN_ONLY')) {
299
+ return {
300
+ id: 'private'
301
+ };
302
+ }
303
+ loggerError(logger, `Failed requesting LinkedIn API for organizationId ${urn}`, error);
304
+ }
305
+ loggerInfo(logger, `Finished requesting LinkedIn API for organizationId ${urn}`);
306
+ return organization;
307
+ }
308
+ async function getAllStats(externalId, token, logger) {
309
+ let response = {};
310
+ try {
311
+ response = await superagent.get(LINKEDIN_API + '/socialMetadata/' + fixedEncodeURIComponent(externalId)).timeout(5000) // 5 seconds
312
+ .set({
313
+ Authorization: `Bearer ${token}`,
314
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
315
+ 'LinkedIn-Version': '202311'
316
+ });
317
+ } catch (error) {
318
+ loggerError(logger, 'Error in getAllStats', error);
319
+ }
320
+ let {
321
+ commentSummary,
322
+ reactionSummaries
323
+ } = response.body || {};
324
+ if (commentSummary && reactionSummaries) {
325
+ return {
326
+ commentSummary,
327
+ reactionSummaries
328
+ };
329
+ } else {
330
+ loggerError(logger, `Invalid response getting all Linkedin Stats for externalId: ${externalId}`, {
331
+ response: JSON.stringify(response)
332
+ });
333
+ return {};
334
+ }
335
+ }
336
+ export async function getSocialStats(externalId, token, logger) {
337
+ try {
338
+ // get all stats (likes are not to be trusted) seems to only work
339
+ // for og posts.
340
+ const {
341
+ commentSummary,
342
+ reactionSummaries
343
+ } = await getAllStats(externalId, token, logger);
344
+ return {
345
+ commentSummary,
346
+ reactionSummaries
347
+ };
348
+ } catch (error) {
349
+ loggerError(logger, 'Error in getSocialStats', error);
350
+ }
351
+ }
352
+ export async function likedByUser(token, externalId, authorExternalId, logger) {
353
+ let result;
354
+ try {
355
+ result = await superagent.get(`${LINKEDIN_API}/reactions/(actor:${fixedEncodeURIComponent(authorExternalId)},entity:${fixedEncodeURIComponent(externalId)})`).set({
356
+ Authorization: `Bearer ${token}`,
357
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
358
+ 'LinkedIn-Version': '202311'
359
+ }).then(result => result.body);
360
+ } catch (error) {
361
+ loggerError(logger, 'Error in getLikesByUser', error);
362
+ return false;
363
+ }
364
+ return true;
365
+ }
366
+
367
+ // query object is from AssetManager
368
+ export async function uploadMedia(query, logger) {
369
+ const {
370
+ url,
371
+ token,
372
+ data
373
+ } = query;
374
+ return await superagent.put(url).set({
375
+ Accept: '*/*',
376
+ 'Content-Type': 'application/octet-stream',
377
+ Authorization: `Bearer ${token}`,
378
+ 'X-RestLi-Protocol-Version': LINKEDIN_API_VERSION,
379
+ 'LinkedIn-Version': '202311'
380
+ }).send(data).catch(err => {
381
+ loggerError(logger, "Linkedin Error uploading Media", err);
382
+ throw err;
383
+ });
384
+ }
385
+ function fixedEncodeURIComponent(str) {
386
+ return encodeURIComponent(str).replace(/\(/g, '%28').replace(/\)/g, '%29');
387
+ }
@@ -18,6 +18,7 @@ import * as applicationTagFunctions from '../lib/applicationTags.helpers.js';
18
18
  import * as hiddenHelpers from '../lib/hidden.helpers.js';
19
19
  import * as FacebookNative from './http/facebook.native.js';
20
20
  import * as TiktokNative from './http/tiktok.native.js';
21
+ import * as LinkedinNative from './http/linkedin.native.js';
21
22
  const DocumentHelperFunctions = {
22
23
  ...messageHelpers,
23
24
  ...applicationTagFunctions,
@@ -27,4 +28,4 @@ const LinkedInHelpers = {
27
28
  getOrganization,
28
29
  getProfile
29
30
  };
30
- export { FacebookNative, TiktokNative, awsS3Client, assetManagerTvmRepository, CompanyApiClient, CredentialsApiClient, EntitlementsApiClient, FacebookApiClient, FeatureToggleClient, IdentityServicesClient, InstagramApiClient, InstagramVideoClient, IRClient, LinkedInApiClient, TikTokApiClient, MasfClient, WarpZoneApiClient, DocumentHelperFunctions, LinkedInHelpers };
31
+ export { FacebookNative, TiktokNative, LinkedinNative, awsS3Client, assetManagerTvmRepository, CompanyApiClient, CredentialsApiClient, EntitlementsApiClient, FacebookApiClient, FeatureToggleClient, IdentityServicesClient, InstagramApiClient, InstagramVideoClient, IRClient, LinkedInApiClient, TikTokApiClient, MasfClient, WarpZoneApiClient, DocumentHelperFunctions, LinkedInHelpers };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meltwater/conversations-api-services",
3
- "version": "1.0.21",
3
+ "version": "1.0.23",
4
4
  "description": "Repository to contain all conversations api services shared across our services",
5
5
  "main": "dist/cjs/data-access/index.js",
6
6
  "module": "dist/esm/data-access/index.js",
@@ -119,7 +119,7 @@ export async function privateMessage(token, {
119
119
  logger
120
120
  );
121
121
  loggerInfo(logger,
122
- `Native Facebook API Publish Private Message Response for documentId ${documentId}`,
122
+ `Native Facebook API Publish Private Message Response`,
123
123
  { responseBody: JSON.stringify(response.body) }
124
124
  );
125
125
  return response.body;