about summary refs log tree commit diff stats
path: root/src/assets/javascripts/utils.js
blob: 4dd537fcf278a86a1cf2fcc4ed335dfb64553ae5 (plain) (blame)
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
258
259
260
261
262
263
window.browser = window.browser || window.chrome

import localise from "./localise.js"
import servicesHelper from "./services.js"

function getRandomInstance(instances) {
	return instances[~~(instances.length * Math.random())]
}

function camelCase(str) {
	return str.charAt(0).toUpperCase() + str.slice(1)
}

let cloudflareBlackList = []
let authenticateBlackList = []
async function initBlackList() {
	return new Promise(resolve => {
		fetch("/instances/blacklist.json")
			.then(response => response.text())
			.then(data => {
				cloudflareBlackList = JSON.parse(data).cloudflare
				authenticateBlackList = JSON.parse(data).authenticate
				resolve()
			})
	})
}

function updateInstances() {
	return new Promise(async resolve => {
		let http = new XMLHttpRequest()
		let fallback = new XMLHttpRequest()
		http.open("GET", "https://codeberg.org/LibRedirect/libredirect/raw/branch/master/src/instances/data.json", false)
		http.send(null)
		if (http.status != 200) {
			fallback.open("GET", "https://raw.githubusercontent.com/libredirect/libredirect/master/src/instances/data.json", false)
			fallback.send(null)
			if (fallback.status === 200) {
				http = fallback
			} else {
				resolve()
				return
			}
		}
		await initBlackList()
		const instances = JSON.parse(http.responseText)

		await servicesHelper.setRedirects(instances)

		console.info("Successfully updated Instances")
		resolve(true)
		return
	})
}

function protocolHost(url) {
	if (url.username && url.password) return `${url.protocol}//${url.username}:${url.password}@${url.host}`
	return `${url.protocol}//${url.host}`
}

