-
Notifications
You must be signed in to change notification settings - Fork 1
/
onedrive-base
406 lines (329 loc) · 11 KB
/
onedrive-base
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
api_auth_url="https://login.live.com/oauth20_token.srf"
api_base_url="https://api.onedrive.com/v1.0"
get_json_value="cut -d= -f2-"
curl_opts="--silent --retry ${http_retries} --retry-delay 10"
function error() {
echo "$1" >&2
exit 1
}
function exit_on_error() {
if (( $? > 0 )); then
exit 1
fi
}
function debug() {
if [ "${debug_mode}" == "1" ]; then
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
echo "${timestamp} $1" >&2
fi
}
function info() {
if [ "${silent_mode}" == "0" ]; then
echo "$1"
fi
}
# $1=parameter to encode
function urlencode() {
curl \
--silent \
--output /dev/null \
--write-out "%{url_effective}" \
--get \
--data-urlencode "$1" \
"" | cut -b3-
}
# ------------------ #
# --- cURL calls --- #
# ------------------ #
# $1=old refresh token
function curl_refresh_access_token() {
debug "Acquiring new access token"
curl \
${curl_opts} \
--data-urlencode "client_id=${api_client_id}" \
--data-urlencode "client_secret=${api_client_secret}" \
--data-urlencode "refresh_token=$1" \
--data-urlencode "grant_type=refresh_token" \
"${api_auth_url}" | "${json_parser}"
}
# $1=resource and folder identifier (e.g. root:/subfolder: or just root)
function curl_create_folder() {
debug "Creating folder $1"
local json_payload="{\"folder\":{},\"@name.conflictBehavior\":\"replace\"}"
local resource=$(urlencode "$1")
curl \
${curl_opts} \
--request PATCH \
--output /dev/null \
--write-out "%{http_code}" \
--header "Content-Type: application/json" \
--data "${json_payload}" \
"${api_base_url}/drive/${resource}?access_token=${api_access_token}"
}
function curl_upload_file() {
local url="${api_base_url}/drive/${api_upload_destination}/content?access_token=${api_access_token}&@name.conflictBehavior=replace"
debug "Uploading '${file}' into ${api_upload_destination}"
curl \
${curl_opts} \
--request PUT \
--output /dev/null \
--write-out "%{http_code}" \
--upload-file "${file}" \
"${url}"
}
function curl_request_upload_session() {
local json_payload="{\"item\":{\"@name.conflictBehavior\":\"replace\"}}"
local url="${api_base_url}/drive/${api_upload_destination}/upload.createSession?access_token=${api_access_token}"
debug "Uploading '${file}' into ${api_upload_destination}"
curl \
${curl_opts} \
--request POST \
--header "Content-Type: application/json" \
--data "${json_payload}" \
"${url}" | "${json_parser}"
if [ "${PIPESTATUS[0]}" != "0" ]; then
error "Could not retrieve an upload session for '${filename}' in '$1'"
fi
}
# $1=upload url
function curl_delete_upload_session() {
curl \
${curl_opts} \
--request DELETE \
--output /dev/null \
--write-out "%{http_code}" \
"${1}"
}
# $1=upload url
# $2=current chunk
function curl_upload_chunk() {
local current_range_start
local current_range_end
local current_range_length
current_range_start=$(($2*${max_chunk_size}))
current_range_end=$((${current_range_start}+${max_chunk_size}-1))
if [ ${current_range_end} -gt ${filesize} ]; then
current_range_end=$((${filesize}-1))
fi
current_range_length=$((${current_range_end}-${current_range_start}+1))
debug "Content-Length: ${current_range_length}"
debug "Content-Range: bytes ${current_range_start}-${current_range_end}/${filesize}"
dd if="${file}" count=1 skip=$2 bs=${max_chunk_size} 2>/dev/null | curl \
${curl_opts} \
--request PUT \
--output /dev/null \
--write-out "%{http_code}" \
--header "Content-Length: ${current_range_length}" \
--header "Content-Range: bytes ${current_range_start}-${current_range_end}/${filesize}" \
--data-binary @- \
"${1}?access_token=${api_access_token}"
}
# ------------------------ #
# --- TOKEN MANAGEMENT --- #
# ------------------------ #
function filesystem_load_refresh_token() {
if [ ! -f "${refresh_token_file}" ]; then
error "Refresh token not found, please complete the authorization process first"
fi
cat "${refresh_token_file}"
}
# $1=new refresh token
function filesystem_save_refresh_token() {
if [ "$1" == "" ]; then
error "No refresh token received from API. Please try again or re-authorize."
fi
echo "$1" > "${refresh_token_file}.$$"
mv "${refresh_token_file}.$$" "${refresh_token_file}" > /dev/null 2>&1
if [ "$?" != "0" ]; then
debug "Could not write refresh_token because of another process, deleting ${refresh_token_file}.$$"
rm "${refresh_token_file}.$$"
fi
}
function onedrive_acquire_access_token() {
local old_refresh_token
local new_refresh_token
local api_parsed_json_result
local current_access_token
old_refresh_token=$(filesystem_load_refresh_token)
exit_on_error
api_parsed_json_result=$(curl_refresh_access_token "${old_refresh_token}")
new_refresh_token=$(echo "${api_parsed_json_result}" | grep "refresh_token" | ${get_json_value})
filesystem_save_refresh_token "${new_refresh_token}"
exit_on_error
current_access_token=$(echo "${api_parsed_json_result}" | grep "access_token" | ${get_json_value})
if [ "${current_access_token}" == "" ]; then
error "An error has occurred while refreshing the access token: ${api_parsed_json_result}"
fi
echo "${current_access_token}"
}
# --------------------------------- #
# --- UPLOAD SESSION MANAGEMENT --- #
# --------------------------------- #
# $1=file
function filesystem_get_filesize() {
if [[ $(uname) == "Darwin" ]]; then
stat -f%z "$1"
else
stat -c%s "$1"
fi
}
# $1=folder id
function onedrive_request_upload_session() {
local api_parsed_json_result
local upload_url
api_parsed_json_result=$(curl_request_upload_session "$1")
exit_on_error
upload_url=$(echo "${api_parsed_json_result}" | grep "uploadUrl" | ${get_json_value})
# Remove access_token from upload_url
upload_url=$(echo "${upload_url/?access_token=*/}")
if [ "${upload_url}" == "" ]; then
error "An error has occurred while requesting an upload session: ${api_parsed_json_result}"
fi
echo "${upload_url}"
}
# ------------------------- #
# --- FOLDER MANAGEMENT --- #
# ------------------------- #
# $1=top level flag
# $1=current remote path
# $2=current stripped prefix length (-1 for first level)
# $3+=files and folders to upload
#
# Fills the array remote_local_pairs with relative remote folders and local paths
# Creates
function onedrive_build_remote_local_pairs_recursion() {
local top_level="$1"
shift
local current_remote_path="${1%/}"
shift
while [[ $# -ge 1 ]]; do
if [ -f "$1" ]; then
local local_path="$1"
local remote_filename
if [ ${rename_mode} -eq 1 ] && [ ${top_level} -eq 1 ]; then
shift
remote_filename="$1"
else
remote_filename=$(basename "$1")
fi
remote_local_pairs+=($(urlencode "${api_drive_resource}:${current_remote_path}/${remote_filename}:"))
remote_local_pairs+=("$local_path")
elif [ -d "$1" ]; then
local next_local_path="${1%/}"
local next_entries=("${next_local_path}/"*)
local current_folder_name
if [ ${rename_mode} -eq 1 ] && [ ${top_level} -eq 1 ]; then
shift
current_folder_name="$1"
else
current_folder_name=$(basename "$1")
fi
status_code=$(curl_create_folder "${api_drive_resource}:${current_remote_path}/${current_folder_name}:")
if [ "${status_code}" == "200" ] || [ "${status_code}" == "201" ]; then
debug "Successfully created folder '${current_remote_path}/${current_folder_name}'"
else
error "An error has occurred while creating folder '${current_remote_path}/${current_folder_name}' (Code: ${status_code})"
fi
if test -e "${next_entries}"; then
onedrive_build_remote_local_pairs_recursion 0 "${current_remote_path}/${current_folder_name}" "${next_entries[@]}"
else
info "Successfully created empty folder '${current_remote_path}/${current_folder_name}'"
fi
fi
shift
done
}
# $1=global path prefix (without trailing slash)
# $2+=files and folders to upload
#
# Fills the array remote_local_pairs with relative remote folders and local paths
# Creates
function onedrive_build_remote_local_pairs() {
api_access_token=$(onedrive_acquire_access_token)
exit_on_error
local current_remote_path="${1#/}"
current_remote_path="${current_remote_path#./}"
shift
onedrive_build_remote_local_pairs_recursion 1 "/${current_remote_path}" "${@}"
}
# ------------------- #
# --- FILE UPLOAD --- #
# ------------------- #
function onedrive_upload_file_simple() {
if [ ! -f "${file}" ]; then
error "An error has occurred while uploading '${file}' (File does not exist)"
fi
api_access_token=$(onedrive_acquire_access_token)
exit_on_error
curl_upload_file "${api_folder_id}"
}
function onedrive_upload_file_chunked() {
api_access_token=$(onedrive_acquire_access_token)
exit_on_error
debug "Requesting upload session for '${file}'"
local upload_url
upload_url=$(onedrive_request_upload_session "${api_folder_id}")
exit_on_error
local current_chunk=0
local status_code=""
while [ $((${current_chunk}*${max_chunk_size})) -lt ${filesize} ]; do
# Acquire a token for each chunk to ensure that it has not yet expired. This WILL slow things down a little bit.
api_access_token=$(onedrive_acquire_access_token)
exit_on_error
debug "Uploading chunk ${current_chunk} of '${file}'"
local retry_count=0
status_code=""
while [ ${retry_count} -lt ${chunk_retries} ] && \
[ ! "${status_code}" == "200" ] && \
[ ! "${status_code}" == "201" ] && \
[ ! "${status_code}" == "202" ] && \
[ ! "${status_code}" == "204" ]; do
if [ ${retry_count} -gt 0 ]; then
debug "Retrying upload of chunk ${current_chunk} of '${file}' (Previous code: ${status_code})"
fi
status_code=$(curl_upload_chunk "${upload_url}" "${current_chunk}")
retry_count=$((retry_count+1))
done
debug "Upload of chunk ${current_chunk} of '${file}' finished (Code: ${status_code})"
if [ ! "${status_code}" == "200" ] && \
[ ! "${status_code}" == "201" ] && \
[ ! "${status_code}" == "202" ] && \
[ ! "${status_code}" == "204" ]; then
curl_delete_upload_session "${upload_url}" > /dev/null
echo "${status_code}"
return;
fi
current_chunk=$((${current_chunk}+1))
done
echo "${status_code}"
}
function onedrive_upload_file() {
if [ ! -f "$1" ]; then
error "An error has occurred while uploading '$1' (File does not exist)"
fi
file="$1"
filename=$(basename "${file}")
filesize=$(filesystem_get_filesize "${file}")
local retry_count=0
local status_code=""
while [ ${retry_count} -lt ${file_retries} ] && \
[ ! "${status_code}" == "200" ] && \
[ ! "${status_code}" == "201" ]; do
if [ ${retry_count} -gt 0 ]; then
debug "Retrying full upload of '${file}' (Previous code: ${status_code})"
fi
if [ ${filesize} -gt ${max_simple_upload_size} ]; then
debug "Size of ${filename} is more than ${max_simple_upload_size} bytes, will use chunked upload"
status_code=$(onedrive_upload_file_chunked)
else
debug "Size of ${filename} is less than or equal to ${max_simple_upload_size} bytes, will use simple upload"
status_code=$(onedrive_upload_file_simple)
fi
retry_count=$((retry_count+1))
done
if [ "${status_code}" == "200" ] || [ "${status_code}" == "201" ]; then
info "Successfully uploaded '${file}'"
else
error "An error has occurred while uploading '${file}' (Code: ${status_code})"
fi
}