Project

General

Profile

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

hydrilla-fixes-bundle / src / box.js @ e24c60dd

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

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

    
65
/* 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
66

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

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

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

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

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

    
113
      .hide {
114
          display: none;
115
      }
116

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

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

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

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

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

    
173
async function hack_file() {
174
    nodes.loading.classList.remove("hide");
175

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

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

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

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

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

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

    
235
    const file_info = await file_info_response.json();
236
    console.log("file_info", file_info);
237

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

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

    
252
    show_title(file_info.name);
253

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

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

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

    
281
	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;
282

    
283
	const folderButton = nodes.download_button.cloneNode(false);
284
	folderButton.removeAttribute("id");
285

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

    
295
	document.body.appendChild(folderButton);
296
    });
297
} else {
298
	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');
299
	show_error();
300
}
(3-3/22)