backend-manager 3.2.152 → 3.2.154

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,154 @@
1
+ const fetch = require('wonderful-fetch');
2
+ const _ = require('lodash');
3
+
4
+ function Module() {
5
+
6
+ }
7
+
8
+ Module.prototype.main = function () {
9
+ const self = this;
10
+ const Manager = self.Manager;
11
+ const Api = self.Api;
12
+ const assistant = self.assistant;
13
+ const payload = self.payload;
14
+
15
+ return new Promise(async function(resolve, reject) {
16
+
17
+ // console.log('---self.libraries.admin', self.libraries.admin);
18
+ // console.log('---self.libraries.admin.credential', self.libraries.admin.credential);
19
+ // console.log('---self.libraries.admin.credential.cert()', self.libraries.admin.credential.cert());
20
+ // console.log('---self.libraries.admin.credential.refreshToken()', self.libraries.admin.credential.refreshToken());
21
+ // console.log('---self.libraries.admin.default', self.libraries.admin.default);
22
+ // console.log('---self.libraries.initializedAdmin', self.libraries.initializedAdmin);
23
+ // console.log('---self.libraries.admin.INTERNAL', self.libraries.admin.INTERNAL);
24
+ // console.log('---self.libraries.initializedAdmin.options_.credential', self.libraries.initializedAdmin.options_.credential);
25
+ // console.log('---self.libraries.initializedAdmin.options_.credential.refreshToken', self.libraries.initializedAdmin.options_.credential.refreshToken);
26
+ // console.log('---self.libraries.initializedAdmin.options_.credential.refreshToken', self.libraries.initializedAdmin.options_.credential.refreshToken);
27
+ // console.log('---self.libraries.initializedAdmin.INTERNAL', self.libraries.initializedAdmin.INTERNAL);
28
+ // const powertools = require('node-powertools');
29
+ // console.log('---self.libraries.admin', powertools.stringify(self.libraries.admin));
30
+ // console.log('---self.libraries.initializedAdmin', powertools.stringify(self.libraries.initializedAdmin));
31
+
32
+ const providers = [
33
+ { name: 'google.com', prefix: ['id_token'] },
34
+ { name: 'facebook.com', prefix: ['access_token'] },
35
+ { name: 'twitter.com', prefix: ['access_token', 'oauth_token_secret'] },
36
+ { name: 'github.com', prefix: ['access_token'] },
37
+ { name: 'microsoft.com', prefix: ['id_token'] },
38
+ // { name: 'microsoft.com', prefix: ['context', 'continueUri', 'sessionId'] },
39
+ { name: 'yahoo.com', prefix: ['id_token'] },
40
+ { name: 'apple.com', prefix: ['id_token'] },
41
+ ]
42
+ const promises = []
43
+
44
+ payload.data.payload.firebaseApiKey = payload.data.payload.firebaseApiKey || _.get(Manager, 'config.firebaseConfig.apiKey') || false;
45
+
46
+ if (!payload.data.payload.firebaseApiKey) {
47
+ return reject(assistant.errorify(`The firebaseApiKey parameter is required.`, {code: 400}));
48
+ }
49
+
50
+ // Default
51
+ payload.response.data.password = true;
52
+
53
+ assistant.log('Checking providers for firebaseApiKey', payload.data.payload.firebaseApiKey);
54
+
55
+ function request(provider) {
56
+ return new Promise(function(resolve, reject) {
57
+ let prefix = '';
58
+ provider.prefix
59
+ .forEach((item, i) => {
60
+ prefix += `${item}=LOL&`
61
+ });
62
+
63
+ // https://firebase.google.com/docs/reference/rest/auth#section-sign-in-with-oauth-credential
64
+ fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=${payload.data.payload.firebaseApiKey}`, {
65
+ method: 'post',
66
+ body: {
67
+ postBody: `${prefix}providerId=${provider.name}`,
68
+ requestUri: 'http://localhost',
69
+ returnIdpCredential: true,
70
+ returnSecureToken: true
71
+ }
72
+ })
73
+ .then(response => {
74
+ payload.response.data[provider.name] = true;
75
+ })
76
+ .catch(e => {
77
+ try {
78
+ const errorJson = JSON.parse(e.message);
79
+ const errorArray = errorJson.error.errors || [];
80
+ let result = true;
81
+
82
+ errorArray
83
+ .forEach((error, i) => {
84
+ if (error.message.includes('OPERATION_NOT_ALLOWED') || error.message.includes('INVALID_CREDENTIAL_OR_PROVIDER_ID')) {
85
+ result = false;
86
+ }
87
+ assistant.log('Provider check', provider.name, error);
88
+ });
89
+
90
+ assistant.log('Provider response', provider.name, result);
91
+
92
+ payload.response.data[provider.name] = result;
93
+ } catch (e) {
94
+ assistant.errorify(`Error parsing error: ${e}`, {code: 500, sentry: true});
95
+ payload.response.data[provider.name] = false;
96
+ }
97
+ })
98
+ .finally(r => {
99
+ return resolve();
100
+ })
101
+ });
102
+ }
103
+
104
+ providers
105
+ .forEach((provider, i) => {
106
+ payload.response.data[provider.name] = false;
107
+ promises.push(request(provider))
108
+ });
109
+
110
+ assistant.log('Checking providers...');
111
+
112
+ await Promise.all(promises)
113
+ .then(response => {
114
+ // console.log('--payload.response.data', promises.length, payload.response.data);
115
+
116
+ fetch(`https://us-central1-itw-creative-works.cloudfunctions.net/getApp`, {
117
+ method: 'post',
118
+ response: 'json',
119
+ body: {
120
+ id: Manager.config.app.id,
121
+ }
122
+ })
123
+ .then(response => {
124
+ assistant.log('getApp response', response);
125
+ response.authentication = response.authentication || {};
126
+
127
+ Object.keys(response.authentication)
128
+ .forEach((provider, i) => {
129
+ response.authentication[provider] = response.authentication[provider] || {};
130
+
131
+ if (typeof response.authentication[provider].enabled !== 'undefined') {
132
+ payload.response.data[provider] = response.authentication[provider].enabled;
133
+ assistant.log(`Overwriting ${provider} to ${payload.response.data[provider]}...`);
134
+ }
135
+ });
136
+
137
+ })
138
+ .catch(e => {
139
+ assistant.errorify(`Error getting app data: ${e}`, {code: 500, log: true})
140
+ })
141
+ .finally(r => {
142
+ return resolve({data: payload.response.data});
143
+ })
144
+
145
+ })
146
+ .catch(e => {
147
+ return reject(assistant.errorify(`Failed to check providers: ${e}`, {code: 500}));
148
+ })
149
+
150
+ });
151
+
152
+ };
153
+
154
+ module.exports = Module;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "3.2.152",
3
+ "version": "3.2.154",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
package/src/cli/cli.js CHANGED
@@ -963,22 +963,27 @@ function fix_indexesSync(self) {
963
963
 
964
964
  function fix_setStoragePolicy(self) {
965
965
  return new Promise(function(resolve, reject) {
966
- fetch(self.bemApiURL, {
967
- method: 'post',
968
- timeout: 30000,
969
- response: 'json',
970
- body: {
971
- command: 'admin:backup',
972
- },
973
- })
974
- .then(json => {
975
- console.log('Response', json);
976
- return resolve();
977
- })
978
- .catch(e => {
979
- console.error(chalk.red(`There is no automatic fix. Please run: \n${chalk.bold('firebase deploy && npx bm setup')}`));
980
- return reject();
981
- });
966
+ // fetch(self.bemApiURL, {
967
+ // method: 'post',
968
+ // timeout: 30000,
969
+ // response: 'json',
970
+ // body: {
971
+ // command: 'admin:backup',
972
+ // },
973
+ // })
974
+ // .then(json => {
975
+ // console.log('Response', json);
976
+ // return resolve();
977
+ // })
978
+ // .catch(e => {
979
+ // console.error(chalk.red(`There is no automatic fix. Please run: \n${chalk.bold('firebase deploy && npx bm setup')}`));
980
+ // return reject();
981
+ // });
982
+ // Log
983
+ console.error(chalk.red(`There is no automatic fix. Please run: \n${chalk.bold('firebase deploy && npx bm setup')}`));
984
+
985
+ // Reject
986
+ return reject();
982
987
  });
983
988
  };
984
989
 
@@ -90,7 +90,7 @@ Module.prototype._setMetaStats = function (error, meta) {
90
90
  },
91
91
  status: {
92
92
  success: !isError,
93
- error: error,
93
+ error: isError ? error.message : null,
94
94
  }
95
95
  }
