-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrepo.js
257 lines (214 loc) · 6.54 KB
/
repo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
* Functions to work with GitHub
*/
const axios = require('axios');
const uploadToGithub = require('./upload')
const token = process.env['GITHUB_TOKEN'];
const maxBlockSizeMB = parseInt(process.env['BLOCK_SIZE_MB']) || 1000;
const maxFileSizeMB = parseInt(process.env['MAX_FILE_SIZE_MB']) || 50;
const isRepoPrivate = process.env['IS_PRIVATE'] || false;
let API_URL;
// Global state
const gitState = {
workingBlock: 0,
blockLetter: 'localb',
pattern: /localb\d+/,
username: process.env['GITHUB_USERNAME'] || null
}
if (process.env['GITHUB_ORGANIZATION']) {
API_URL = `https://api.github.com/orgs/${process.env['GITHUB_ORGANIZATION']}`;
gitState.blockLetter = 'orgb';
gitState.pattern = new RegExp(/orgb\d+/);
} else {
API_URL = "https://api.github.com/user";
}
// Run once at server initialization
function connectToGitHub() {
return new Promise((resolve, reject) => {
switchToNextBlock()
.then(() => {
console.log(`[connectToGithub]: New working block is ${gitState.blockLetter}${gitState.workingBlock}`);
resolve();
})
.catch(error => {
console.log(error);
reject();
})
});
}
// Run on POST /stats
function getStats() {
return getRepoInfo().then(info => ({
currentBlock: gitState.workingBlock,
currentBlockSize: info.currentBlockSize,
maxBlockSizeMB: maxBlockSizeMB,
totalUploaded: info.totalUploaded
}));
}
function getRepoInfo() {
let currentBlockSize = null;
let totalUploaded = 0;
return new Promise(resolve => {
getAllBlocks()
.then(blocks => {
Object.keys(blocks).forEach(blockName => {
const block = blocks[blockName];
totalUploaded += block.size;
});
currentBlockSize = blocks[gitState.blockLetter + gitState.workingBlock].size;
resolve({
currentBlockSize,
totalUploaded
});
});
});
}
function createBlock(blockNum) {
blockNum = parseInt(blockNum);
console.log(`Creating block ${gitState.blockLetter}${blockNum}`);
const DATA = {
name: `${gitState.blockLetter}${blockNum}`,
description: `Block ${blockNum}`,
homepage: "https://morejust.store/",
private: isRepoPrivate,
has_issues: false,
has_projects: false,
has_wiki: false,
license_template: "unlicense"
};
return new Promise((resolve, reject) => {
axios.post(`${API_URL}/repos?access_token=${token}`, DATA)
.then(response => {
console.log('✅ Block was created');
// Getting repo owner
if (!gitState.username) {
gitState.username = response.data.owner.login;
console.log('😎 Set up owner:', response.data.owner.login);
}
resolve('✅ Block was created');
})
.catch(({ message }) => {
reject(`⚠️ Block was not created, errorMessage=${message}`);
});
});
}
function switchToNextBlock() {
return new Promise((resolve, reject) => {
getAllBlocks()
.then(blocks => {
let needToCreateThisBlock = false;
// Just for test
// blocks['b1'].size = 1000000;
// blocks['b2'].size = 1000000;
// blocks['b3'].size = 1000000;
// blocks['b4'].size = 1000000;
// Selecting next working block
let nextBlock = gitState.workingBlock;
while (true) {
nextBlock += 1;
// If block exists
const selectedBlock = blocks[gitState.blockLetter + nextBlock];
if (selectedBlock) {
if (hasEnoughSpace(selectedBlock)) {
console.log(`[SwitchBlocks]: Selecting ${gitState.blockLetter}${nextBlock}`);
gitState.workingBlock = nextBlock;
break;
} else {
console.log(`[SwitchBlocks]: Block ${gitState.blockLetter}${nextBlock} is full`);
}
} else {
console.log(`[SwitchBlocks]: Need to create ${gitState.blockLetter} ${nextBlock}`);
gitState.workingBlock = nextBlock;
needToCreateThisBlock = true;
break;
}
}
if (needToCreateThisBlock) {
createBlock(nextBlock)
.then(() => {
resolve('✅ New working block selected');
})
.catch((error) => {
console.log(error);
reject('🛑 Error in selecting next block');
})
} else {
resolve('✅ New working block selected');
}
});
});
}
// Returns True if we can use block for uploads, otherwise - False
function hasEnoughSpace(block) {
return block.size < (maxBlockSizeMB - maxFileSizeMB) * 1000;
}
// Returns Object with all block {'b1': repo}
function getAllBlocks() {
return new Promise((resolve, reject) => {
let blocks = {};
axios.get(`${API_URL}/repos?access_token=${token}`)
.then(gitResponse => {
// Going through each repo
gitResponse.data.forEach(repo => {
// It this repo is block
if (gitState.pattern.test(repo.name)) {
console.log('[getAllBlocks]: Found repo', repo.full_name);
blocks[repo.name] = repo;
if (!gitState.username) {
gitState.username = repo.owner.login;
console.log('😎 Set up owner:', repo.owner.login);
}
}
});
resolve(blocks);
})
.catch(error => {
console.log(error);
reject('🛑 Unable to get All Blocks from GitHub');
});
});
}
function uploadToCurrentBlock(filePath) {
return uploadToGithub(gitState.username, `${gitState.blockLetter}${gitState.workingBlock}`, filePath);
}
async function uploadToNextBlock(filePath) {
console.log('[uploadToNextBlock]:', '-> switching to next block')
await switchToNextBlock()
return await uploadToCurrentBlock(filePath)
}
async function upload(filePath) {
console.log('[upload]:', 'uploading', filePath)
try {
console.log('[upload]:', '== trying upload to current block')
return await uploadToCurrentBlock(filePath)
} catch ({ error }) {
if (error !== 'no free space') {
console.error('[upload]:', 'xxx error:', error)
throw error
}
console.log('[upload]:', '== trying upload to next block')
return uploadToNextBlock(filePath)
}
}
function uploadFiles(files) {
return files.reduce(
(load, file) => load.then(async (urls) => {
console.log("[uploadFiles]: File was saved at:", file.path);
try {
const file_url = await upload(file.path);
return [ ...urls, file_url ];
} catch (err) {
console.error("[uploadFiles]:", 'Error uploading file', file.path);
console.error(err);
return [ ...urls, '' ];
}
}),
Promise.resolve([])
);
}
module.exports = {
gitState,
connectToGitHub,
getStats,
uploadFiles
};