Project

General

Profile

Download (11.7 KB) Statistics
| Branch: | Revision:

hydrilla-fixes-bundle / content / sbox / box-fix.js @ 9ceab682

1
/**
2
 * Copyright 2022 Jacob K
3
 * Copyright 2022 Wojtek Kosior <koszko@koszko.org>
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * As additional permission under GNU GPL version 3 section 7, you
16
 * may distribute forms of that code without the copy of the GNU
17
 * GPL normally required by section 4, provided you include this
18
 * license notice and, in case of non-source distribution, a URL
19
 * through which recipients can access the Corresponding Source.
20
 * If you modify file(s) with this exception, you may extend this
21
 * exception to your version of the file(s), but you are not
22
 * obligated to do so. If you do not wish to do so, delete this
23
 * exception statement from your version.
24
 *
25
 * As a special exception to the GPL, any HTML file which merely
26
 * makes function calls to this code, and for that purpose
27
 * includes it by reference shall be deemed a separate work for
28
 * copyright law purposes. If you modify this code, you may extend
29
 * this exception to your version of the code, but you are not
30
 * obligated to do so. If you do not wish to do so, delete this
31
 * exception statement from your version.
32
 *
33
 * You should have received a copy of the GNU General Public License
34
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
35
 *
36
 * I, Wojtek Kosior, thereby promise not to sue for violation of this file's
37
 * license. Although I request that you do not make use of this code in a
38
 * proprietary program, I am not going to enforce this in court.
39
 */
40

    
41
// meta: match should be https://***.app.box.com/s/* (*** instead of * for the first section because otherwise plain app.box.com URLs won't work)
42
// meta: some test cases (mostly found at https://old.reddit.com/search?q="box.com"&include_over_18=on&sort=new)
43
	// https://uwmadison.app.box.com/s/ydht2incbdmw1lhpjg5t40adguc0fm14
44
		// umadison's enrollment report
45
		// pdf
46
	// https://app.box.com/s/gc4ygloi4qtimeh98dq9mmydyuydawcn
47
		// password-protected 7z file (nsfw)
48
	// https://app.box.com/shared/static/su6xx6zx50cd68zdtbm3wfxhh9kwke8x.zip
49
		// a soundtrack in a zip file
50
		// This is a static download, so it works without this script.
51
	// https://app.box.com/s/vysdh2u78yih3c8leetgq82il954a3g3
52
		// some gambling ad
53
		// pptx
54
	// https://app.box.com/s/nnlplkmjhimau404qohh9my10pwmo8es
55
		// a list of books(?)
56
		// txt
57
	// https://ucla.app.box.com/s/mv32q624ojihohzh8d0mhhj0b3xluzbz
58
		// "COVID-19 Pivot Plan Decision Matrix"
59
		// If you load the proprietary scripts on this page, you'll see that there is no download button
60
	// TODO: find a public folder link (the private links I have seem to work)
61
	// TODO: find a (preferably public) link with a folder inside a folder, as these may need to be handled differently
62

    
63
/* Extract data from a script that sets multiple variables. */ // from here: https://api-demo.hachette-hydrilla.org/content/sgoogle_sheets_download/google_sheets_download.js
64

    
65
let prefetchedData = null; // This variable isn't actually used.
66
for (const script of document.scripts) {
67
    const match = /Box.prefetchedData = ({([^;]|[^}];)+})/.exec(script.textContent); // looks for "Box.prefetchedData = " in the script files and then grabs the json text after that.
68
    if (!match)
69
	continue;
70
    prefetchedData = JSON.parse(match[1]);
71
}
72

    
73
let config = null;
74
for (const script of document.scripts) {
75
    const match = /Box.config = ({([^;]|[^}];)+})/.exec(script.textContent); // looks for "Box.config = " in the script files and then grabs the json text after that.
76
    if (!match)
77
	continue;
78
    config = JSON.parse(match[1]);
79
}
80

    
81
let postStreamData = null;
82
for (const script of document.scripts) {
83
    const match = /Box.postStreamData = ({([^;]|[^}];)+})/.exec(script.textContent); // looks for "Box.postStreamData = " in the script files and then grabs the json text after that.
84
    if (!match)
85
	continue;
86
    postStreamData = JSON.parse(match[1]);