96
96
  },
@@ -12,4 +12,5 @@ post:
12
12
  categories: {categories}
13
13
  affiliate-search-term: {affiliate}
14
14
  ---
15
+
15
16
  {body}
@@ -1,5 +1,5 @@
1
1
  const fetch = require('wonderful-fetch');
2
- const _ = require('lodash');
2
+ const { merge } = require('lodash');
3
3
 
4
4
  function Module() {
5
5
 
@@ -13,142 +13,90 @@ Module.prototype.main = function () {
13
13
  const payload = self.payload;
14
14
 
15
15
  return new Promise(async function(resolve, reject) {
16
-
17
- // console.log('---self.libraries.admin', self.libraries.admin);
18
- // console.log('---self.libraries.admin.credential', self.libraries.admin.credential);
19
- // console.log('---self.libraries.admin.credential.cert()', self.libraries.admin.credential.cert());
20
- // console.log('---self.libraries.admin.credential.refreshToken()', self.libraries.admin.credential.refreshToken());
21
- // console.log('---self.libraries.admin.default', self.libraries.admin.default);
22
- // console.log('---self.libraries.initializedAdmin', self.libraries.initializedAdmin);
23
- // console.log('---self.libraries.admin.INTERNAL', self.libraries.admin.INTERNAL);
24
- // console.log('---self.libraries.initializedAdmin.options_.credential', self.libraries.initializedAdmin.options_.credential);
25
- // console.log('---self.libraries.initializedAdmin.options_.credential.refreshToken', self.libraries.initializedAdmin.options_.credential.refreshToken);
26
- // console.log('---self.libraries.initializedAdmin.options_.credential.refreshToken', self.libraries.initializedAdmin.options_.credential.refreshToken);
27
- // console.log('---self.libraries.initializedAdmin.INTERNAL', self.libraries.initializedAdmin.INTERNAL);
28
- // const powertools = require('node-powertools');
29
- // console.log('---self.libraries.admin', powertools.stringify(self.libraries.admin));
30
- // console.log('---self.libraries.initializedAdmin', powertools.stringify(self.libraries.initializedAdmin));
31
-
32
- const providers = [
33
- { name: 'google.com', prefix: ['id_token'] },
34
- { name: 'facebook.com', prefix: ['access_token'] },
35
- { name: 'twitter.com', prefix: ['access_token', 'oauth_token_secret'] },
36
- { name: 'github.com', prefix: ['access_token'] },
37
- { name: 'microsoft.com', prefix: ['id_token'] },
38
- // { name: 'microsoft.com', prefix: ['context', 'continueUri', 'sessionId'] },
39
- { name: 'yahoo.com', prefix: ['id_token'] },
40
- { name: 'apple.com', prefix: ['id_token'] },
41
- ]
42
- const promises = []
43
-
44
- payload.data.payload.firebaseApiKey = payload.data.payload.firebaseApiKey || _.get(Manager, 'config.firebaseConfig.apiKey') || false;
45
-
46
- if (!payload.data.payload.firebaseApiKey) {
47
- return reject(assistant.errorify(`The firebaseApiKey parameter is required.`, {code: 400}));
16
+ const defaultProviders = {
17
+ ['password']: {
18
+ enabled: true,
19
+ },
20
+ ['google.com']: {
21
+ enabled: true,
22
+ },
23
+ ['facebook.com']: {
24
+ enabled: false,
25
+ },
26
+ ['twitter.com']: {
27
+ enabled: false,
28
+ },
29
+ ['github.com']: {
30
+ enabled: false,
31
+ },
32
+ ['microsoft.com']: {
33
+ enabled: false,
34
+ },
35
+ ['yahoo.com']: {
36
+ enabled: false,
37
+ },
38
+ ['apple.com']: {
39
+ enabled: false,
40
+ },
48
41
  }
49
42
 
50
- // Default
51
- payload.response.data.password = true;
52
-
53
- assistant.log('Checking providers for firebaseApiKey', payload.data.payload.firebaseApiKey);
54
-
55
- function request(provider) {
56
- return new Promise(function(resolve, reject) {
57
- let prefix = '';
58
- provider.prefix
59
- .forEach((item, i) => {
60
- prefix += `${item}=LOL&`
61
- });
62
-
63
- // https://firebase.google.com/docs/reference/rest/auth#section-sign-in-with-oauth-credential
64
- fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=${payload.data.payload.firebaseApiKey}`, {
65
- method: 'post',
66
- body: {
67
- postBody: `${prefix}providerId=${provider.name}`,
68
- requestUri: 'http://localhost',
69
- returnIdpCredential: true,
70
- returnSecureToken: true
71
- }
72
- })
73
- .then(response => {
74
- payload.response.data[provider.name] = true;
75
- })
76
- .catch(e => {
77
- try {
78
- const errorJson = JSON.parse(e.message);
79
- const errorArray = errorJson.error.errors || [];
80
- let result = true;
81
-
82
- errorArray
83
- .forEach((error, i) => {
84
- if (error.message.includes('OPERATION_NOT_ALLOWED') || error.message.includes('INVALID_CREDENTIAL_OR_PROVIDER_ID')) {
85
- result = false;
86
- }
87
- assistant.log('Provider check', provider.name, error);
88
- });
89
-
90
- assistant.log('Provider response', provider.name, result);
91
-
92
- payload.response.data[provider.name] = result;
93
- } catch (e) {
94
- assistant.errorify(`Error parsing error: ${e}`, {code: 500, sentry: true});
95
- payload.response.data[provider.name] = false;
96
- }
97
- })
98
- .finally(r => {
99
- return resolve();
100
- })
101
- });
43
+ // Get app
44
+ const appObject = await self.getAppObject();
45
+ if (appObject instanceof Error) {
46
+ return reject(assistant.errorify(`Failed to get app object: ${appObject}`, {code: 500}));
102
47
  }
103
48
 
104
- providers
105
- .forEach((provider, i) => {
106
- payload.response.data[provider.name] = false;
107
- promises.push(request(provider))
49
+ // Merge the default providers with the app providers
50
+ const providers = merge(defaultProviders, appObject.authentication);
51
+
52
+ // Reformat the object so it's just provider=true/false
53
+ const finalProviders = {};
54
+ Object.keys(providers).forEach(key => {
55
+ finalProviders[key] = providers[key].enabled;
108
56
  });
109
57
 
110
- assistant.log('Checking providers...');
111
-
112
- await Promise.all(promises)
113
- .then(response => {
114
- // console.log('--payload.response.data', promises.length, payload.response.data);
115
-
116
- fetch(`https://us-central1-itw-creative-works.cloudfunctions.net/getApp`, {
117
- method: 'post',
118
- response: 'json',
119
- body: {
120
- id: Manager.config.app.id,
121
- }
122
- })
123
- .then(response => {
124
- assistant.log('getApp response', response);
125
- response.authentication = response.authentication || {};
126
-
127
- Object.keys(response.authentication)
128
- .forEach((provider, i) => {
129
- response.authentication[provider] = response.authentication[provider] || {};
130
-
131
- if (typeof response.authentication[provider].enabled !== 'undefined') {
132
- payload.response.data[provider] = response.authentication[provider].enabled;
133
- assistant.log(`Overwriting ${provider} to ${payload.response.data[provider]}...`);
134
- }
135
- });
136
-
137
- })
138
- .catch(e => {
139
- assistant.errorify(`Error getting app data: ${e}`, {code: 500, log: true})
140
- })
141
- .finally(r => {
142
- return resolve({data: payload.response.data});
143
- })
58
+ // Log
59
+ assistant.log('Providers', finalProviders);
144
60
 
61
+ // Resolve
62
+ return resolve({data: finalProviders});
63
+ });
64
+
65
+ };
66
+
67
+ // Get app object
68
+ Module.prototype.getAppObject = function () {
69
+ const self = this;
70
+
71
+ const Manager = self.Manager;
72
+ const Api = self.Api;
73
+ const assistant = self.assistant;
74
+ const payload = self.payload;
75
+
76
+ return new Promise(async function(resolve, reject) {
77
+ const id = Manager.config.app.id;
78
+
79
+ // Get the app settings
80
+ fetch(`https://us-central1-itw-creative-works.cloudfunctions.net/getApp`, {
81
+ method: 'post',
82
+ response: 'json',
83
+ body: {
84
+ id: id,
85
+ }
145
86
  })
146
- .catch(e => {
147
- return reject(assistant.errorify(`Failed to check providers: ${e}`, {code: 500}));
148
- })
87
+ .then((r) => {
88
+ assistant.log('getAppObject(): Response', r);
149
89
 
150
- });
90
+ // If data is missing, return an error
91
+ if (!r) {
92
+ throw new Error(`App with id ${id} not found`);
93
+ }
151
94
 
95
+ // Return the app object
96
+ return resolve(r);
97
+ })
98
+ .catch(e => reject(e));
99
+ });
152
100
  };
153
101
 
154
102
  module.exports = Module;
@@ -4,12 +4,20 @@ const powertools = require('node-powertools');
4
4
  const moment = require('moment');
5
5
  const JSON5 = require('json5');
6
6
 
7
+ // const PROMPT = `
8
+ // Company: {app.name}: {app.brand.description}
9
+ // Date: {date}
10
+ // Instructions: {prompt}
11
+
12
+ // Use the following information to find a topic related to our company:
13
+ // {suggestion}
14
+ // `
7
15
  const PROMPT = `
8
16
  Company: {app.name}: {app.brand.description}
9
17
  Date: {date}
10
18
  Instructions: {prompt}
11
19
 
12
- Use the following information to find a topic related to our company:
20
+ Use the following information to find a topic for our company blog (it can be about our company OR any topic that would be relevant to our website and business BUT not about a competitor):
13
21
  {suggestion}
14
22
  `
15
23
 
@@ -51,9 +59,10 @@ Module.prototype.main = function (assistant, context) {
51
59
 
52
60
  // Fix settings
53
61
  settings.articles = settings.articles || 0;
54
- settings.sources = settings.sources || [];
55
- settings.links = settings.links || [];
62
+ settings.sources = randomize(settings.sources || []);
63
+ settings.links = randomize(settings.links || []);
56
64
  settings.prompt = settings.prompt || '';
65
+ settings.chance = settings.chance || 1.0;
57
66
  settings.app = await self.getAppData(appId).catch((e) => e);
58
67
 
59
68
  // Check for errors
@@ -73,6 +82,12 @@ Module.prototype.main = function (assistant, context) {
73
82
  continue;
74
83
  }
75
84
 
85
+ // Quit if the chance is not met
86
+ const chance = Math.random();
87
+ if (chance > settings.chance) {
88
+ assistant.log(`Quitting because the chance is not met (${chance} <= ${settings.chance})`);
89
+ }
90
+
76
91
  // Harvest articles
77
92
  const result = await self.harvest(settings).catch((e) => e);
78
93
  if (result instanceof Error) {
@@ -320,7 +335,7 @@ const extractBodyContent = (text, contentType, url) => {
320
335
  // Try JSON
321
336
  if (parsed) {
322
337
  // If it's from rss.app, extract the content
323
- if (url.includes('rss.app') && parsed.items) {
338
+ if (parsed.items) {
324
339
  return parsed.items.map((i) => `${i.title}: ${i.content_text}`).join('\n');
325
340
  }
326
341
 
@@ -350,4 +365,9 @@ function tryParse(json) {
350
365
  }
351
366
  };
352
367
 
368
+ // Randomize array
369
+ function randomize(array) {
370
+ return array.sort(() => Math.random() - 0.5);
371
+ }
372
+
353
373
  module.exports = Module;
@@ -46,6 +46,13 @@ Settings.prototype.resolve = function (assistant, schema, settings, options) {
46
46
  // Resolve settings
47
47
  self.settings = powertools.defaults(settings, schema);
48
48
 
49
+ // If schema is not an object, throw an error
50
+ if (!schema || typeof schema !== 'object') {
51
+ throw assistant.errorify(`Invalid schema provided`, {code: 400});
52
+ }
53
+ // console.log('---schema', schema);
54
+ // console.log('---self.settings', self.settings);
55
+
49
56
  // Iterate each key and check for some things
50
57
  processSchema(schema, (path, schemaNode) => {
51
58
  const originalValue = _.get(settings, path);
@@ -638,7 +638,7 @@ Manager.prototype.setupFunctions = function (exporter, options) {
638
638
  // Setup functions
639
639
  exporter.bm_api =
640
640
  self.libraries.functions
641
- .runWith({memory: '256MB', timeoutSeconds: 190})
641
+ .runWith({memory: '256MB', timeoutSeconds: 60 * 5})
642
642
  // TODO: Replace this with new API
643
643
  .https.onRequest(async (req, res) => self._process((new (require(`${core}/actions/api.js`))()).init(self, { req: req, res: res, })));
644
644
 
@@ -849,7 +849,7 @@ Manager.prototype.setupFunctions = function (exporter, options) {
849
849
  // Setup cron jobs
850
850
  exporter.bm_cronDaily =
851
851
  self.libraries.functions
852
- .runWith({ memory: '256MB', timeoutSeconds: 190 })
852
+ .runWith({ memory: '256MB', timeoutSeconds: 60 * 5 })
853
853
  .pubsub.schedule('every 24 hours')
854
854
  .onRun(async (context) => self._process((new (require(`${core}/cron/daily.js`))()).init(self, { context: context, })));
855
855
  };
@@ -42,6 +42,7 @@
42
42
  ],
43
43
  links: [],
44
44
  prompt: '',
45
+ chance: 1.0,
45
46
  }
46
47
  ],
47
48
  }