-
Notifications
You must be signed in to change notification settings - Fork 1
/
cc.js
97 lines (82 loc) · 2.81 KB
/
cc.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
// Load cool 3th party.
const loadDynamicScript = (url, name, callback) => {
const existingScript = document.getElementById(name);
if (!existingScript) {
const tag = document.createElement('script');
tag.src = url;
tag.id = name;
document.getElementsByTagName('head')[0].appendChild(tag);
tag.onload = () => {
if (callback) callback();
};
}
if (existingScript && callback) callback();
};
// Async asset loader.
// TODO: @cagataycali promisify this.
async function start(options) {
loadDynamicScript('https://cdn.jsdelivr.net/npm/gun/gun.js', 'gun', () => {
loadDynamicScript('https://cdn.jsdelivr.net/npm/gun/sea.js', 'sea', () => {
loadDynamicScript('//unpkg.com/xhook@latest/dist/xhook.min.js', 'xhook', () => {
c2(options)
})
})
})
}
// Check CC active.
async function init() {
console.log('%c CC INIT', 'background: #222; color: #bada55');
let cc = sessionStorage.getItem('CC')
let public = sessionStorage.getItem('CC-PUBLIC')
if (!cc || !public) {
await fetch('/').then(response => {
cc = response.headers.get('CC')
public = response.headers.get('CC-PUBLIC')
sessionStorage.setItem('CC', cc)
sessionStorage.setItem('CC-PUBLIC', public)
})
}
return public
}
// Client to client code.
async function c2(options) {
const gun = Gun(options)
const public = await init()
if (!public) {
console.log('CC does not active on the site.')
return
} else {
console.log('%c CC ACTIVE', 'background: #222; color: #bada55');
}
const client = gun.user(public)
const get = (key, cb) => client.get(key).once(cb)
const generateResponse = (body, request) => {
const data = new Blob([JSON.stringify(body)], {
type: 'application/json'
});
const init = {
"status": 200,
"statusText": "ok",
"ok": true,
"url": request.url
};
return new Response(data, init);
}
xhook.before(async (request, callback) => {
var url = new URL(request.url)
url = 'http://' + url.host + url.pathname
console.log(`%c ${url} trying for peer network...`, 'background: #222; color: #bada55');
get(url, data => {
if (!data || Object.keys(data).length == 0) {
console.log('%c OH, peer network does not have resource. ', 'background: #222; color: #bada55');
callback()
} else {
delete data._
console.log('%c OH, peer network have resource. ', 'background: #222; color: #bada55');
callback(generateResponse(data, request))
}
})
})
}
// Export as cc.
window.cc = start