2016-08-30 19:06:20 -03:00
|
|
|
import LocalForage from 'localforage';
|
|
|
|
import MediaProxy from '../../valueObjects/MediaProxy';
|
|
|
|
import { Base64 } from 'js-base64';
|
2016-09-13 14:31:18 -03:00
|
|
|
import _ from 'lodash';
|
|
|
|
import { SIMPLE, EDITORIAL_WORKFLOW, status } from '../../constants/publishModes';
|
2016-08-30 19:06:20 -03:00
|
|
|
|
|
|
|
const API_ROOT = 'https://api.github.com';
|
|
|
|
|
|
|
|
export default class API {
|
|
|
|
constructor(token, repo, branch) {
|
|
|
|
this.token = token;
|
|
|
|
this.repo = repo;
|
|
|
|
this.branch = branch;
|
|
|
|
this.repoURL = `/repos/${this.repo}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
user() {
|
|
|
|
return this.request('/user');
|
|
|
|
}
|
|
|
|
|
|
|
|
requestHeaders(headers = {}) {
|
|
|
|
return {
|
|
|
|
Authorization: `token ${this.token}`,
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
...headers
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
parseJsonResponse(response) {
|
|
|
|
return response.json().then((json) => {
|
|
|
|
if (!response.ok) {
|
|
|
|
return Promise.reject(json);
|
|
|
|
}
|
|
|
|
|
|
|
|
return json;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-09-04 14:01:28 +02:00
|
|
|
urlFor(path, options) {
|
|
|
|
const params = [];
|
|
|
|
if (options.params) {
|
|
|
|
for (const key in options.params) {
|
|
|
|
params.push(`${key}=${encodeURIComponent(options.params[key])}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (params.length) {
|
|
|
|
path += `?${params.join('&')}`;
|
|
|
|
}
|
|
|
|
return API_ROOT + path;
|
|
|
|
}
|
|
|
|
|
2016-08-30 19:06:20 -03:00
|
|
|
request(path, options = {}) {
|
|
|
|
const headers = this.requestHeaders(options.headers || {});
|
2016-09-04 14:01:28 +02:00
|
|
|
const url = this.urlFor(path, options);
|
|
|
|
return fetch(url, { ...options, headers: headers }).then((response) => {
|
2016-08-30 19:06:20 -03:00
|
|
|
if (response.headers.get('Content-Type').match(/json/)) {
|
|
|
|
return this.parseJsonResponse(response);
|
|
|
|
}
|
|
|
|
|
|
|
|
return response.text();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-31 16:41:29 -03:00
|
|
|
checkMetadataRef() {
|
|
|
|
return this.request(`${this.repoURL}/git/refs/meta/_netlify_cms?${Date.now()}`, {
|
2016-08-31 13:30:14 -03:00
|
|
|
cache: 'no-store',
|
2016-08-30 19:06:20 -03:00
|
|
|
})
|
2016-08-31 16:41:29 -03:00
|
|
|
.then(response => response.object)
|
2016-08-30 19:06:20 -03:00
|
|
|
.catch(error => {
|
2016-08-31 16:41:29 -03:00
|
|
|
// Meta ref doesn't exist
|
2016-08-30 19:06:20 -03:00
|
|
|
const readme = {
|
2016-08-31 16:41:29 -03:00
|
|
|
raw: '# Netlify CMS\n\nThis tree is used by the Netlify CMS to store metadata information for specific files and branches.'
|
2016-08-30 19:06:20 -03:00
|
|
|
};
|
|
|
|
|
2016-08-31 13:30:14 -03:00
|
|
|
return this.uploadBlob(readme)
|
2016-08-30 19:06:20 -03:00
|
|
|
.then(item => this.request(`${this.repoURL}/git/trees`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({ tree: [{ path: 'README.md', mode: '100644', type: 'blob', sha: item.sha }] })
|
|
|
|
}))
|
2016-08-31 13:30:14 -03:00
|
|
|
.then(tree => this.commit('First Commit', tree))
|
2016-08-31 16:41:29 -03:00
|
|
|
.then(response => this.createRef('meta', '_netlify_cms', response.sha))
|
2016-08-31 13:30:14 -03:00
|
|
|
.then(response => response.object);
|
2016-08-30 19:06:20 -03:00
|
|
|
});
|
2016-08-31 13:30:14 -03:00
|
|
|
}
|
2016-08-30 19:06:20 -03:00
|
|
|
|
2016-08-31 15:44:00 -03:00
|
|
|
storeMetadata(key, data) {
|
2016-08-31 17:33:12 -03:00
|
|
|
return this.checkMetadataRef()
|
2016-08-31 13:30:14 -03:00
|
|
|
.then((branchData) => {
|
|
|
|
const fileTree = {
|
2016-08-31 15:44:00 -03:00
|
|
|
[`${key}.json`]: {
|
|
|
|
path: `${key}.json`,
|
2016-08-31 13:30:14 -03:00
|
|
|
raw: JSON.stringify(data),
|
|
|
|
file: true
|
|
|
|
}
|
|
|
|
};
|
2016-08-30 19:06:20 -03:00
|
|
|
|
2016-08-31 15:44:00 -03:00
|
|
|
return this.uploadBlob(fileTree[`${key}.json`])
|
2016-08-31 13:30:14 -03:00
|
|
|
.then(item => this.updateTree(branchData.sha, '/', fileTree))
|
2016-08-31 15:44:00 -03:00
|
|
|
.then(changeTree => this.commit(`Updating “${key}” metadata`, changeTree))
|
2016-09-13 16:00:24 -03:00
|
|
|
.then(response => this.patchRef('meta', '_netlify_cms', response.sha))
|
|
|
|
.then(() => {
|
|
|
|
LocalForage.setItem(`gh.meta.${key}`, {
|
|
|
|
expires: Date.now() + 300000, // In 5 minutes
|
|
|
|
data
|
|
|
|
});
|
|
|
|
});
|
2016-08-31 13:30:14 -03:00
|
|
|
});
|
2016-08-30 19:06:20 -03:00
|
|
|
}
|
|
|
|
|
2016-09-06 17:18:27 -03:00
|
|
|
retrieveMetadata(key) {
|
2016-09-13 16:00:24 -03:00
|
|
|
const cache = LocalForage.getItem(`gh.meta.${key}`);
|
|
|
|
return cache.then((cached) => {
|
|
|
|
if (cached && cached.expires > Date.now()) { return cached.data; }
|
|
|
|
|
|
|
|
return this.request(`${this.repoURL}/contents/${key}.json`, {
|
|
|
|
params: { ref: 'refs/meta/_netlify_cms' },
|
|
|
|
headers: { Accept: 'application/vnd.github.VERSION.raw' },
|
|
|
|
cache: 'no-store',
|
|
|
|
})
|
|
|
|
.then(response => JSON.parse(response));
|
|
|
|
});
|
2016-08-31 15:44:00 -03:00
|
|
|
}
|
|
|
|
|
2016-09-06 17:18:27 -03:00
|
|
|
readFile(path, sha, branch = this.branch) {
|
2016-08-30 19:06:20 -03:00
|
|
|
const cache = sha ? LocalForage.getItem(`gh.${sha}`) : Promise.resolve(null);
|
|
|
|
return cache.then((cached) => {
|
|
|
|
if (cached) { return cached; }
|
|
|
|
|
|
|
|
return this.request(`${this.repoURL}/contents/${path}`, {
|
|
|
|
headers: { Accept: 'application/vnd.github.VERSION.raw' },
|
2016-09-06 17:18:27 -03:00
|
|
|
params: { ref: branch },
|
2016-08-30 19:06:20 -03:00
|
|
|
cache: false
|
|
|
|
}).then((result) => {
|
|
|
|
if (sha) {
|
|
|
|
LocalForage.setItem(`gh.${sha}`, result);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
listFiles(path) {
|
|
|
|
return this.request(`${this.repoURL}/contents/${path}`, {
|
2016-09-04 14:01:28 +02:00
|
|
|
params: { ref: this.branch }
|
2016-08-30 19:06:20 -03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-09-06 17:18:27 -03:00
|
|
|
readUnpublishedBranchFile(contentKey) {
|
2016-09-13 16:00:24 -03:00
|
|
|
let metaData;
|
|
|
|
return this.retrieveMetadata(contentKey)
|
|
|
|
.then(data => {
|
|
|
|
metaData = data;
|
|
|
|
return this.readFile(data.objects.entry, null, data.branch);
|
|
|
|
})
|
|
|
|
.then(file => {
|
|
|
|
return { metaData, file };
|
2016-09-06 17:18:27 -03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
listUnpublishedBranches() {
|
|
|
|
return this.request(`${this.repoURL}/git/refs/heads/cms`);
|
|
|
|
}
|
|
|
|
|
2016-08-30 19:06:20 -03:00
|
|
|
persistFiles(entry, mediaFiles, options) {
|
|
|
|
let filename, part, parts, subtree;
|
|
|
|
const fileTree = {};
|
2016-09-05 12:12:38 -03:00
|
|
|
const uploadPromises = [];
|
|
|
|
|
|
|
|
const files = mediaFiles.concat(entry);
|
|
|
|
|
|
|
|
files.forEach((file) => {
|
2016-08-30 19:06:20 -03:00
|
|
|
if (file.uploaded) { return; }
|
2016-09-05 12:12:38 -03:00
|
|
|
uploadPromises.push(this.uploadBlob(file));
|
2016-08-30 19:06:20 -03:00
|
|
|
parts = file.path.split('/').filter((part) => part);
|
|
|
|
filename = parts.pop();
|
|
|
|
subtree = fileTree;
|
|
|
|
while (part = parts.shift()) {
|
|
|
|
subtree[part] = subtree[part] || {};
|
|
|
|
subtree = subtree[part];
|
|
|
|
}
|
|
|
|
subtree[filename] = file;
|
|
|
|
file.file = true;
|
|
|
|
});
|
2016-09-13 14:31:18 -03:00
|
|
|
return Promise.all(uploadPromises).then(() => {
|
|
|
|
if (!options.mode || (options.mode && options.mode === SIMPLE)) {
|
|
|
|
return this.getBranch()
|
|
|
|
.then(branchData => this.updateTree(branchData.commit.sha, '/', fileTree))
|
|
|
|
.then(changeTree => this.commit(options.commitMessage, changeTree))
|
|
|
|
.then(response => this.patchBranch(this.branch, response.sha));
|
|
|
|
} else if (options.mode && options.mode === EDITORIAL_WORKFLOW) {
|
|
|
|
const mediaFilesList = mediaFiles.map(file => file.path);
|
|
|
|
return this.editorialWorkflowGit(fileTree, entry, mediaFilesList, options);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
editorialWorkflowGit(fileTree, entry, filesList, options) {
|
|
|
|
const contentKey = options.collectionName ? `${options.collectionName}-${entry.slug}` : entry.slug;
|
|
|
|
const branchName = `cms/${contentKey}`;
|
|
|
|
const unpublished = options.unpublished || false;
|
|
|
|
|
|
|
|
if (!unpublished) {
|
|
|
|
// Open new editorial review workflow for this entry - Create new metadata and commit to new branch
|
|
|
|
return this.getBranch()
|
2016-08-31 13:30:14 -03:00
|
|
|
.then(branchData => this.updateTree(branchData.commit.sha, '/', fileTree))
|
|
|
|
.then(changeTree => this.commit(options.commitMessage, changeTree))
|
|
|
|
.then((response) => {
|
2016-09-13 14:31:18 -03:00
|
|
|
const contentKey = options.collectionName ? `${options.collectionName}-${entry.slug}` : entry.slug;
|
|
|
|
const branchName = `cms/${contentKey}`;
|
|
|
|
return this.user().then(user => {
|
|
|
|
return user.name ? user.name : user.login;
|
|
|
|
})
|
|
|
|
.then(username => this.storeMetadata(contentKey, {
|
|
|
|
type: 'PR',
|
|
|
|
user: username,
|
|
|
|
status: status.first(),
|
|
|
|
branch: branchName,
|
|
|
|
collection: options.collectionName,
|
|
|
|
title: options.parsedData && options.parsedData.title,
|
|
|
|
description: options.parsedData && options.parsedData.description,
|
|
|
|
objects: {
|
|
|
|
entry: entry.path,
|
|
|
|
files: filesList
|
|
|
|
},
|
|
|
|
timeStamp: new Date().toISOString()
|
|
|
|
}))
|
|
|
|
.then(this.createBranch(branchName, response.sha))
|
|
|
|
.then(this.createPR(options.commitMessage, `cms/${contentKey}`));
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// Entry is already on editorial review workflow - just update metadata and commit to existing branch
|
|
|
|
return this.getBranch(branchName)
|
|
|
|
.then(branchData => this.updateTree(branchData.commit.sha, '/', fileTree))
|
|
|
|
.then(changeTree => this.commit(options.commitMessage, changeTree))
|
|
|
|
.then((response) => {
|
|
|
|
const contentKey = options.collectionName ? `${options.collectionName}-${entry.slug}` : entry.slug;
|
|
|
|
const branchName = `cms/${contentKey}`;
|
|
|
|
return this.user().then(user => {
|
|
|
|
return user.name ? user.name : user.login;
|
|
|
|
})
|
|
|
|
.then(username => this.retrieveMetadata(contentKey))
|
|
|
|
.then(metadata => {
|
|
|
|
let files = metadata.objects && metadata.objects.files || [];
|
|
|
|
files = files.concat(filesList);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...metadata,
|
2016-09-09 17:15:58 -03:00
|
|
|
title: options.parsedData && options.parsedData.title,
|
|
|
|
description: options.parsedData && options.parsedData.description,
|
2016-09-06 17:18:27 -03:00
|
|
|
objects: {
|
|
|
|
entry: entry.path,
|
2016-09-13 14:31:18 -03:00
|
|
|
files: _.uniq(files)
|
2016-09-09 17:15:58 -03:00
|
|
|
},
|
|
|
|
timeStamp: new Date().toISOString()
|
2016-09-13 14:31:18 -03:00
|
|
|
};
|
|
|
|
})
|
|
|
|
.then(updatedMetadata => this.storeMetadata(contentKey, updatedMetadata))
|
|
|
|
.then(this.patchBranch(branchName, response.sha));
|
2016-08-30 19:06:20 -03:00
|
|
|
});
|
2016-09-13 14:31:18 -03:00
|
|
|
}
|
2016-08-30 19:06:20 -03:00
|
|
|
}
|
|
|
|
|
2016-09-13 16:00:24 -03:00
|
|
|
updateUnpublishedEntryStatus(collection, slug, status) {
|
|
|
|
const contentKey = collection ? `${collection}-${slug}` : slug;
|
|
|
|
return this.retrieveMetadata(contentKey)
|
|
|
|
.then(metadata => {
|
|
|
|
return {
|
|
|
|
...metadata,
|
|
|
|
status
|
|
|
|
};
|
|
|
|
})
|
|
|
|
.then(updatedMetadata => this.storeMetadata(contentKey, updatedMetadata));
|
|
|
|
}
|
|
|
|
|
2016-08-31 16:41:29 -03:00
|
|
|
createRef(type, name, sha) {
|
2016-08-30 19:06:20 -03:00
|
|
|
return this.request(`${this.repoURL}/git/refs`, {
|
|
|
|
method: 'POST',
|
2016-08-31 16:41:29 -03:00
|
|
|
body: JSON.stringify({ ref: `refs/${type}/${name}`, sha }),
|
2016-08-30 19:06:20 -03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-31 16:41:29 -03:00
|
|
|
createBranch(branchName, sha) {
|
|
|
|
return this.createRef('heads', branchName, sha);
|
|
|
|
}
|
|
|
|
|
|
|
|
patchRef(type, name, sha) {
|
|
|
|
return this.request(`${this.repoURL}/git/refs/${type}/${name}`, {
|
2016-08-30 19:06:20 -03:00
|
|
|
method: 'PATCH',
|
|
|
|
body: JSON.stringify({ sha })
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-31 16:41:29 -03:00
|
|
|
patchBranch(branchName, sha) {
|
|
|
|
return this.patchRef('heads', branchName, sha);
|
|
|
|
}
|
|
|
|
|
2016-09-13 14:31:18 -03:00
|
|
|
getBranch(branch = this.branch) {
|
|
|
|
return this.request(`${this.repoURL}/branches/${branch}`);
|
2016-08-31 16:41:29 -03:00
|
|
|
}
|
|
|
|
|
2016-08-31 17:33:12 -03:00
|
|
|
createPR(title, head, base = 'master') {
|
|
|
|
const body = 'Automatically generated by Netlify CMS';
|
|
|
|
return this.request(`${this.repoURL}/pulls`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({ title, body, head, base }),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-30 19:06:20 -03:00
|
|
|
getTree(sha) {
|
|
|
|
return sha ? this.request(`${this.repoURL}/git/trees/${sha}`) : Promise.resolve({ tree: [] });
|
|
|
|
}
|
|
|
|
|
|
|
|
toBase64(str) {
|
|
|
|
return Promise.resolve(
|
|
|
|
Base64.encode(str)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
uploadBlob(item) {
|
|
|
|
const content = item instanceof MediaProxy ? item.toBase64() : this.toBase64(item.raw);
|
|
|
|
|
|
|
|
return content.then((contentBase64) => {
|
|
|
|
return this.request(`${this.repoURL}/git/blobs`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({
|
|
|
|
content: contentBase64,
|
|
|
|
encoding: 'base64'
|
|
|
|
})
|
|
|
|
}).then((response) => {
|
|
|
|
item.sha = response.sha;
|
|
|
|
item.uploaded = true;
|
|
|
|
return item;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
updateTree(sha, path, fileTree) {
|
|
|
|
return this.getTree(sha)
|
|
|
|
.then((tree) => {
|
|
|
|
var obj, filename, fileOrDir;
|
|
|
|
var updates = [];
|
|
|
|
var added = {};
|
|
|
|
|
|
|
|
for (var i = 0, len = tree.tree.length; i < len; i++) {
|
|
|
|
obj = tree.tree[i];
|
|
|
|
if (fileOrDir = fileTree[obj.path]) {
|
|
|
|
added[obj.path] = true;
|
|
|
|
if (fileOrDir.file) {
|
|
|
|
updates.push({ path: obj.path, mode: obj.mode, type: obj.type, sha: fileOrDir.sha });
|
|
|
|
} else {
|
|
|
|
updates.push(this.updateTree(obj.sha, obj.path, fileOrDir));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (filename in fileTree) {
|
|
|
|
fileOrDir = fileTree[filename];
|
|
|
|
if (added[filename]) { continue; }
|
|
|
|
updates.push(
|
|
|
|
fileOrDir.file ?
|
|
|
|
{ path: filename, mode: '100644', type: 'blob', sha: fileOrDir.sha } :
|
|
|
|
this.updateTree(null, filename, fileOrDir)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return Promise.all(updates)
|
|
|
|
.then((updates) => {
|
|
|
|
return this.request(`${this.repoURL}/git/trees`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({ base_tree: sha, tree: updates })
|
|
|
|
});
|
|
|
|
}).then((response) => {
|
|
|
|
return { path: path, mode: '040000', type: 'tree', sha: response.sha, parentSha: sha };
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-31 13:30:14 -03:00
|
|
|
commit(message, changeTree) {
|
|
|
|
const tree = changeTree.sha;
|
|
|
|
const parents = changeTree.parentSha ? [changeTree.parentSha] : [];
|
|
|
|
return this.request(`${this.repoURL}/git/commits`, {
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({ message, tree, parents })
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-30 19:06:20 -03:00
|
|
|
}
|