async function processDefaultCustomInstances(service, frontend, network, document) {
	let frontendNetworkElement = document.getElementById(frontend).getElementsByClassName(network)[0]

	let frontendCustomInstances = []
	let frontendCheckListElement = frontendNetworkElement.getElementsByClassName("checklist")[0]

	await initBlackList()

	let frontendDefaultRedirects

	let redirects, options

	async function getFromStorage() {
		return new Promise(async resolve =>
			browser.storage.local.get(["options", "redirects",], r => {
				frontendDefaultRedirects = r.options[frontend][network].enabled
				frontendCustomInstances = r.options[frontend][network].custom
				options = r.options
				redirects = r.redirects
				resolve()
			})
		)
	}

	await getFromStorage()

	function calcFrontendCheckBoxes() {
		let isTrue = true
		for (const item of redirects[frontend][network]) {
			if (!frontendDefaultRedirects.includes(item)) {
				isTrue = false
				break
			}
		}
		for (const element of frontendCheckListElement.getElementsByTagName("input")) {
			element.checked = frontendDefaultRedirects.includes(element.className)
		}
		if (frontendDefaultRedirects.length == 0) isTrue = false
		frontendNetworkElement.getElementsByClassName("toggle-all")[0].checked = isTrue
	}
	frontendCheckListElement.innerHTML = [
		`<div>
        <x data-localise="__MSG_toggleAll__">Toggle All</x>
        <input type="checkbox" class="toggle-all"/>
      </div>`,
		...redirects[frontend][network]
			.map(x => {
				const cloudflare = cloudflareBlackList.includes(x) ? ' <span style="color:red;">cloudflare</span>' : ""
				const authenticate = authenticateBlackList.includes(x) ? ' <span style="color:orange;">authenticate</span>' : ""

				let warnings = [cloudflare, authenticate].join(" ")
				return `<div>
                    <x><a href="${x}" target="_blank">${x}</a>${warnings}</x>
                    <input type="checkbox" class="${x}"/>
                  </div>`
			}),
	].join("\n<hr>\n")

	localise.localisePage()

	calcFrontendCheckBoxes()
	frontendNetworkElement.getElementsByClassName("toggle-all")[0].addEventListener("change", async event => {
		browser.storage.local.get("options", r => {
			let options = r.options
			if (event.target.checked) frontendDefaultRedirects = [...redirects[frontend][network]]
			else frontendDefaultRedirects = []

			options[frontend][network].enabled = frontendDefaultRedirects
			browser.storage.local.set({ options })
			calcFrontendCheckBoxes()
		})
	})

	for (let element of frontendCheckListElement.getElementsByTagName("input")) {
		if (element.className != "toggle-all")
			frontendNetworkElement.getElementsByClassName(element.className)[0].addEventListener("change", async event => {
				browser.storage.local.get("options", r => {
					let options = r.options
					if (event.target.checked) frontendDefaultRedirects.push(element.className)
					else {
						let index = frontendDefaultRedirects.indexOf(element.className)
						if (index > -1) frontendDefaultRedirects.splice(index, 1)
					}

					options[frontend][network].enabled = frontendDefaultRedirects
					browser.storage.local.set({ options })
					calcFrontendCheckBoxes()
				})
			})
	}

	function calcFrontendCustomInstances() {
		frontendNetworkElement.getElementsByClassName("custom-checklist")[0].innerHTML = frontendCustomInstances
			.map(
				x => `<div>
                ${x}
                <button class="add clear-${x}">
                  <svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 0 24 24" width="20px" fill="currentColor">
                    <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z" />
                  </svg>
                </button>
              </div>
              <hr>`
			)
			.join("\n")

		for (const item of frontendCustomInstances) {
			frontendNetworkElement.getElementsByClassName(`clear-${item}`)[0].addEventListener("click", async () => {
				browser.storage.local.get("options", r => {
					let options = r.options
					let index = frontendCustomInstances.indexOf(item)
					if (index > -1) frontendCustomInstances.splice(index, 1)
					options[frontend][network].custom = frontendCustomInstances
					browser.storage.local.set({ options })
					calcFrontendCustomInstances()
				})
			})
		}
	}
	calcFrontendCustomInstances()
	frontendNetworkElement.getElementsByClassName("custom-instance-form")[0].addEventListener("submit", async event => {
		browser.storage.local.get("options", r => {
			let options = r.options
			event.preventDefault()
			let frontendCustomInstanceInput = frontendNetworkElement.getElementsByClassName("custom-instance")[0]
			let url = new URL(frontendCustomInstanceInput.value)
			let protocolHostVar = protocolHost(url)
			if (frontendCustomInstanceInput.validity.valid && !redirects[frontend][network].includes(protocolHostVar)) {
				if (!frontendCustomInstances.includes(protocolHostVar)) {
					frontendCustomInstances.push(protocolHostVar)
					options[frontend][network].custom = frontendCustomInstances
					browser.storage.local.set({ options })
					frontendCustomInstanceInput.value = ""
				}
				calcFrontendCustomInstances()
			}
		})
	})
}

function copyRaw(test, copyRawElement) {
	return new Promise(resolve => {
		browser.tabs.query({ active: true, currentWindow: true }, async tabs => {
			let currTab = tabs[0]
			if (currTab) {
				let url
				try {
					url = new URL(currTab.url)
				} catch {
					resolve()
					return
				}

				const newUrl = await servicesHelper.reverse(url)

				if (newUrl) {
					resolve(newUrl)
					if (test) return
					navigator.clipboard.writeText(newUrl)
					if (copyRawElement) {
						const textElement = copyRawElement.getElementsByTagName("h4")[0]
						const oldHtml = textElement.innerHTML
						textElement.innerHTML = browser.i18n.getMessage("copied")
						setTimeout(() => (textElement.innerHTML = oldHtml), 1000)
					}
				}
			}
			resolve()
		})
	})
}

function switchInstance(test) {
	return new Promise(resolve => {
		browser.tabs.query({ active: true, currentWindow: true }, async tabs => {
			let currTab = tabs[0]
			if (currTab) {
				let url
				try {
					url = new URL(currTab.url)
				} catch {
					resolve()
					return
				}
				const newUrl = await servicesHelper.switchInstance(url)

				if (newUrl) {
					if (!test) browser.tabs.update({ url: newUrl })
					resolve(true)
				} else resolve()
			}
		})
	})
}

export default {
	getRandomInstance,
	updateInstances,
	protocolHost,
	processDefaultCustomInstances,
	switchInstance,
	copyRaw,
	camelCase,
}