fb-oo-hook.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. (function(){
  2. var OFFICE_EXT = ["docx","pptx","ppt","xlsx","xls"];
  3. var PREVIEW_BASE = "http://" + location.hostname + ":8080";
  4. function startsWithFiles(p){ return (p || "").toLowerCase().indexOf("/files/") === 0; }
  5. function normalizeFilePath(path){
  6. var p = path || "";
  7. if (!startsWithFiles(p)) return "";
  8. p = p.slice(7);
  9. try { p = decodeURIComponent(p); } catch(e) {}
  10. while (p.length > 0 && p.charAt(0) === "/") p = p.slice(1);
  11. return p;
  12. }
  13. function isOffice(path){
  14. var s = (path || "").toLowerCase();
  15. for (var i = 0; i < OFFICE_EXT.length; i++) {
  16. if (s.endsWith("." + OFFICE_EXT[i])) return true;
  17. }
  18. return false;
  19. }
  20. function encodePathSegments(path){
  21. return (path || "").split("/").map(function(seg){ return encodeURIComponent(seg); }).join("/");
  22. }
  23. function buildRawPath(rel){
  24. var low = (rel || "").toLowerCase();
  25. if (low.indexOf("words/") === 0) {
  26. return "/raw/words/" + encodePathSegments((rel || "").slice(6));
  27. }
  28. if (low.indexOf("excels/") === 0) {
  29. return "/raw/excels/" + encodePathSegments((rel || "").slice(7));
  30. }
  31. return "/raw/files/" + encodePathSegments(rel || "");
  32. }
  33. function buildPreviewUrlFromPath(pathname){
  34. var rel = normalizeFilePath(pathname);
  35. if (!rel || !isOffice(rel)) return "";
  36. var ext = (rel.split(".").pop() || "").toLowerCase();
  37. var rawUrl = PREVIEW_BASE + buildRawPath(rel);
  38. var nonce = Date.now().toString() + "-" + Math.random().toString(16).slice(2, 8);
  39. return PREVIEW_BASE + "/oo-preview.html?url=" + encodeURIComponent(rawUrl) + "&type=" + encodeURIComponent(ext) + "&title=" + encodeURIComponent(rel) + "&_fbv=" + encodeURIComponent(nonce);
  40. }
  41. function maybeJump(){
  42. var p = location.pathname || "";
  43. var u = buildPreviewUrlFromPath(p);
  44. if (!u) return;
  45. if (location.pathname === "/oo-preview.html") return;
  46. location.replace(u);
  47. }
  48. var pushed = history.pushState;
  49. history.pushState = function(){
  50. pushed.apply(history, arguments);
  51. setTimeout(maybeJump, 0);
  52. };
  53. var replaced = history.replaceState;
  54. history.replaceState = function(){
  55. replaced.apply(history, arguments);
  56. setTimeout(maybeJump, 0);
  57. };
  58. window.addEventListener("popstate", function(){ setTimeout(maybeJump, 0); });
  59. window.addEventListener("hashchange", function(){ setTimeout(maybeJump, 0); });
  60. setTimeout(maybeJump, 0);
  61. })();