87
}
88

    
89
// get domain from URL
90
const domain = document.location.href.split("/")[2];
91

    
92
/* Replace current page contents. */
93
const replacement_html = `\
94
<!DOCTYPE html>
95
<html>
96
  <head>
97
    <style>
98
      button, .button {
99
          border-radius: 10px;
100
          padding: 20px;
101
          color: #333;
102
          background-color:
103
          lightgreen;
104
          text-decoration: none;
105
          display: inline-block;
106
      }
107
      button:hover, .button:hover {
108
          box-shadow: -4px 8px 8px #888;
109
      }
110

    
111
      .hide {
112
          display: none;
113
      }
114

    
115
      #download_button .unofficial, #download_button .red_note {
116
          display: none;
117
      }
118
      #download_button.unofficial .unofficial {
119
          display: inline;
120
      }
121
      #download_button.unofficial .red_note {
122
          display: block;
123
      }
124
      .red_note {
125
          font-size: 75%;
126
          color: #c55;
127
          font-style: italic;
128
          text-align: center;
129
      }
130
    </style>
131
  </head>
132
  <body>
133
    <h1 id="loading" class="hide">loading...</h1>
134
    <h1 id="error" class="hide">error occured :(</h1>
135
    <h1 id="title" class="hide"></h1>
136
    <div id="single_file_section" class="hide">
137
      <a id="download_button" class="button">
138
        <span class="unofficial">unofficial</span> download
139
        <aside class="red_note">(officially disallowed)</aside>
140
      </a>
141
      <aside></aside>
142
      <h2>File info</h2>
143
      <div id="file_info"></div>
144
    </div>
145
  </body>
146
</html>
147
`;
148

    
149
/*
150
 * We could instead use document.write(), but browser's debugging tools would
151
 * not see the new page contents.
152
 */
