-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhack.v1.js
86 lines (74 loc) · 2.78 KB
/
hack.v1.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
// ==UserScript==
// @name Keybr github
// @namespace https://github.com/anka-213
// @version 0.1
// @description Type a github repo using keybr.com
// @author You
// @match http://www.keybr.com/*
// @grant unsafeWindow
// ==/UserScript==
/* jshint -W097, esnext:true */
/* globals unsafeWindow: false */
'use strict';
debugger
(function(LessonFactory, MODE, CustomGenerator, CustomLesson) {
LessonFactory.loadLessonOrig = LessonFactory.loadLessonOrig || LessonFactory.loadLesson;
Promise.prototype.done = Promise.prototype.then; // Ugly hack. Convert to real "P" promise instead.
Promise.prototype.fail = Promise.prototype.catch;
var log = x=>console.log(x);
var processStatus = function(response) {
// status "0" to handle local files fetching (e.g. Cordova/Phonegap etc.)
if (response.status === 200 || response.status === 0) {
return response;
} else {
throw new Error(response.statusText);
}
}
;
var fetchOK = url=>fetch(url).then(processStatus);
var fetchText = url=>fetchOK(url).then(ans=>ans.text());
var fetchJson = url=>fetchOK(url).then(ans=>ans.json());
var getBlobPaths = json=>json.tree.filter(a=>a.type=="blob").map(a=>a.path);
var getDownloadUrl = a => downloadURL + a;
function getRandom(arr) {
var i = Math.floor(Math.random() * arr.length);
return arr[i];
}
function fetchAll(urls) {
var contentPromises = urls.map(fetchText);
return Promise.all(contentPromises);
}
function getGithub(url) {
var repo = url[1];
var branch = "master";
var downloadURL = "https://raw.githubusercontent.com/" + repo + "/" + branch + "/";
var apiUrl = 'https://api.github.com/repos/' + repo + '/git/trees/' + branch + '?recursive=1';
// Get random file
var p = fetchJson(apiUrl)
.then(getBlobPaths)
.then(getRandom)
.then(function (path) {
console.log(path);
return fetchText(downloadURL + path).then(txt => path + "\n" + txt);
});
/*
// Get all files
var p = fetchJson(apiUrl)
.then(getBlobUrls)
.then(fetchAll);
*/
p.catch(console.error.bind(console));
return p;
}
LessonFactory.loadLesson = function(settings) {
// debugger ;
var url;
if (MODE.IMPORT_WEBSITE === settings.mode && (url = settings.text.url.match("https://github.com/([^/]*/[^/]*)"))) {
console.log(url);
var github = getGithub(url);
return github.then(text => new CustomLesson(settings,new CustomGenerator(settings, text)));
} else {
return LessonFactory.loadLessonOrig(settings);
}
};
})(unsafeWindow.LessonFactory, unsafeWindow.MODE, unsafeWindow.CustomGenerator, unsafeWindow.CustomLesson);