lib:file opener

none

目前為 2024-05-15 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name lib:file opener
  3. // @version 3
  4. // @description none
  5. // @license GPLv3
  6. // @run-at document-start
  7. // @author You
  8. // @match *://*/*
  9. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAMAAABiM0N1AAAAAXNSR0IB2cksfwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAHJQTFRFAAAAEIijAo2yAI60BYyuF4WaFIifAY6zBI2wB4usGIaZEYigIoiZCIyrE4igG4iYD4mjEomhFoedCoqpDIqnDomlBYyvE4efEYmiDYqlA42xBoytD4mkCYqqGYSUFYidC4qoC4upAo6yCoupDYqmCYur4zowOQAAACZ0Uk5TAO////9vr////1+/D/+/L+/Pf/////+f3///////H4////////+5G91rAAACgUlEQVR4nM2Y22KjIBCGidg1264liZqDadK03X3/V2wNKHMC7MpF/xthHD5mgERAqZhWhfYqH6K+Qf2qNNf625hCoFj9/gblMUi5q5jLkXLCKudgyiRm0FMK82cWJp1fLbV5VmvJbCIc0GCYaFqqlDJgADdBjncqAXYobm1xh72aFMflbysteFfdy2Yi1XGOm5HGBzQ1dq7TzEoxjeNTjQZb7VA3e1c7+ImgasAgQ9+xusNVNZIo5xmOMgihIS2PbCQIiHEUdTvhxCcS/kPomfFI2zHy2PkWmA6aNatIJpKFJyekyy02xh5Y3DI9T4aOT6VhIUrsNTFp1pf79Z4SIIVDegl6IJO6cHiL/GimIZDhgTu/BlYWCQzHMl0zBWT/T3KAhtxOuUB9FtBrpsz0RV4xsjHmW+UCaffcSy/5viMGer0/6HdFNMZBq/vjJL38H9Dqx4Fuy0Em12DbZy+9pGtiDijbglwAehyj11n0tRD3WUBm+lwulE/8h4BuA+iWAQQnteg2Xm63WQLTpnMnpjdge0Mgu/GRPsV4xdjQ94Lfi624fabhDkfUqIKNrM64Q837v8yL0prasepCgrtvw1sJpoqanGEX7b5mQboNW8eawXaWXTMfMGxub472hzWzHSn6Sg2G9+6TAyRruE71s+zAzjWaknoyJCQzwxrghH2k5FDT4eqWunuNxyN9QCGcxVod5oADbYnIUkDTGZEf1xDJnSFteQ3KdsT8zYDMQXcHxsevcLH1TrsABzkNPyA/L7b0jg704viMMlpQI96WsHknCt/3YH0kOEo9zcGkwrFK39ck72rmoehmKqo2RKlilzSy/nJKEV45CT38myJp456fezktHjN5aeMAAAAASUVORK5CYII=
  10. // @grant none
  11. // ==/UserScript==
  12. ;(() => {
  13. const a = loadlib("allfuncs")
  14. const run = {
  15. file: runfile,
  16. folder: runfolder,
  17. globals: window.ERwkOoQYn9C3jxDZdovIZoZ2DmGt5wKyTMPU2uck ?? [],
  18. }
  19. delete window.ERwkOoQYn9C3jxDZdovIZoZ2DmGt5wKyTMPU2uck
  20. ;(async () => {
  21. var cac = {}
  22. async function newglobaljs(name, func = (e) => e, newname) {
  23. if ((newname ?? name).startsWith("blob:http")) return
  24. var text = cac[name] ?? (await (await fetch(name)).text())
  25. if (newname) name = newname
  26. cac[name] ??= text
  27. run.globals.push({
  28. text: func(text),
  29. name: name,
  30. })
  31. }
  32. run.newglobaljs = newglobaljs
  33. })()
  34. function hashformat({ isglobal, name }) {
  35. const hashformat = "#__isglobal: filename"
  36. if (isglobal == true) isglobal = "global"
  37. if (isglobal == false) isglobal = "local"
  38. return _replaceall(hashformat, [
  39. ["isglobal", isglobal],
  40. ["filename", name],
  41. ])
  42. }
  43.  
  44. loadlib("libloader").savelib("file opener", run)
  45. async function runfile(file) {
  46. file = await formatfiles(await file.getFile())
  47. replaceglobalurls(file)
  48. await updateglobals(file)
  49. newurl(file, file.format)
  50. openfile(file, file.name)
  51. }
  52. async function updateglobals(file) {
  53. const tempglobals = JSON.stringify([
  54. ...run.globals.map((e) => {
  55. return { name: e.name, text: e.text }
  56. }),
  57. ])
  58. // .replaceAll("<", "&lt;")
  59. // .replaceAll("&", "&amp;")
  60. if (file.name.endsWith(".html"))
  61. file.text =
  62. `<script>window.ERwkOoQYn9C3jxDZdovIZoZ2DmGt5wKyTMPU2uck = ${tempglobals}<\/script>` +
  63. file.text
  64. }
  65. async function runfolder(folder, mainfile = "index.html") {
  66. var files = await getfilesfromfolder(folder)
  67. const name = files[0].path.match(/^([^\/]+)\//, "")[1]
  68. files = await formatfiles(files)
  69.  
  70. setupget(files)
  71. var index = files.get(mainfile)
  72. if (!index) {
  73. error(
  74. `folder ${name} doesn't contain ${mainfile}, searching for index.html instead`
  75. )
  76. index = files.get("index.html")
  77. }
  78. if (!index) throw new Error(`folder ${name} doesn't contain index.html`)
  79. var htmls = files.get(/\.html/i)
  80. // error(a(files.get(/\.png/i)[0].file).readfile('DataURL'))
  81. {
  82. function updatebar(i, name) {
  83. progresstext.innerHTML = `${i}/${files.length + htmls.length}: ${name}`
  84. innerprogress.style.width =
  85. "calc(" +
  86. a(Number(i)).rerange(0, files.length + htmls.length, 0, 100) +
  87. "% - 2px)"
  88. }
  89. var progress = a(document.body)
  90. .createelem("div", {
  91. position: "fixed",
  92. top: "0",
  93. left: 0,
  94. border: "30px solid #999",
  95. backgroundColor: "black",
  96. color: "white",
  97. width: "calc(100vw - 60px)",
  98. height: "29px",
  99. })
  100. .createelem.same("div", {
  101. backgroundColor: "#777",
  102. width:
  103. a(files.length).rerange(0, files.length + htmls.length, 0, 100) +
  104. "%",
  105. height: "10px",
  106. })
  107. .createelem.same("div", {
  108. backgroundColor: "#555",
  109. width:
  110. 100 -
  111. a(files.length).rerange(0, files.length + htmls.length, 0, 100) +
  112. "%",
  113. position: "relative",
  114. top: "-10px",
  115. left:
  116. a(files.length).rerange(0, files.length + htmls.length, 0, 100) +
  117. "%",
  118. height: "10px",
  119. }).val
  120. var innerprogress = a(progress).createelem("div", {
  121. backgroundColor: "#aaa",
  122. width: 0,
  123. position: "relative",
  124. top: "-18px",
  125. left: "2px",
  126. height: "6px",
  127. }).val
  128. var progresstext = a(progress).createelem("span", {
  129. position: "relative",
  130. top: "-16px",
  131. }).val
  132. for (var i in files) {
  133. var file = files[i]
  134. updatebar(i, file.name)
  135. newurl(file, file.format)
  136. if (Number(i) % 15 == 0) await a(0).wait()
  137. }
  138. var f = files.get(/\./)
  139. f = f.filter((e) => ["js", "css"].includes(e.extension))
  140. for (var i in f) {
  141. var e = f[i]
  142. if (Number(i) % 15 == 0) {
  143. updatebar(Number(i), e.name)
  144. await a(0).wait()
  145. }
  146. replaceallurls(e, files)
  147. replaceglobalurls(e)
  148. newurl(e)
  149. }
  150. for (var i in htmls) {
  151. var e = htmls[i]
  152. if (Number(i) % 15 == 0) {
  153. updatebar(Number(i) + files.length, e.name)
  154. await a(0).wait()
  155. }
  156. replaceallurls(e, files)
  157. replaceglobalurls(e)
  158. newurl(e, "text/html")
  159. }
  160. }
  161. // warn(index, index.path.split("/"))
  162. replaceallurls(index, files, true)
  163. await updateglobals(index)
  164. newurl(index, "text/html")
  165. progress.remove()
  166. openfile(index, name)
  167. }
  168. function openfile(file, name) {
  169. name ??= file?.file?.name
  170. return open(file.url, location.href + name)
  171. }
  172. function getallgoodpaths(file, files, lll) {
  173. var p = file.path.split("/")
  174. var n = p.pop()
  175. return files.map((e) => {
  176. if (!e.path) error(e, file)
  177. var path = e.path.split("/")
  178. var name = path.pop()
  179. if (same(p, path)) {
  180. return { ...e, path: name }
  181. }
  182. var newpath = ""
  183. var rs = false
  184. p.forEach((e, i) => {
  185. if (same(e, path[i]) && !rs) return
  186. rs = true
  187. newpath += "../"
  188. })
  189. path.push("")
  190. return {
  191. ...e,
  192. path: newpath + path.join("/") + name,
  193. }
  194. })
  195. function same(a, s) {
  196. return JSON.stringify(a) == JSON.stringify(s)
  197. }
  198. }
  199. function replaceallurls(file, files, lll) {
  200. if (file.text.startsWith("#redirect")) {
  201. var redir = file.text.match(/^#redirect (.*)/)[1]
  202. var redirfile = files.get(redir)
  203. if (!redirfile)
  204. throw new Error(`failed to redirect from ${file.name} to ${redir}`)
  205. file.text =
  206. file.text.replace(`#redirect ${redir}`, "") + "\n" + redirfile.text
  207. }
  208. var goodfiles = getallgoodpaths(file, files, lll)
  209. goodfiles.forEach(({ path, url }) => {
  210. file.text = file.text.replaceAll(
  211. new RegExp(`(['"])(?:\\.\\/)*${regescape(path)}\\1`, "gi"),
  212. `"${url}${hashformat({ isglobal: false, name: path })}"`
  213. )
  214. })
  215. replaceglobalurls(file)
  216. }
  217. function regescape(reg) {
  218. return reg.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")
  219. }
  220. function newurl(file, type) {
  221. type ??= file.format
  222. var blob =
  223. type && type.startsWith("image/")
  224. ? new Blob([file.file], { type })
  225. : new Blob([file.text], { type })
  226. file.url = URL.createObjectURL(blob)
  227. return file
  228. }
  229. async function replaceglobalurls(file) {
  230. run.globals.forEach((e) => {
  231. if (!e.regex)
  232. e.regex = new RegExp(
  233. `(['"])(?:\\.?\\.\\/)*${regescape(e.name)}\\1`,
  234. "gi"
  235. )
  236. if (!e.url)
  237. e.url = URL.createObjectURL(
  238. new Blob([e.text], { type: "text/javascript" })
  239. )
  240. file.text = file.text.replaceAll(
  241. e.regex,
  242. `"${e.url}${hashformat({ isglobal: true, name: e.name })}"`
  243. )
  244. })
  245. return file
  246. }
  247. async function formatfiles(files) {
  248. if (!a(files).gettype("array").val) return await format(files)
  249. return await Promise.all(files.map(format))
  250. async function format(file) {
  251. var data = await a(file).readfile()
  252. // if(file.name.match(/\.(\w+)$/)?.[1]=='svg'){
  253. // error(file)
  254. // }
  255. return {
  256. name: file.name,
  257. text: data,
  258. path: file?.path?.replace?.(/^[^\/]+\//, ""),
  259. extension: file.name.match(/\.(\w+)$/)?.[1],
  260. format: {
  261. js: "text/javascript",
  262. html: "text/html",
  263. css: "text/css",
  264. jpg: "image/jpg",
  265. jpeg: "image/jpeg",
  266. png: "image/png",
  267. svg: "image/svg+xml",
  268. }[file.name.match(/\.(\w+)$/)?.[1]],
  269. file,
  270. }
  271. }
  272. }
  273. function setupget(files) {
  274. files.get = function (name, skip = 0) {
  275. if (a(name).gettype("string").val)
  276. return files.find((e) => {
  277. return e.path == name
  278. })
  279. else return files.filter((e) => name.test(e.path))
  280. }
  281. }
  282.  
  283. async function getfilesfromfolder(dirHandle, path = dirHandle.name) {
  284. const dirs = []
  285. const files = []
  286. // warn(path)
  287. for await (const entry of dirHandle.values()) {
  288. const nestedPath = `${path}/${entry.name}`
  289. if (nestedPath.startsWith(dirHandle.name + "/codemirror/mode/ja"))
  290. error(nestedPath, entry)
  291. if (entry.kind === "file") {
  292. files.push(
  293. entry.getFile().then((file) => {
  294. file.directoryHandle = dirHandle
  295. file.handle = entry
  296. Object.defineProperty(file, "path", {
  297. configurable: true,
  298. enumerable: true,
  299. get: () => nestedPath,
  300. })
  301. return Object.defineProperty(file, "webkitRelativePath", {
  302. configurable: true,
  303. enumerable: true,
  304. get: () => nestedPath,
  305. })
  306. })
  307. )
  308. } else if (entry.kind === "directory") {
  309. warn(entry, nestedPath)
  310. dirs.push(getfilesfromfolder(entry, nestedPath))
  311. } else {
  312. error(entry.kind)
  313. }
  314. }
  315. return [...(await Promise.all(dirs)).flat(), ...(await Promise.all(files))]
  316. }
  317. function _replaceall(q, w, e) {
  318. switch (a(w).gettype("array").val + " " + a(e).gettype("array").val) {
  319. case "true true":
  320. if (e.length == w.length) {
  321. w.forEach((ww, i) => {
  322. q = q.replaceAll(ww, e[i])
  323. })
  324. return q
  325. }
  326. throw new Error("when both are arrays the length must be the same")
  327. break
  328. case "true false":
  329. if (a(w[0]).gettype("array").val) {
  330. w.forEach(([ww, e]) => {
  331. q = q.replaceAll(ww, e)
  332. })
  333. } else {
  334. w.forEach((ww) => {
  335. q = q.replaceAll(ww, e)
  336. })
  337. }
  338. return q
  339. break
  340. case "false false":
  341. return q.replaceAll(w, e)
  342. break
  343. }
  344. }
  345. })()