backend-manager 3.2.172 → 3.2.173

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.
Files changed (87) hide show
  1. package/package.json +3 -3
  2. package/src/cli/cli.js +27 -11
  3. package/dist/cli/cli.js +0 -1534
  4. package/dist/manager/functions/core/actions/api/admin/backup.js +0 -338
  5. package/dist/manager/functions/core/actions/api/admin/create-post.js +0 -388
  6. package/dist/manager/functions/core/actions/api/admin/cron.js +0 -37
  7. package/dist/manager/functions/core/actions/api/admin/database-read.js +0 -35
  8. package/dist/manager/functions/core/actions/api/admin/database-write.js +0 -39
  9. package/dist/manager/functions/core/actions/api/admin/edit-post.js +0 -158
  10. package/dist/manager/functions/core/actions/api/admin/firestore-query.js +0 -165
  11. package/dist/manager/functions/core/actions/api/admin/firestore-read.js +0 -38
  12. package/dist/manager/functions/core/actions/api/admin/firestore-write.js +0 -54
  13. package/dist/manager/functions/core/actions/api/admin/get-stats.js +0 -269
  14. package/dist/manager/functions/core/actions/api/admin/payment-processor.js +0 -57
  15. package/dist/manager/functions/core/actions/api/admin/run-hook.js +0 -95
  16. package/dist/manager/functions/core/actions/api/admin/send-notification.js +0 -197
  17. package/dist/manager/functions/core/actions/api/admin/sync-users.js +0 -125
  18. package/dist/manager/functions/core/actions/api/admin/templates/post.html +0 -16
  19. package/dist/manager/functions/core/actions/api/firebase/get-providers.js +0 -102
  20. package/dist/manager/functions/core/actions/api/general/emails/general:download-app-link.js +0 -21
  21. package/dist/manager/functions/core/actions/api/general/fetch-post.js +0 -99
  22. package/dist/manager/functions/core/actions/api/general/generate-uuid.js +0 -41
  23. package/dist/manager/functions/core/actions/api/general/send-email.js +0 -112
  24. package/dist/manager/functions/core/actions/api/handler/create-post.js +0 -146
  25. package/dist/manager/functions/core/actions/api/special/setup-electron-manager-client.js +0 -103
  26. package/dist/manager/functions/core/actions/api/template.js +0 -33
  27. package/dist/manager/functions/core/actions/api/test/authenticate.js +0 -22
  28. package/dist/manager/functions/core/actions/api/test/create-test-accounts.js +0 -27
  29. package/dist/manager/functions/core/actions/api/test/lab.js +0 -55
  30. package/dist/manager/functions/core/actions/api/test/redirect.js +0 -26
  31. package/dist/manager/functions/core/actions/api/test/webhook.js +0 -30
  32. package/dist/manager/functions/core/actions/api/user/create-custom-token.js +0 -32
  33. package/dist/manager/functions/core/actions/api/user/delete.js +0 -68
  34. package/dist/manager/functions/core/actions/api/user/get-active-sessions.js +0 -45
  35. package/dist/manager/functions/core/actions/api/user/get-subscription-info.js +0 -49
  36. package/dist/manager/functions/core/actions/api/user/oauth2/discord.js +0 -114
  37. package/dist/manager/functions/core/actions/api/user/oauth2/google.js +0 -99
  38. package/dist/manager/functions/core/actions/api/user/oauth2.js +0 -476
  39. package/dist/manager/functions/core/actions/api/user/regenerate-api-keys.js +0 -54
  40. package/dist/manager/functions/core/actions/api/user/resolve.js +0 -32
  41. package/dist/manager/functions/core/actions/api/user/sign-out-all-sessions.js +0 -118
  42. package/dist/manager/functions/core/actions/api/user/sign-up copy.js +0 -544
  43. package/dist/manager/functions/core/actions/api/user/sign-up.js +0 -99
  44. package/dist/manager/functions/core/actions/api/user/submit-feedback.js +0 -96
  45. package/dist/manager/functions/core/actions/api/user/validate-settings.js +0 -86
  46. package/dist/manager/functions/core/actions/api.js +0 -354
  47. package/dist/manager/functions/core/actions/create-post-handler.js +0 -184
  48. package/dist/manager/functions/core/actions/generate-uuid.js +0 -62
  49. package/dist/manager/functions/core/actions/sign-up-handler.js +0 -205
  50. package/dist/manager/functions/core/admin/create-post.js +0 -206
  51. package/dist/manager/functions/core/admin/firestore-write.js +0 -72
  52. package/dist/manager/functions/core/admin/get-stats.js +0 -218
  53. package/dist/manager/functions/core/admin/query.js +0 -198
  54. package/dist/manager/functions/core/admin/send-notification.js +0 -206
  55. package/dist/manager/functions/core/cron/daily/ghostii-auto-publisher.js +0 -377
  56. package/dist/manager/functions/core/cron/daily/reset-usage.js +0 -197
  57. package/dist/manager/functions/core/cron/daily.js +0 -114
  58. package/dist/manager/functions/core/events/auth/before-create.js +0 -124
  59. package/dist/manager/functions/core/events/auth/before-signin.js +0 -62
  60. package/dist/manager/functions/core/events/auth/on-create copy.js +0 -121
  61. package/dist/manager/functions/core/events/auth/on-create.js +0 -564
  62. package/dist/manager/functions/core/events/auth/on-delete.js +0 -72
  63. package/dist/manager/functions/core/events/firestore/on-subscription.js +0 -107
  64. package/dist/manager/functions/test/authenticate.js +0 -38
  65. package/dist/manager/functions/test/create-test-accounts.js +0 -144
  66. package/dist/manager/functions/test/webhook.js +0 -37
  67. package/dist/manager/functions/wrappers/mailchimp/addToList.js +0 -25
  68. package/dist/manager/helpers/analytics copy.js +0 -217
  69. package/dist/manager/helpers/analytics.js +0 -467
  70. package/dist/manager/helpers/api-manager.js +0 -324
  71. package/dist/manager/helpers/assistant.js +0 -1043
  72. package/dist/manager/helpers/metadata.js +0 -32
  73. package/dist/manager/helpers/middleware.js +0 -154
  74. package/dist/manager/helpers/roles.js +0 -69
  75. package/dist/manager/helpers/settings.js +0 -158
  76. package/dist/manager/helpers/subscription-resolver-new.js +0 -828
  77. package/dist/manager/helpers/subscription-resolver.js +0 -842
  78. package/dist/manager/helpers/usage.js +0 -381
  79. package/dist/manager/helpers/user.js +0 -198
  80. package/dist/manager/helpers/utilities.js +0 -292
  81. package/dist/manager/index.js +0 -1076
  82. package/dist/manager/libraries/openai.js +0 -460
  83. package/dist/manager/routes/restart/index.js +0 -52
  84. package/dist/manager/routes/test/index.js +0 -43
  85. package/dist/manager/schemas/restart.js +0 -13
  86. package/dist/manager/schemas/test.js +0 -13
  87. package/dist/require.js +0 -3
