-
Notifications
You must be signed in to change notification settings - Fork 1
/
2-generate.tsx
205 lines (182 loc) · 5.05 KB
/
2-generate.tsx
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
import TextField from '@mui/material/TextField';
import { add, commit, init } from 'isomorphic-git';
import { createFsFromVolume, Volume } from 'memfs';
import { MutableRefObject, useState } from 'react';
import Step, { Download, Progress } from '@/components/Step';
import { getAllRevisions } from '@/lib/drive';
import { zipFiles } from '@/lib/files';
const downloadMimeTypes: Record<string, string> = {
// 'text/html': 'html',
'text/plain': 'txt',
};
const docIdPattern = /^\s*[\w-]+\s*$/;
const docUrlPattern = /docs.google.com\/(?:u\/\d+\/)?document\/d\/([\w-]+)/i;
export const DOC_INVALID_ERROR = `This doesn't appear to be a valid Google Doc URL or ID`;
export const DOC_FETCH_ERROR = `Failed to list the revisions for this doc. Are you sure that it's a valid doc URL or ID, and that the account you've signed in with has access?`;
export interface Step2GenerateProps {
docUrl: string;
setDocUrl: (docUrl: string) => void;
googleReady: Promise<boolean>;
actionLoading: boolean;
setActionLoading: (actionLoading: boolean) => void;
error: string;
setError: (error: string) => void;
setDownload: (download: Download) => void;
setProgress: (progress: Progress) => void;
tokenClient?: google.accounts.oauth2.TokenClient;
tokenCallback: MutableRefObject<
undefined | ((resp: google.accounts.oauth2.TokenResponse) => void)
>;
next: () => Promise<void>;
back: () => void;
doneCallback?: () => void;
}
const Step2Generate = ({
docUrl,
setDocUrl,
googleReady,
actionLoading,
setActionLoading,
error,
setError,
setDownload,
setProgress,
tokenCallback,
tokenClient,
next,
back,
doneCallback,
}: Step2GenerateProps): JSX.Element => {
const [docUrlError, setDocUrlError] = useState('');
const action = async (): Promise<void> => {
let docId: string;
const m = docUrlPattern.exec(docUrl);
if (m && m[1].length > 0) {
docId = m[1];
} else if (docIdPattern.test(docUrl)) {
docId = docUrl.trim();
} else {
setDocUrlError(DOC_INVALID_ERROR);
return;
}
setDocUrlError('');
setActionLoading(true);
if (!(await googleReady)) {
setActionLoading(false);
return;
}
const revisions = await getAllRevisions(docId)
.catch((error_: any) => {
if (
error_.result === undefined ||
error_.result.error === undefined ||
(error_.result.error.code !== 401 &&
(error_.result.error.code !== 403 ||
error_.result.error.status !== 'PERMISSION_DENIED'))
) {
throw new Error(error_);
}
if (tokenClient === undefined) {
throw new Error('tokenClient is undefined');
}
return new Promise((resolve, reject) => {
tokenCallback.current = (
resp: google.accounts.oauth2.TokenResponse,
): void => {
if (resp.error !== undefined) {
return reject(resp);
}
resolve(resp);
};
tokenClient.requestAccessToken();
});
})
.then((_retry: any) => getAllRevisions(docId))
.catch((_: any) => {
// Ignore actual error, will show user-friendly error below.
});
if (!revisions) {
setActionLoading(false);
setError(DOC_FETCH_ERROR);
return;
}
next();
setProgress({ percent: 0, status: 'Creating Git repo...' });
const vol = new Volume();
const fs = createFsFromVolume(vol);
await init({ fs, dir: '/' });
const fetchParams = {
headers: {
Authorization: `Bearer ${gapi.client.getToken().access_token}`,
},
};
let i = 0;
for (const rev of revisions) {
++i;
if (rev.id === undefined || !rev.exportLinks) {
continue;
}
const downloads = [];
for (const [mimeType, url] of Object.entries(rev.exportLinks)) {
if (mimeType in downloadMimeTypes) {
const filepath = `doc.${downloadMimeTypes[mimeType]}`;
downloads.push(
fetch(url, fetchParams)
.then((resp) => resp.arrayBuffer())
.then((buf) => fs.writeFileSync(`/${filepath}`, Buffer.from(buf)))
.then(() => add({ fs, dir: '/', filepath })),
);
}
}
await Promise.all(downloads);
await commit({
fs,
dir: '/',
message: `Revision #${rev.id}`,
author: {
name: rev.lastModifyingUser?.displayName,
email: rev.lastModifyingUser?.emailAddress,
timestamp:
rev.modifiedTime !== undefined
? Math.floor(Date.parse(rev.modifiedTime) / 1000)
: 0,
},
});
setProgress({
percent: (100 * i) / revisions.length,
status: `Adding revision ${i} of ${revisions.length}`,
});
}
setProgress({ percent: 100, status: 'Done' });
const zipBlob = await zipFiles(fs);
setDownload({
download: `doc2git-${docId}.zip`,
href: URL.createObjectURL(zipBlob),
});
setActionLoading(false);
if (doneCallback !== undefined) {
doneCallback();
}
};
return (
<Step
actionLoading={actionLoading}
action={action}
actionLabel="Generate"
error={error}
setError={setError}
back={back}>
<TextField
label="URL or ID"
value={docUrl}
onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
setDocUrl(event.target.value);
}}
error={docUrlError !== ''}
helperText={docUrlError}
/>
,
</Step>
);
};
export default Step2Generate;