-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathupdate_libgen
executable file
·463 lines (390 loc) · 10.9 KB
/
update_libgen
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#!/usr/bin/env bash
# shellcheck disable=SC2034,SC1090,SC2155,SC2207
version="0.6.1"
release="20210512"
trap "trap_error" TERM
trap "trap_clean" EXIT
export TOP_PID=$$
LC_ALL=C
functions="$(dirname "$0")/books_functions"
if [ -f "$functions" ]; then
source "$functions"
else
echo "$functions not found"
exit 1
fi
main () {
exlock now || exit 1
# PREFERENCES
config=${XDG_CONFIG_HOME:-$HOME/.config}/books.conf
dbhost="localhost"
dbport="3306"
db="libgen"
dbuser="libgen"
limit=1000
api="http://libgen.rs/json.php"
# source config file if it exists
[[ -f ${config} ]] && source "${config}"
# (more or less) END OF PREFERENCES
jq=$(find_tool "jq")
curl=$(find_tool "curl")
tmpdir=$(mktemp -d '/tmp/update_libgen.XXXXXX')
updates="${tmpdir}/updates"
update_count="${tmpdir}/update_count"
update_sql="${tmpdir}/update_sql"
update_last_modified="${tmpdir}/update_last_modified"
update_last_id="${tmpdir}/update_last_id"
update_newer="${tmpdir}/update_newer"
verbose=0
no_action=0
unknown_fields=""
re_type='[a-z]+'
re_int='[0-9]+'
re_year='[0-9]{4}'
re_timestamp='[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]:[0-5][0-9]:[0-5][0-9]'
declare -a tables="(description hashes updated)"
declare -A current_fields="($(get_current_fields))"
declare -A field_types="($(get_field_types))"
declare -A field_sizes="($(get_field_sizes))"
declare -A columns=()
declare -A values=()
declare -A upsert=()
while getopts "a:D:j:hH:i:l:nP:U:qs:ct:u:v@:" OPTION
do
case $OPTION in
j)
json_dump="${OPTARG}"
;;
s)
sql_dump="${OPTARG}"
;;
c)
classify=$(find_tool "classify")
import_metadata=$(find_tool "import_metadata")
classifile="${tmpdir}/classifile"
;;
v)
((verbose++))
;;
n)
no_action=1
;;
l)
limit="${OPTARG}"
if [[ $limit -le 1 ]]; then
exit_wit_error "limit too low (-l ${limit}), minimum is 2"
fi
;;
t)
startdatetime="${OPTARG}"
;;
i)
echo "${OPTARG}" > "${update_last_id}"
;;
u)
api="${OPTARG}"
;;
H)
dbhost="${OPTARG}"
;;
P)
dbport="${OPTARG}"
;;
U)
dbuser="${OPTARG}"
;;
D)
db="${OPTARG}"
;;
a)
if url_available "${OPTARG}?fields=id&ids=0"; then
api="${OPTARG}"
else
exit_with_error "-a ${OPTARG}: API endpoint not available"
fi
;;
@)
torsocks=$(find_tool "torsocks")
export TORSOCKS_TOR_PORT=${OPTARG}
;;
q)
quiet=1
;;
h)
help
exit
;;
*)
exit_with_error "unknown option $OPTION"
;;
esac
done
check_fields
while (
if [[ -s ${update_last_modified} ]]; then
last_update="$(cat "${update_last_modified}")"
last_update_in_db="$(get_time_last_modified)"
if [[ $last_update != "$last_update_in_db" && $no_action == 0 ]]; then
exit_with_error "uh oh... something went wrong, last update in db does not equal last update from api response..."
fi
elif [[ -n $startdatetime ]]; then
last_update="${startdatetime}"
else
last_update="$(get_time_last_modified)"
fi
last_id=$([[ -s ${update_last_id} ]] && cat "${update_last_id}" || get_max_id)
get_updates "$last_id" "$limit" "$last_update"
updcnt=$(get_update_count)
[[ -n $json_dump ]] && cat "${updates}" >> "${json_dump}"
if [[ $verbose -ge 1 ]]; then
echo "database last modified: $last_update";
# update counter is 0-based, humans prefer 1-based notation
if [[ ${updcnt} -gt 0 ]]; then
echo "$((updcnt+1)) updates";
else
more=$([[ -s $update_last_id ]] && echo "more " || echo "")
echo "no ${more}updates"
fi
echo ;
fi
test "$updcnt" -gt 0
); do
updcnt=$(get_update_count)
count=0
echo "start transaction;" > "${update_sql}"
while [[ $count -le $updcnt ]]; do
declare -A record
while IFS="=" read -r key value; do
# drop unknown fields
if [[ ! $unknown_fields =~ ${key,,} ]]; then
# limit field size to avoid choking jq on overly long strings
[[ ${#value} -gt 1000 ]] && value="${value:0:997}..."
record[${key,,}]="$value"
fi
done < <($jq -r ".[$count]"'|to_entries|map("\(.key)=\(.value|tostring|.[0:4000]|gsub("\n";"\\n"))")|.[]' "${updates}")
# record current position
echo "${record['id']}" > "${update_last_id}"
echo "${record['timelastmodified']}" > "${update_last_modified}"
if [[ $verbose -ge 2 ]]; then
echo "ID: ${record['id']}";
echo "Author: ${record['author']}";
echo "Title: ${record['title']}";
echo "Modified: ${record['timelastmodified']}";
echo
fi
if [[ -n "$classifile" && -n "${record['identifierwodash']}" ]]; then
echo "${record['md5']}" >> "$classifile"
fi
keys=${!record[*]}
md5="${record[md5]}"
# split fields between tables
for key in "${!record[@]}"; do
table=${current_fields[$key]}
columns[$table]+="${key},"
value=${record[$key]}
if [ -n "$value" ]; then
value=$(sanitize_field "$key" "$value")
fi
values[$table]+="'$value',"
upsert[$table]+="${key} = values(${key}),"
done
# add md5 to secondary tables (all but the last)
for n in $(seq 0 $((${#tables[@]}-2))); do
table="${tables[$n]}"
if [[ -n "${columns[$table]}" ]]; then
columns[$table]+="md5,"
values[$table]+="'$md5',"
upsert[$table]+="md5 = values(md5),"
fi
done
# main table (last in tables array) first
for n in $(seq $((${#tables[@]}-1)) -1 0); do
table="${tables[$n]}"
if [[ -n "${columns[$table]}" ]]; then
sql+="insert into $table (${columns[$table]%?}) values(${values[$table]%?}) on duplicate key update ${upsert[$table]%?};"
fi
done
echo "${sql}" >> "${update_sql}"
[[ -n $sql_dump ]] && echo "${sql}" >> "${sql_dump}"
unset record
unset keys
unset key
unset value
unset sql
columns=()
values=()
upsert=()
((count++))
done
echo "commit;" >> "${update_sql}"
[[ $no_action == 0 ]] && dbx "$db" < "${update_sql}"
done
# optionally add classification data to new records
# this will use tor and round-robin through TOR ports if these are
# defined in classify_tor_ports in the config file
if [[ -n "$classifile" && -f $classifile ]]; then
now=$(date +%Y%m%d%H%M)
csvfile="${classify_csv:+$classify_csv/}${now}.csv"
IFS=',' read -ra torports <<< "$classify_tor_ports"
if [[ ${#torports[*]} -gt 0 ]]; then
torpc=${#torports[*]}
fi
upc=0
while read md5;do
$classify ${torpc:+-@ ${torports[$upc%$torpc]}} -D "$db" ${classify_xml:+-X $classify_xml} -C "$md5" >> "${csvfile}"
((upc++))
done < <(cat "$classifile")
if [[ -f ${csvfile} ]]; then
$import_metadata -d "$db" -f "${classify_fields:-ddc,lcc,fast}" ${classify_sql:+-s $classify_sql/$now.sql} -F "${csvfile}"
fi
fi
}
get_current_fields () {
for table in "${tables[@]}"; do
dbx "$db" "describe $table;"|awk '{print "["tolower($1)"]='"$table"'"}'
done
}
get_field_type () {
field="$1"
table="${current_fields[$field]}"
dbx "$db" "show fields from $table where field=\"$field\";"|awk '{print $2}'
}
get_field_types () {
for field in "${!current_fields[@]}"; do
fieldtype=$(get_field_type "$field")
[[ "$fieldtype" =~ $re_type ]]
echo -n "[$field]=${BASH_REMATCH[0]} "
done
}
get_field_sizes () {
for field in "${!current_fields[@]}"; do
fieldtype=$(get_field_type "$field")
[[ "$fieldtype" =~ $re_int ]]
if [[ "${BASH_REMATCH[0]}" -gt 0 ]]; then
echo -n "[$field]=${BASH_REMATCH[0]} "
fi
done
}
# sanitize_field FIELD VALUE
sanitize_field () {
field=$1
shift
value="$*"
# quote values for SQL
value=${value//\\/\\\\}
value=${value//\'/\\\'}
# field-type specific filters
case "${field_types[$field]}" in
int|bigint)
[[ "$value" =~ $re_int ]]
value=${BASH_REMATCH[0]}
value=${value:0:${field_sizes[$field]}}
;;
char|varchar)
value=${value:0:${field_sizes[$field]}}
;;
timestamp)
[[ "$value" =~ $re_timestamp ]]
value=${BASH_REMATCH[0]}
;;
esac
# field-specific filters
case "$field" in
year)
# filter out Chinese date stamps
[[ "$value" =~ $re_year ]]
value=${BASH_REMATCH[0]}
;;
esac
echo -n "$value"
}
# libgen_api ID LIMIT TIME_LAST_MODIFIED
libgen_api () {
id="$1"
shift
limit="$1"
shift
if ! newer=$(date -d "$*" +'%Y-%m-%d%%20%H:%M:%S'); then
exit_with_error "date error: $* is not a valid date"
fi
echo "$newer" > "$update_newer"
$torsocks "$curl" -s "${api}?"'fields=*&idnewer='"${id}"'&mode=newer&limit1='"${limit}"'&timenewer='"${newer}"
}
# get_updates ID LIMIT TIME_LAST_MODIFIED
get_updates () {
id="$1"
shift
limit="$1"
shift
last="$*"
libgen_api "$id" "$limit" "$last" > "${updates}"
$jq '.|length' "${updates}" > "${update_count}"
}
get_time_last_modified () {
dbx "$db" 'select MAX(TimeLastModified) FROM updated;'|tail -1
}
get_max_id () {
dbx "$db" 'select MAX(id) FROM updated;'|tail -1
}
get_update_count () {
echo $(($(cat "${update_count}")-1))
}
check_fields () {
updates_fields=($(libgen_api 1 2 '2000-01-01'|$jq -r '.[0]|keys|@sh'))
db_fields="${!current_fields[*]}"
db_fields="${db_fields,,}"
# check for extra fields in api response
for index in "${!updates_fields[@]}"; do
field="${updates_fields[$index]%\'}"
field="${field#\'}"
if [[ ! $db_fields =~ ${field,,} ]]; then
if [[ ! -v quiet ]]; then
echo "unknown field in api response: ${field} (consider refreshing database from dump)"
fi
unknown_fields+="${field,,} "
else
:
fi
done
# check for missing fields in api reponse
[[ $verbose -ge 1 ]] && {
for field in "${!current_fields[@]}"; do
if [[ ! -v quiet && ! ${updates_fields[*],,} =~ ${field,,} ]]; then
echo "missing field in api response: $field"
fi
done
}
}
cleanup () {
rm -rf "${tmpdir}"
}
help () {
echo "$(basename "$(readlink -f "$0")")" "version $version"
cat <<- 'EOT'
Usage: update_libgen OPTIONS
-l LIMIT get updates in blocks of LIMIT entries
-v be verbose about what is being updated; repeat for more verbosity:
-v: show basic info (number of updates, etc)
-vv: show ID, Title and TimeLastModified for each update
-n do not update database. Use together with -v or -vv to show
how many (-v) and which (-vv) titles would be updated.
-j FILE dump (append) json to FILE
-s FILE dump (append) sql to FILE
-u URL use URL to access the libgen API (overrides default)
-t DATETIME get updates since DATETIME (ignoring TimeLastModified in database)
use this option together with -s to create an sql update file to update
non-networked machines
-i ID get updates from ID
-H DBHOST database host
-P DBPORT database port
-U DBUSER database user
-D DATABASE database name
-a APIHOST use APIHOST as API server
-@ TORPORT use tor (through torsocks) to connect to libgen API server
-c run classify over new records to get classification data
-q don't warn about missing fields in database or api response
-h this help message
EOT
}
exlock prepare || exit 1
main "$@"