@@ -1,184 +0,0 @@
1
- let Poster;
2
- let pathApi;
3
- let os;
4
- // let JSON5;
5
- const fetch = require('node-fetch');
6
- const Mailchimp = require('mailchimp-api-v3');
7
- const { get, merge } = require('lodash');
8
-
9
- let Module = {
10
- init: async function (Manager, data) {
11
- const self = this;
12
- self.Manager = Manager;
13
- self.libraries = Manager.libraries;
14
- self.assistant = Manager.Assistant({req: data.req, res: data.res});
15
- self.req = data.req;
16
- self.res = data.res;
17
-
18
- return self;
19
- },
20
- main: async function() {
21
- let self = this;
22
- let libraries = self.libraries;
23
- let assistant = self.assistant;
24
- let req = self.req;
25
- let res = self.res;
26
- let mailchimp;
27
-
28
- let response = {
29
- status: 200,
30
- };
31
-
32
- return libraries.cors(req, res, async () => {
33
- // authenticate admin!
34
- let user = await assistant.authenticate();
35
-
36
- // Analytics
37
- let analytics = self.Manager.Analytics({
38
- assistant: assistant,
39
- uuid: user.auth.uid,
40
- })
41
- .event({
42
- category: 'admin',
43
- action: 'post-created',
44
- // label: '',
45
- });
46
-
47
- assistant.log('Creating campagin with data', assistant.request.data)
48
-
49
- if (!user.roles.admin) {
50
- response.status = 401;
51
- response.error = new Error('Unauthenticated, admin required.');
52
- assistant.error(response.error)
53
- } else {
54
- mailchimp = new Mailchimp(get(self.Manager.config, 'mailchimp.key', ''));
55
- await fetch(`https://us-central1-${self.Manager.project.projectId}.cloudfunctions.net/bm_sendNotification`, {
56
- method: 'POST',
57
- headers: { 'Content-Type': 'application/json' },
58
- body: JSON.stringify(merge({}, {
59
- payload: {
60
- title: 'New blog post!',
61
- click_action: assistant.request.data.url,
62
- body: `"${assistant.request.data.title}" was just published on our blog. It's a great read and we think you'll enjoy the content!`,
63
- icon: assistant.request.data.imageUrl,
64
- }
65
- },
66
- assistant.request.data
67
- )),
68
- })
69
- .then(res => {
70
- if (res.status >= 200 && res.status < 300) {
71
- res.json()
72
- .then(function (data) {
73
- assistant.log('Push notification response', data)
74
- })
75
- } else {
76
- return res.text()
77
- .then(function (data) {
78
- throw new Error(data || res.statusTest || 'Unknown error.')
79
- })
80
- }
81
- })
82
- .catch(e => {
83
- assistant.error('Failed to send push notification', e);
84
- })
85
- return res.send('DONE');
86
- await mailchimp.post(`/campaigns`, {
87
- "type": "regular",
88
- "recipients": {
89
- "list_id": get(self.Manager.config, 'mailchimp.list_id', ''),
90
- },
91
- "settings": {
92
- "subject_line": `${assistant.request.data.title}`,
93
- // "preview_text": "",
94
- "title": `Blog post: "${assistant.request.data.title}"`,
95
- "from_name": get(self.Manager.config, 'brand.name'),
96
- "reply_to": get(self.Manager.config, 'brand.email'),
97
- "use_conversation": false,
98
- "to_name": "*|FNAME|*",
99
- // "folder_id": "",
100
- "authenticate": false,
101
- },
102
- })
103
- .then(async (campaign) => {
104
- assistant.log('Created campaign', campaign);
105
- await fetch(`https://email.itwcreativeworks.com/general/mailchimp-blog-syndication?cb=${Math.random()}`)
106
- .then(async (fetchResponse) => {
107
- if (fetchResponse.status >= 200 && fetchResponse.status < 300) {
108
- let html = await fetchResponse.text();
109
- html = html
110
- .replace(/{ENTRY_TITLE}/g, assistant.request.data.title)
111
- .replace(/{ENTRY_URL}/g, assistant.request.data.url)
112
- .replace(/{ENTRY_IMAGE_URL}/g, assistant.request.data.imageUrl)
113
- .replace(/{ENTRY_CONTENT}/g, (assistant.request.data.content || '').split('\n')[0])
114
- .replace(/{ENTRY_PUBLISHED}/g, assistant.request.data.published)
115
- .replace(/{ENTRY_AUTHOR}/g, assistant.request.data.author)
116
- .replace(/{ENTRY_TAGS}/g, assistant.request.data.tags)
117
- .replace(/{BRAND_NAME}/g, get(self.Manager.config, 'brand.name'))
118
- .replace(/{BRAND_LOGO_COMBOMARK}/g, get(self.Manager.config, 'brand.combomark'))
119
- .replace(/{BRAND_LOGO_WORDMARK}/g, get(self.Manager.config, 'brand.wordmark'))
120
- // assistant.log('Resolved email', html);
121
- await mailchimp.put(`/campaigns/${campaign.id}/content`, {
122
- "content": 'regular',
123
- "html": html,
124
- })
125
- .then(async (content) => {
126
- await mailchimp.post(`/campaigns/${campaign.id}/actions/send`)
127
- assistant.log('Mailchimp campaign created and sent', campaign);
128
- })
129
- } else {
130
- throw new Error('Failed to fetch.');
131
- }
132
- })
133
- })
134
- .catch(e => {
135
- // assistant.error('Failed to send Mailchimp campaign', e);
136
- assistant.error('Failed to send Mailchimp campaign');
137
- })
138
- }
139
-
140
- if (response.status === 200) {
141
- return res.status(response.status).json(response.data);
142
- } else {
143
- return res.status(response.status).send(response.error.message);
144
- }
145
- });
146
- }
147
- }
148
-
149
- module.exports = Module;
150
-
151
- // HELPERS //
152
- // function callMailChimp(options) {
153
- //
154
- // }
155
- //
156
- // function addToMCList(key, listId, email) {
157
- // return new Promise((resolve, reject) => {
158
- // let datacenter = key.split('-')[1];
159
- // fetch = require('node-fetch');
160
- // fetch(`https://${datacenter}.api.mailchimp.com/3.0/lists/${listId}/members`, {
161
- // method: 'post',
162
- // body: JSON.stringify({
163
- // email_address: email,
164
- // status: 'subscribed',
165
- // }),
166
- // timeout: 10000,
167
- // headers: {
168
- // 'Content-Type': 'application/json',
169
- // 'Authorization': `Basic ${key}`,
170
- // },
171
- // })
172
- // .then(res => res.json())
173
- // .then(json => {
174
- // if (json.status !== 'subscribed') {
175
- // return reject(new Error(json.status));
176
- // }
177
- // return resolve(json);
178
- // })
179
- // .catch(e => {
180
- // return reject(e);
181
- // })
182
- //
183
- // });
184
- // }
@@ -1,62 +0,0 @@
1
- const uuid = require('uuid');
2
-
3
- let Module = {
4
- init: async function (Manager, data) {
5
- this.Manager = Manager;
6
- this.libraries = Manager.libraries;
7
- this.assistant = Manager.Assistant({req: data.req, res: data.res})
8
- this.req = data.req;
9
- this.res = data.res;
10
-
11
- return this;
12
- },
13
- main: async function() {
14
- let self = this;
15
- let libraries = self.libraries;
16
- let assistant = self.assistant;
17
- let req = self.req;
18
- let res = self.res;
19
-
20
- let response = {
21
- status: 200,
22
- data: {},
23
- };
24
-
25
- return libraries.cors(req, res, async () => {
26
- let user = await assistant.authenticate();
27
-
28
- // Analytics
29
- let analytics = self.Manager.Analytics({
30
- assistant: assistant,
31
- uuid: user.auth.uid,
32
- })
33
- .event({
34
- category: 'admin',
35
- action: 'generate-uuid',
36
- // label: '',
37
- });
38
-
39
- const namespace = assistant.request.data.namespace || self.Manager.config.backend_manager.namespace;
40
- assistant.request.data.version = `${assistant.request.data.version || '5'}`.replace('v', '');
41
- assistant.request.data.name = assistant.request.data.name || assistant.request.data.input;
42
-
43
- if (!assistant.request.data.name) {
44
- response.status = 400;
45
- response.error = new Error('You must provide a name to hash');
46
- } else if (assistant.request.data.version === '5') {
47
- response.data.uuid = uuid.v5(assistant.request.data.name, namespace);
48
- } else if (assistant.request.data.version === '4') {
49
- response.data.uuid = uuid.v4();
50
- }
51
-
52
- assistant.log('UUID Generated', assistant.request.data, response);
53
-
54
- if (response.status === 200) {
55
- return res.status(response.status).json(response.data);
56
- } else {
57
- return res.status(response.status).send(response.error.message);
58
- }
59
- });
60
- },
61
- }
62
- module.exports = Module;
@@ -1,205 +0,0 @@
1
- let fetch;
2
- const _ = require('lodash');
3
-
4
- let Module = {
5
- init: async function (Manager, data) {
6
- this.Manager = Manager;
7
- this.libraries = Manager.libraries;
8
- this.assistant = Manager.Assistant({req: data.req, res: data.res})
9
- this.req = data.req;
10
- this.res = data.res;
11
-
12
- return this;
13
- },
14
- main: async function() {
15
- let self = this;
16
- let libraries = self.libraries;
17
- let assistant = self.assistant;
18
- let req = self.req;
19
- let res = self.res;
20
-
21
- let response = {
22
- status: 200,
23
- data: {},
24
- };
25
-
26
-
27
- return libraries.cors(req, res, async () => {
28
- let user = await assistant.authenticate();
29
-
30
- if (!user.authenticated) {
31
- response.status = 401;
32
- response.error = new Error('Account does not exist in Auth.');
33
- } else {
34
- await self.signUp({
35
- auth: {
36
- uid: user.auth.uid,
37
- email: user.auth.email,
38
- },
39
- affiliate: {
40
- referredBy: assistant.request.data.affiliateCode
41
- },
42
- })
43
- .then(async function (result) {
44
- response.data = result;
45
- if (assistant.request.data.newsletterSignUp) {
46
- await addToMCList(
47
- _.get(self.Manager.config, 'mailchimp.key'),
48
- _.get(self.Manager.config, 'mailchimp.list_id'),
49
- user.auth.email,
50
- )
51
- .then(function (res) {
52
- assistant.log('Sucessfully added user to MC list.')
53
- })
54
- .catch(function (error) {
55
- assistant.log('Failed to add user to MC list.', error)
56
- })
57
- }
58
- })
59
- .catch(function (e) {
60
- response.status = 400;
61
- response.error = e;
62
- assistant.error('Failed to signup:', response.error);
63
- })
64
- }
65
-
66
- assistant.log('Signup handler:', assistant.request.data, response);
67
-
68
- if (response.status === 200) {
69
- return res.status(response.status).json(response.data);
70
- } else {
71
- assistant.error('Failed to signup:', assistant.request.data, user);
72
- return res.status(response.status).send(response.error.message);
73
- }
74
- });
75
- },
76
- signUp: async function (payload) {
77
- let self = this;
78
- let response = {};
79
- let error;
80
- payload = payload || {};
81
-
82
- return new Promise(async function(resolve, reject) {
83
- let existingUser = {};
84
- let finalPayload = {};
85
- let user = self.Manager.User(payload);
86
-
87
- if (!_.get(payload, 'auth.uid', null) || !_.get(payload, 'auth.email', null)) {
88
- return reject(new Error('Cannot create user without UID and email.'))
89
- }
90
-
91
- await self.libraries.admin.firestore().doc(`users/${payload.auth.uid}`)
92
- .get()
93
- .then(async function (doc) {
94
- existingUser = doc.data() || {};
95
- })
96
- .catch(function (e) {
97
- error = e;
98
- })
99
-
100
- if (error) {
101
- return reject(error);
102
- }
103
-
104
- // Merge the payload and the default user object
105
- finalPayload = _.merge({}, existingUser, user.properties)
106
-
107
- self.updateReferral({
108
- affiliateCode: _.get(payload, 'affiliate.referredBy', null),
109
- uid: payload.auth.uid,
110
- })
111
- .catch(function (e) {
112
- assistant.log('Failed to update affiliate code')
113
- })
114
-
115
- self.libraries.admin.firestore().doc(`users/${payload.auth.uid}`)
116
- .set(finalPayload, { merge: true })
117
- .then(function(data) {
118
- response.status = 200;
119
- response.data = {created: true};
120
- return resolve(response);
121
- })
122
- .catch(function(error) {
123
- return reject(error);
124
- })
125
-
126
- });
127
- },
128
- updateReferral: async function (payload) {
129
- let self = this;
130
- payload = payload || {};
131
-
132
- let response = {};
133
-
134
- return new Promise(function(resolve, reject) {
135
- self.libraries.admin.firestore().collection('users')
136
- .where('affiliate.code', '==', payload.affiliateCode)
137
- .get()
138
- .then(snapshot => {
139
- if (snapshot.empty) {
140
- response.status = 200;
141
- response.referrals = 0;
142
- return resolve()
143
- }
144
- let count = 0;
145
- snapshot.forEach(doc => {
146
- let data = doc.data() || {};
147
- let referrals = data.affiliate && data.affiliate.referrals ? data.affiliate.referrals : [];
148
- referrals = Array.isArray(referrals) ? referrals : [];
149
- count = referrals.length;
150
- referrals = referrals.concat({
151
- uid: payload.uid,
152
- timestamp: self.assistant.meta.startTime.timestamp,
153
- })
154
-
155
- self.libraries.admin.firestore().doc(`users/${doc.id}`)
156
- .set({
157
- affiliate: {
158
- referrals: referrals
159
- }
160
- }, {merge: true})
161
- });
162
- response.status = 200;
163
- response.referrals = count;
164
- return resolve()
165
- })
166
- .catch(err => {
167
- response.status = 500;
168
- response.error = err;
169
- return reject(response);
170
- });
171
- });
172
- }
173
- }
174
- module.exports = Module;
175
-
176
- // HELPERS //
177
- function addToMCList(key, listId, email) {
178
- return new Promise((resolve, reject) => {
179
- let datacenter = key.split('-')[1];
180
- fetch = fetch || require('node-fetch');
181
- fetch(`https://${datacenter}.api.mailchimp.com/3.0/lists/${listId}/members`, {
182
- method: 'post',
183
- body: JSON.stringify({
184
- email_address: email,
185
- status: 'subscribed',
186
- }),
187
- timeout: 10000,
188
- headers: {
189
- 'Content-Type': 'application/json',
190
- 'Authorization': `Basic ${key}`,
191
- },
192
- })
193
- .then(res => res.json())
194
- .then(json => {
195
- if (json.status !== 'subscribed') {
196
- return reject(new Error(json.status));
197
- }
198
- return resolve(json);
199
- })
200
- .catch(e => {
201
- return reject(e);
202
- })
203
-
204
- });
205
- }
@@ -1,206 +0,0 @@
1
- let fetch;
2
- let Poster;
3
- let pathApi;
4
- let os;
5
- const { get } = require('lodash');
6
- let Module = {
7
- init: async function (Manager, data) {
8
- this.Manager = Manager;
9
- this.libraries = Manager.libraries;
10
- this.assistant = Manager.Assistant({req: data.req, res: data.res});
11
- this.req = data.req;
12
- this.res = data.res;
13
-
14
- return this;
15
- },
16
- main: async function() {
17
- let self = this;
18
- let libraries = self.libraries;
19
- let assistant = self.assistant;
20
- let req = self.req;
21
- let res = self.res;
22
-
23
- let response = {
24
- status: 200,
25
- };
26
-
27
- return libraries.cors(req, res, async () => {
28
- // authenticate admin!
29
- let user = await assistant.authenticate();
30
-
31
- // Analytics
32
- let analytics = self.Manager.Analytics({
33
- assistant: assistant,
34
- uuid: user.auth.uid,
35
- })
36
- .event({
37
- category: 'admin',
38
- action: 'create-post',
39
- // label: '',
40
- });
41
-
42
- let repoInfo = assistant.parseRepo(get(self.Manager.config, 'github.repo_website'));
43
-
44
- if (!user.roles.admin) {
45
- response.status = 401;
46
- response.error = new Error('Unauthenticated, admin required.');
47
- assistant.error(response.error)
48
- } else {
49
- // Poster = Poster || require('/Users/ianwiedenman/Documents/GitHub/ITW-Creative-Works/ultimate-jekyll-poster');
50
- Poster = Poster || require('ultimate-jekyll-poster');
51
-
52
- let poster = new Poster();
53
-
54
- // Save to disk OR commit
55
- poster.onDownload = async function (meta) {
56
- return new Promise(async function(resolve, reject) {
57
- let finalPath = poster.removeDirDot(meta.finalPath);
58
- let tempPath = (meta.tempPath);
59
- await createFile(get(self.Manager.config, 'github.user'), repoInfo.user, repoInfo.name, get(self.Manager.config, 'github.key'), finalPath, await poster.readImage(tempPath))
60
- .catch((e) => {
61
- // console.log('---CAUGHT 1', e);
62
- })
63
- resolve();
64
- });
65
- }
66
-
67
- let finalPost = await poster.create(assistant.request.data);
68
-
69
- // Save post OR commit
70
- await createFile(get(self.Manager.config, 'github.user'), repoInfo.user, repoInfo.name, get(self.Manager.config, 'github.key'), poster.removeDirDot(finalPost.path), finalPost.content)
71
- .catch((e) => {
72
- response.status = 400;
73
- response.error = new Error('Failed to post: ' + e);
74
- assistant.error(response.error)
75
- })
76
- }
77
-
78
- assistant.log('Post', assistant.request.data, response);
79
-
80
- if (response.status === 200) {
81
- return res.status(response.status).json(response.data);
82
- } else {
83
- return res.status(response.status).send(response.error.message);
84
- }
85
- });
86
- }
87
- }
88
- module.exports = Module;
89
-
90
- // HELPERS //
91
- async function createFile(user, repoUser, repoName, key, path, contents) {
92
- pathApi = pathApi || require('path');
93
- let fileParsed = pathApi.parse(path);
94
-
95
- let base64Data = Buffer.from(contents).toString('base64');
96
- // base64Data = contents;
97
- // console.log('--------base64Data', base64Data);
98
- return new Promise(async (resolve, reject) => {
99
- let sha;
100
- try {
101
-
102
- let branch = (repoName === 'ultimate-jekyll') ? 'template' : 'master';
103
-
104
- let pathGet = `https://api.github.com/repos/${repoUser}/${repoName}/git/trees/${branch}:${encodeURIComponent(pathApi.dirname(path))}`;
105
- await makeRequest({
106
- method: 'GET',
107
- url: pathGet,
108
- body: {
109
- },
110
- timeout: 30000,
111
- json: true,
112
- headers: {
113
- 'User-Agent': user,
114
- // 'Authorization': `Basic ${user}:${key}`,
115
- 'Authorization': `Basic ${Buffer.from(user + ':' + key).toString('base64')}`,
116
- }
117
- })
118
- .then(function (resp) {
119
- // sha = resp.sha;
120
- sha = resp.tree.find(function (element) {
121
- // console.log('checiing', element.path, fileParsed.base);
122
- return element.path === fileParsed.base;
123
- });
124
- sha = sha.sha;
125
- });
126
- } catch (e) {
127
- sha = null;
128
- }
129
-
130
- let pathPut = `https://api.github.com/repos/${repoUser}/${repoName}/contents/${path}`;
131
- let writeRequest =
132
- {
133
- // url: `https://api.github.com/repos/:owner/:repo/contents/:path`,
134
- method: 'PUT',
135
- url: pathPut,
136
- body: {
137
- message: `BackendManager Post: ${new Date().toISOString()}`,
138
- content: base64Data,
139
- },
140
- timeout: 30000,
141
- json: true,
142
- headers: {
143
- 'User-Agent': user,
144
- // 'Authorization': `Basic ${user}:${key}`,
145
- 'Authorization': `Basic ${Buffer.from(user + ':' + key).toString('base64')}`,
146
- }
147
- }
148
- if (sha) {
149
- writeRequest.body.sha = sha;
150
- }
151
- // console.log('--------PUT', pathPut);
152
- await makeRequest(writeRequest)
153
- .then((json) => {
154
- if (!json || (json.message && (json.message === 'Not Found' || json.message.includes('Invalid request'))) ) {
155
- return reject(new Error(json.message));
156
- }
157
- })
158
- .catch((e) => {
159
- return reject(e);
160
- })
161
- return resolve(true)
162
- });
163
- }
164
-
165
- function makeRequest(options) {
166
- return new Promise(function(resolve, reject) {
167
- fetch = fetch || require('node-fetch');
168
- options.headers = options.headers || {};
169
- options.headers['Content-Type'] = 'application/json';
170
- let hasBody = Object.keys(options.body || {}).length > 0
171
- fetch(options.url, {
172
- method: options.method,
173
- body: hasBody ? JSON.stringify(options.body) : undefined,
174
- timeout: 30000,
175
- headers: options.headers,
176
- auth: options.auth,
177
- })
178
- .then(res => res.json())
179
- .then(json => {
180
- return resolve(json);
181
- })
182
- .catch(e => {
183
- // console.error('e', e);
184
- return reject(e);
185
- })
186
-
187
- });
188
- }
189
-
190
-
191
- // function makeRequest(options) {
192
- // return new Promise(function(resolve, reject) {
193
- // request = request || require('request');
194
- // request(options,
195
- // function (err, httpResponse, body) {
196
- // if (err) {
197
- // // console.log('ERROR', err);
198
- // reject(err);
199
- // } else {
200
- // // console.log('SUCCESS', body);
201
- // resolve(body);
202
- // }
203
- // }
204
- // );
205
- // });
206
- // }