153
const parser = new DOMParser();
154
const alt_doc = parser.parseFromString(replacement_html, "text/html");
155
document.documentElement.replaceWith(alt_doc.documentElement);
156

    
157
const nodes = {};
158
document.querySelectorAll('[id]').forEach(node => nodes[node.id] = node);
159

    
160
function show_error() {
161
    nodes.loading.classList.add("hide");
162
    nodes.error.classList.remove("hide");
163
}
164

    
165
function show_title(text) {
166
    nodes.title.innerText = text;
167
    nodes.loading.classList.add("hide");
168
    nodes.title.classList.remove("hide");
169
}
170

    
171
async function hack_file() {
172
    nodes.loading.classList.remove("hide");
173

    
174
    const tokens_url = "/app-api/enduserapp/elements/tokens";
175
    const file_nr = postStreamData["/app-api/enduserapp/shared-item"].itemID;
176
    const file_id = `file_${file_nr}`;
177
    const shared_name = postStreamData["/app-api/enduserapp/shared-item"].sharedName;
178

    
179
    /*
180
     * We need to perform a POST to obtain a token that will be used later to
181
     * authenticate against Box's API endpoint.
182
     */
183
    const tokens_response = await fetch(tokens_url, {
184
	method: "POST",
185
	headers: {
186
	    "Accept":               "application/json",
187
	    "Content-Type":         "application/json",
188
	    "Request-Token":        config.requestToken,
189
	    "X-Box-Client-Name":    "enduserapp",
190
	    "X-Box-Client-Version": "20.712.2",
191
	    "X-Box-EndUser-API":    `sharedName=${shared_name}`,
192
	    "X-Request-Token":      config.requestToken
193
	},
194
	body: JSON.stringify({"fileIDs": [file_id]})
195
    });
196
    console.log("tokens_response", tokens_response);
197

    
198
    const access_token = (await tokens_response.json())[file_id].read;
199
    console.log("access_token", access_token);
200

    
201
    const fields = [
202
	"permissions", "shared_link", "sha1", "file_version", "name", "size",
203
	"extension", "representations", "watermark_info",
204
	"authenticated_download_url", "is_download_available",
205
	"content_created_at", "content_modified_at", "created_at", "created_by",
206
	"modified_at", "modified_by", "owned_by", "description",
207
	"metadata.global.boxSkillsCards", "expires_at", "version_limit",
208
	"version_number", "is_externally_owned", "restored_from",
209
	"uploader_display_name"
210
    ];
211

    
212
    const file_info_url =
213
	  `https://api.box.com/2.0/files/${file_nr}?fields=${fields.join()}`;
214

    
215
    /*
216
     * We need to perform a GET to obtain file metadata. The fields we curently
217
     * make use of are "authenticated_download_url" and "file_version", but in
218
     * the request we also include names of other fields that the original Box
219
     * client would include. The metadata is then dumped as JSON on the page, so
220
     * the user, if curious, can look at it.
221
     */
222
    const file_info_response = await fetch(file_info_url, {
223
	headers: {
224
	    "Accept":            "application/json",
225
	    "Authorization":     `Bearer ${access_token}`,
226
	    "BoxApi":            `shared_link=${document.URL}`,
227
	    "X-Box-Client-Name": "ContentPreview",
228
	    "X-Rep-Hints":       "[3d][pdf][text][mp3][json][jpg?dimensions=1024x1024&paged=false][jpg?dimensions=2048x2048,png?dimensions=2048x2048][dash,mp4][filmstrip]"
229
	},
230
    });
231
    console.log("file_info_response", file_info_response);
232

    
233
    const file_info = await file_info_response.json();
234
    console.log("file_info", file_info);
235

    
236
    const params = new URLSearchParams();
237
    params.set("preview",            true);
238
    params.set("version",            file_info.file_version.id);
239
    params.set("access_token",       access_token);
240
    params.set("shared_link",        document.URL);
241
    params.set("box_client_name",    "box-content-preview");
242
    params.set("box_client_version", "2.82.0");
243
    params.set("encoding",           "gzip");
244

    
245
    /* We use file metadata from earlier requests to construct the link. */
246
    const download_url =
247
	  `${file_info.authenticated_download_url}?${params.toString()}`;
248
    console.log("download_url", download_url);
249

    
250
    show_title(file_info.name);
251

    
252
    nodes.download_button.href = download_url;
253
    if (!file_info.permissions.can_download)
254
	nodes.download_button.classList.add("unofficial");
255
    nodes.file_info.innerText =  JSON.stringify(file_info);
256
    nodes.single_file_section.classList.remove("hide");
257
}
258

    
259
if (postStreamData["/app-api/enduserapp/shared-item"].itemType == "file") {
260
    /*
261
     * We call hack_file and in case it asynchronously throws an exception, we
262
     * make an error message appear.
263
     */
264
    hack_file().then(() => {}, show_error);
265
} else if (postStreamData["/app-api/enduserapp/shared-item"].itemType == "folder") {
266
    show_title(postStreamData["/app-api/enduserapp/shared-folder"].currentFolderName);
267

    
268
    // TODO: implement a download folder button (included in proprietary app)
269
    /*
270
      The original download folder button sends a GET request that gets 2 URLs
271
      in the response. 1 of those URLs downloads the file, and a POST request
272
      is sent after (or maybe while in some cases?) a file is downloaded, to
273
      let the server know how much is downloaded.
274
    */
275
    // for each item in the folder, show a button with a link to download it
276
    postStreamData["/app-api/enduserapp/shared-folder"].items.forEach(function(item) {
277
	console.log("item", item);
278

    
279
	const file_direct_url = "https://"+domain+"/index.php?rm=box_download_shared_file&shared_name="+postStreamData["/app-api/enduserapp/shared-item"].sharedName+"&file_id="+item.typedID;
280

    
281
	const folderButton = nodes.download_button.cloneNode(false);
282
	folderButton.removeAttribute("id");
283

    
284
	if (item.type == "file") {
285
	    folderButton.href = file_direct_url;
286
	    folderButton.innerText = item.name; // show the name of the file
287
	} else if (item.type == "folder") {
288
	    folderButton.innerText = "[folders inside folders not yet supported]";
289
	} else {
290
	    folderButton.innerText = "[this item type is not supported]";
291
	}
292

    
293
	document.body.appendChild(folderButton);
294
    });
295
} else {
296
	console.log('expected "folder" or "file" as the item type (postStreamData["/app-api/enduserapp/shared-item"].itemType) but got ' + postStreamData["/app-api/enduserapp/shared-item"].itemType + ' instead; this item type is not implemented');
297
	show_error();
298
}
(1-1/2)