-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfunctions.py
2223 lines (1902 loc) · 71.2 KB
/
functions.py
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
from pathlib import Path
from urllib.parse import *
import uuid
import datetime
import gevent
from gevent import monkey
from gevent import Timeout
from gevent.pool import Pool
import ipaddress
import pandas as pd
from sqlite_utils import Database
import sqlite3
import sys
import shodan
import os
import time
import re
import shutil
from typing import Dict
import json
from humanize import naturalsize as hsize
import humanize
from langid.langid import LanguageIdentifier, model
import iso639
import time
import unidecode
from requests.adapters import HTTPAdapter
import urllib3
import logging
logging.basicConfig(filename='shodantest.log', encoding='utf-8', level=logging.DEBUG)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
global api
api = shodan.Shodan('')
global site_conn
data_dir = "./data/"
site_conn = sqlite3.connect(data_dir + "sites.db")
site_cursor = site_conn.cursor()
########################
# Setup Sites Database #
########################
def init_sites_db(dir=data_dir):
"""
Initializes the sites database.
Parameters:
- dir (str): The directory path where the database file will be created. Default is the current directory.
Returns:
- db (Database): The initialized database object.
"""
print("Dir = ", dir)
logging.info("****Setup Sites Database Function****")
logging.info("Dir = ", dir)
path = Path(dir) / "sites.db"
print("Path = ", path)
logging.info("Database Directory = ", path)
db = Database(path)
if not "sites" in db.table_names():
db["sites"].create({
"uuid": str,
"url": str,
"hostnames": str,
"ports": str,
"country": str,
"isp": str,
"status": str,
"last_online": str,
"last_check": str,
"error": int,
# "schema_version": 1
# # TODO: add the most common formats
}, pk="uuid")
# }, pk="uuid", not_null=True)
# if not "sites" in db.table_names():
# db["sites"].create({
# "uuid": str
# }, pk="uuid",)
db.table("sites", pk='uuid', batch_size=100, alter=True)
return db
########################################
# Save sites found into Sites Database #
########################################
def save_site(db: Database, site):
"""
Saves a site to the database.
Parameters:
- db (Database): The database object to save the site to.
- site (dict): The site to be saved.
This function saves a site to the specified database. If the site does not have a 'uuid' key, a new UUID will be generated and assigned to the site before saving it. The site is saved using the 'upsert' method of the database object, with the primary key set to 'uuid'.
Returns:
- None
"""
logging.info("****Save Site Function****")
# # TODO: Check if the site is not alreday present
# def save_sites(db, sites):
# db["sites"].insert_all(sites, alter=True, batch_size=100)
if not 'uuid' in site:
site['uuid']=str(uuid.uuid4())
print("Site: ",site)
logging.info("Site: %s", site)
db["sites"].upsert(site, pk='uuid')
##########################
# Validate Site and save #
##########################
def check_and_save_site(db, site):
"""
Check and save a site.
Args:
db (database): The database object.
site (str): The site to be checked and saved.
Returns:
None
"""
logging.info("****Check and Save Function****")
res= check_calibre_site(site)
print(res)
logging.info("Result: %s", res)
save_site(db, res)
# import pysnooper
# @pysnooper.snoop()
######################
# Check Calibre Site #
######################
def check_calibre_site(site):
"""
Check the calibre site.
:param site: A dictionary containing information about the site.
It should have the following keys:
- "uuid" (str): The UUID of the site.
- "url" (str): The URL of the site.
:return: A dictionary containing the result of the check.
It has the following keys:
- "uuid" (str): The UUID of the site.
- "last_check" (str): The timestamp of the last check.
- "status" (str): The status of the site, which can be "unauthorized", "down", "online", or "Unknown Error".
- "last_online" (str): The timestamp of the last online status if the site is online.
- "error" (int): The HTTP status code if there is an error.
"""
logging.info("****Check Calibre Site Function****")
ret={}
ret['uuid']=site["uuid"]
now=str(datetime.datetime.now())
ret['last_check']=now
print ('URL = ', site['url'])
api=site['url']+'/ajax/'
timeout=15
library=""
url=api+'search'+library+'?num=0'
print()
print("Getting ebooks count:", site['url'])
logging.info("Getting ebooks count: %s", site['url'])
print(url)
logging.info("URL: %s", url)
try:
r=requests.get(url, verify=False, timeout=(timeout, 30))
r.raise_for_status()
except requests.exceptions.HTTPError as e:
r.status_code
logging.error("HTTP error: %s", r.status_code)
ret['error']=r.status_code
if (r.status_code == 401):
ret['status']="unauthorized"
logging.error("HTTP unauthorized")
else:
ret['status']="down"
logging.error("HTTP down")
return ret
except requests.RequestException as e:
print("Unable to open site:", url)
logging.error("Unable to open site: %s", url)
# print (getattr(e, 'message', repr(e)))
print (e)
ret['status']="down"
return ret
except Exception as e:
print ("Other issue:", e)
logging.error("Other issue: %s", e)
ret['status']='Unknown Error'
print (e)
return ret
except :
print("Wazza !!!!")
logging.error("Critical Error: %s", e)
ret['status']='Critical Error'
print (e)
return ret
try:
print("Total count=",r.json()["total_num"])
logging.info("Total count: %s", r.json()["total_num"])
except:
pass
status=ret['status']='online'
if status=="online":
ret['last_online']=now
return ret
######################
# Get UUID from Site #
######################
def get_site_uuid_from_url(db, url):
"""
Retrieve the site UUID from a given URL.
Args:
db (Database): The database connection.
url (str): The URL to extract the site UUID from.
Returns:
tuple or None: The row from the 'sites' table if a match is found, None otherwise.
"""
logging.info("****Get Site UUID from url Function****")
site=urlparse(url)
hostname=site.hostname
site=site._replace(path='')
url=urlunparse(site)
# print (url)
# print (hostname)
row=db.conn.execute(f"select * from sites where instr(hostnames, '{hostname}')").fetchone()
# print(row)
if row:
return row
##############################
# Get URL, hostname and Port #
##############################
def map_site_from_url(url):
"""
Generates a site map from a given URL.
Args:
url (str): The URL to generate the site map from.
country (str): The country the URL belongs to.
Returns:
dict: A dictionary containing the generated site map. The dictionary has the following keys:
- 'url' (str): The modified URL with the path removed.
- 'hostnames' (list): A list containing the hostname extracted from the URL.
- 'ports' (list): A list containing the port number extracted from the URL as a string.
"""
logging.info("****Map Site from URL Function****")
ret={}
print ('*******')
print ('URL = ', url)
print ('*******')
if len(url) > 30:
return ret
else:
site=urlparse(url)
print(site)
site=site._replace(path='')
logging.info("URL: %s", url)
ret['url']=urlunparse(site)
logging.info("Hostnames: %s", site.hostname)
ret['hostnames']=[site.hostname]
logging.info("Port: %s", site.port)
ret['ports']=[str(site.port)]
return ret
############################################################
# Import the URLS from the temp file and write to Database #
############################################################
def import_urls_from_file(filepath, dir=data_dir):
"""
Import URLs from a file and add them to a sites database.
Args:
filepath (str): The path to the file containing the URLs.
dir (str, optional): The directory where the sites database is located. Defaults to '.'.
Returns:
None
"""
#TODO skip malformed urls
#TODO use cache instead
logging.info("***Importing URLs from file Function*** %s", filepath)
db=init_sites_db(dir)
with open(filepath) as f:
for url in f.readlines():
url=url.rstrip()
# url='http://'+url
if get_site_uuid_from_url(db, url):
logging.info("'%s' already present", url)
print(f"'{url}'' already present")
continue
print(f"'{url}'' added")
logging.info("'%s' added", url)
save_site(db, map_site_from_url(url))
###################################
# Get list of libraries from site #
###################################
def get_libs_from_site(site):
"""
Retrieves libraries from a specified website.
Args:
site (str): The URL of the website to retrieve libraries from.
Returns:
list[str]: A list of libraries retrieved from the website.
Raises:
requests.RequestException: If there is an issue making the request to the website.
"""
logging.info("****Get Libs from site Function****")
server=site.rstrip('/')
api=server+'/ajax/'
timeout=30
print()
print("Server:", server)
logging.info("Server: %s", server)
url=api+'library-info'
print()
print("Getting libraries from", server)
logging.info("Getting libraries from: %s", server)
# print(url)
try:
r=requests.get(url, verify=False, timeout=(timeout, 30))
r.raise_for_status()
except requests.RequestException as e:
print("Unable to open site:", url)
logging.error("Unable to open site: %s", url)
# return
except Exception as e:
logging.error("Other issue: %s", e)
print ("Other issue:", e)
return
# pass
libraries = r.json()["library_map"].keys()
logging.info("Libraries: %s", libraries)
print("Libraries:", ", ".join(libraries))
return libraries
###################################
# Check the list of sites in file #
###################################
def check_calibre_list(dir=data_dir):
"""
Generates a comment for the given function body in a markdown code block with the correct language syntax.
Parameters:
dir (str): The directory to search for the sites database. Defaults to the current directory.
Returns:
None
"""
logging.info("****Check Calibre List Function****")
db=init_sites_db(dir)
sites=[]
for row in db["sites"].rows:
logging.info("Queueing: %s", row['url'])
print(f"Queueing:{row['url']}")
sites.append(row)
print(sites)
pool = Pool(100)
pool.map(lambda s: check_and_save_site (db, s), sites)
#################
# Get site UUID #
#################
# example of a fts search sqlite-utils index.db "select * from summary_fts where summary_fts match 'title:fre*'"
def get_site_db(uuid, data_dir):
"""
Retrieves the site database based on the given UUID and directory.
:param uuid: The UUID of the site.
:type uuid: int or str
:param dir: The directory where the site database is located.
:type dir: str
:return: The site database.
:rtype: Database
"""
logging.info("****Get Site DB Function****")
f_uuid=str(uuid)+".db"
logging.info(f_uuid)
print(f_uuid)
path = Path(dir) / str(f_uuid)
return Database(path)
############################
# Initialize Site Database #
############################
def init_site_db(site, _uuid="", dir=data_dir):
"""
Initializes a site database.
Parameters:
site (str): The URL of the site.
_uuid (str, optional): The UUID for the database. Defaults to an empty string.
dir (str, optional): The directory where the database will be created. Defaults to ".".
Returns:
Database: The initialized database.
"""
logging.info("****Init Site DB Function****")
if not _uuid:
s_uuid=str(uuid.uuid4())
else:
s_uuid=str(_uuid)
f_uuid=s_uuid+".db"
path = Path(dir) / f_uuid
db = Database(path)
if not "site" in db.table_names():
s=db["site"]
s.insert(
{
"uuid": s_uuid,
"urls": [site],
"version": "",
"major": 0,
"schema_version": 1,
}
, pk='uuid'
)
if not "ebooks" in db.table_names():
db["ebooks"].create({
"uuid": str,
"id": int,
"library": str, #TODO: manage libraries ids as integer to prevent library renam on remote site
"title": str,
"authors": str,
"series": str,
"series_index": int,
# "edition": int,
"language": str,
"desc": str,
"identifiers": str,
"tags": str,
"publisher": str, #Index Ebooks From Library Function
"pubdate": str,
"last_modified": str,
"timestamp": str,
"formats": str,
"cover": int,
# "epub": int,
# "mobi": int,
# "pdf": int,
# TODO: add the most common formats to avoid alter tables
}, pk="uuid")
if not "libraries" in db.table_names():
db["libraries"].create({
"id": int,
"names": str
}, pk="id")
# db.table("ebooks", pk="id")
# db.table("ebooks", pk="id", alter=True
return db
#################################
# Get Library URL from Database #
#################################
def get_format_url(db, book, format):
"""
Generate the URL for a specific book format.
Args:
db (dict): The database containing the site information.
book (dict): The book information.
format (str): The desired book format.
Returns:
str: The URL for the specified book format.
"""
logging.info("****Get Format URL Function****")
url = json.loads(list(db['site'].rows)[0]["urls"])[0]
library=book['library']
id_=str(book['id'])
f_url = url+"/get/"+format+"/"+id_+"/"+library
return f_url
############################
# Get Library Version Info #
############################
def get_desc_url(db, book):
"""
Generate the URL for the book description.
Parameters:
db (dict): The database containing the site information.
book (dict): The book object.
Returns:
str: The URL for the book description.
"""
logging.info("****Get Desc URL Function****")
url = json.loads(list(db['site'].rows)[0]["urls"])[0]
library=book['library']
id_=str(book['id'])
f_urls=[]
major= list(db['site'].rows)[0]["major"]
if major >= 3:
d_url =url+"#book_id="+id_+"&library_id="+library+"&panel=book_details"
else:
d_url =url+"/browse/book/"+id_
return d_url
###############################
# Write book info to Database #
###############################
def save_books_metadata_from_site(db, books):
"""
Saves the metadata of books from a website into the database.
Parameters:
- db (dict): The database object.
- books (list): A list of dictionaries containing the metadata of the books.
Returns:
- None
"""
logging.info("****Save Books Metadata From Site Function****")
uuid = list(db['site'].rows)[0]["uuid"]
# print(uuid)
ebooks_t=db["ebooks"]
# print([c[1] for c in ebooks_t.columns])
# for b in books:
# print(b['title'])
# ebooks_t.insert(b, alter=True)
# ebooks_t.insert_all(books, alter=True)
ebooks_t.insert_all(books, alter=True, pk='uuid', batch_size=1000)
# print([c[1] for c in ebooks_t.columns])
##########################################
# Update Status when book details loaded #
##########################################
def update_done_status(book):
"""
Update the status of a book based on its source.
Args:
book (dict): The book object containing the source information.
Returns:
None: This function does not return anything.
"""
logging.info("****Update Done Status Function****")
source=book['source']
if source['status']!='ignored':
if set(source['formats'].keys()) == set(book['formats']) & set(source['formats'].keys()):
book['source']['status']="done"
else:
book['source']['status']="todo"
################################
# Index the Site List Sequence #
################################
def index_site_list_seq(file):
"""
Reads a file line by line and calls the index_ebooks function on each line.
Parameters:
file (str): The path to the file to be read.
Returns:
None
"""
logging.info("****Index Site List Sequence Function****")
with open(file) as f:
for s in f.readlines():
# try:
# index_ebooks(s.rstrip())
# except:
# continue
index_ebooks(s.rstrip())
###################
# Index Site List #
###################
def index_site_list(file):
"""
Indexes a list of sites in parallel using a pool of worker processes.
Args:
file (str): The path to the file containing the list of sites.
Returns:
None
"""
logging.info("****Index Site List Function****")
pool = Pool(40)
with open(file) as f:
sites = f.readlines()
sites= [s.rstrip() for s in sites]
logging.info("Sites: "+str(sites))
print(sites)
pool.map(index_ebooks_except, sites)
##########################
# Index ebooks Exception #
##########################
#def index_ebooks_except(site):
# """
# Indexes ebooks for a given site, except when an error occurs.
# Args:
# site (str): The site to index ebooks for.
# Returns:
# None
# """
# logging.info("****Index ebooks Exception Function****")
# try:
# index_ebooks(site)
# except:
# print("Error on site")
# logging.error("Error on site: "+site)
################
# Index Ebooks #
################
def index_ebooks(site, library, start=0, stop=0, dir=data_dir, num=1000, force_refresh=False):
"""
Retrieves ebooks from a site and indexes them into a library.
Args:
site (str): The site from which to retrieve ebooks.
library (str, optional): The library in which to index the ebooks. Defaults to "".
start (int, optional): The starting index of ebooks to retrieve. Defaults to 0.
stop (int, optional): The ending index of ebooks to retrieve. Defaults to 0.
dir (str, optional): The directory in which to store the ebooks. Defaults to ".".
num (int, optional): The number of ebooks to retrieve. Defaults to 1000.
force_refresh (bool, optional): Whether to force a refresh of the ebooks. Defaults to False.
Returns:
None
"""
#TODO old calibres don't manage libraries. /ajax/library-info endpoint doesn't exist. It would be better to manage calibre version directly
logging.info("****Index Ebooks Function****")
libs=[]
try:
libs= get_libs_from_site(site)
except:
print("old lib")
logging.error("Error on site (Old Lib): "+site)
_uuid=str(uuid.uuid4())
print ('libs = ', libs)
if libs:
for lib in libs:
print ('lib', lib)
print('Index ebooks From Libary', site, ' ', _uuid, ' ', lib, ' ', start, ' ', stop)
index_ebooks_from_library(site=site, _uuid=_uuid, library=lib, start=start, stop=stop, dir=dir, num=num, force_refresh=force_refresh)
else:
print('Not lib')
index_ebooks_from_library(site=site, _uuid=_uuid, start=start, stop=stop, dir=dir, num=num, force_refresh=force_refresh)
#############################
# Index Ebooks from Library #
#############################
def index_ebooks_from_library(site, _uuid="", library="", start=0, stop=0, dir=data_dir, num=1000, force_refresh=False):
"""
Index ebooks from a library on a site.
Args:
site (str): The site to index the library from.
_uuid (str, optional): The UUID of the library. Defaults to "".
library (str, optional): The library name. Defaults to "".
start (int, optional): The starting index for indexing. Defaults to 0.
stop (int, optional): The stopping index for indexing. Defaults to 0.
dir (str, optional): The directory to save the indexed ebooks. Defaults to ".".
num (int, optional): The number of ebooks to index at a time. Defaults to 1000.
force_refresh (bool, optional): Whether to force refresh the metadata. Defaults to False.
Returns:
None
"""
logging.info("****Index Ebooks from Library Function****")
offset= 0 if not start else start-1
num=min(1000, num)
server=site.rstrip('/')
api=server+'/ajax/'
lib=library
library= '/'+library if library else library
timeout=15
print(f"\nIndexing library: {lib} from server: {server} ")
logging.info(f"Indexing library: {lib} from server: {server} ")
url=api+'search'+library+'?num=0'
print(f"\nGetting ebooks count of library: {lib} from server:{server} ")
logging.info(f"Getting ebooks count of library: {lib} from server:{server} ")
# print(url)
try:
r=requests.get(url, verify=False, timeout=(timeout, 30))
r.raise_for_status()
except requests.RequestException as e:
print("Unable to open site:", url)
logging.error("Unable to open site: "+url)
return
# pass
except Exception as e:
print ("Other issue:", e)
logging.error("Other issue: "+str(e))
return
# pass
except :
print("Wazza !!!!")
sys.exit(1)
total_num=int(r.json()["total_num"])
total_num= total_num if not stop else stop
print()
print(f"Total count={total_num} from {server}")
logging.info(f"Total count={total_num} from {server}")
# library=r.json()["base_url"].split('/')[-1]
# base_url=r.json()["base_url"]
# cache_db=init_cache_db(dir=dir)
# _uuid=get_uuid_from_url(cache_db)
print('Init database for site:', site )
db=init_site_db(site, _uuid=_uuid, dir=dir)
r_site = (list(db['site'].rows)[0])
print('r_site = ', r_site)
r_site['version']=r.headers['server']
print('Version =', r_site['version'])
r_site['major']=int(re.search('calibre.*', r.headers['server']).group(1))
print('Major = ',r_site['major'])
db["site"].upsert(r_site, pk='uuid')
print()
range=offset+1
while offset < total_num:
remaining_num = min(num, total_num - offset)
# print()
# print("Downloading ids: offset="+str(offset), "num="+str(remaining_num))
print ('\r {:180.180}'.format(f'Downloading ids: offset={str(offset)} count={str(remaining_num)} from {server}'), end='')
logging.info(f"Downloading ids: offset={str(offset)} count={str(remaining_num)} from {server}")
# url=server+base_url+'?num='+str(remaining_num)+'&offset='+str(offset)+'&sort=timestamp&sort_order=desc'
url=api+'search'+library+'?num='+str(remaining_num)+'&offset='+str(offset)+'&sort=timestamp&sort_order=desc'
# print("->", url)
try:
r=requests.get(url, verify=False, timeout=(timeout, 30))
r.raise_for_status()
except requests.RequestException as e:
print ("Connection issue:", e)
logging.error("Connection issue: "+str(e))
return
# pass
except Exception as e:
print ("Other issue:", e)
logging.error("Other issue: "+str(e))
return
# pass
except :
print ("Wazza !!!!")
logging.error("Wazza !!!!")
return
# print("Ids received from:"+str(offset), "to:"+str(offset+remaining_num-1))
# print()
# print("Downloading metadata from", str(offset+1), "to", str(offset+remaining_num))
print ('\r {:180.180}'.format(f'Downloading metadata from {str(offset+1)} to {str(offset+remaining_num)}/{total_num} from {server}'), end='')
logging.info("Downloading metadata from "+str(offset+1)+" to "+str(offset+remaining_num))
books_s=",".join(str(i) for i in r.json()['book_ids'])
url=api+'books'+library+'?ids='+books_s
# url=server+base_url+'/books?ids='+books_s
# print("->", url)
# print ('\r{:190.190}'.format(f'url= {url} ...'), end='')
try:
r=requests.get(url, verify=False, timeout=(60, 60))
r.raise_for_status()
except requests.RequestException as e:
print ("Connection issue:", e)
logging.error("Connection issue: "+str(e))
return
# pass
except Exception as e:
print ("Other issue:", e)
logging.error("Other issue: "+str(e))
return
# pass
except :
print ("Wazza !!!!")
logging.error("Wazza !!!!")
return
# print(len(r.json()), "received")
print ('\r {:180.180}'.format(f'{len(r.json())} received'), end='')
logging.info(f"{len(r.json())} received")
books=[]
for id, r_book in r.json().items():
uuid=r_book['uuid']
if not uuid:
print ("No uuid for ebook: ignored")
logging.info("No uuid for ebook: ignored")
continue
if r_book['authors']:
desc= f"({r_book['title']} / {r_book['authors'][0]})"
else:
desc= f"({r_book['title']})"
# print (f'\r--> {range}/{total_num} - {desc}', end='')
# print (f'\r{server}--> {range}/{total_num} - {desc}', end='')
print ('\r {:180.180} '.format(f'{range}/{total_num} ({server} : {uuid} --> {desc}'), end='')
logging.info(f"{range}/{total_num} ({server} : {uuid} --> {desc}")
if not force_refresh:
# print("Checking local metadata:", uuid)
try:
book = load_metadata(dir, uuid)
except:
print("Unable to get metadata from:", uuid)
logging.error("Unable to get metadata from: "+str(uuid))
range+=1
continue
if book:
print("Metadata already present for:", uuid)
logging.error("Metadata already present for: "+str(uuid))
range+=1
continue
if not r_book['formats']:
# print("No format found for {}".format(r_book['uuid']))
range+=1
continue
book={}
book['uuid']=r_book['uuid']
book['id']=id
book['library']=lib
# book['title']=r_book['title']
book['title']=unidecode.unidecode(r_book['title'])
# book['authors']=r_book['authors']
if r_book['authors']:
book['authors']=[unidecode.unidecode(s) for s in r_book['authors']]
# book['desc']=""
book['desc']=r_book['comments']
if r_book['series']:
book['series']=unidecode.unidecode(r_book['series'])
# book['series']=[unidecode.unidecode(s) for s in r_book['series']]
s_i=r_book['series_index']
if (s_i):
book['series_index']=int(s_i)
# book['edition']=0
book['identifiers']=r_book['identifiers']
# book['tags']=r_book['tags']
if r_book['tags']:
book['tags']=[unidecode.unidecode(s) for s in r_book['tags']]
book['publisher']=r_book['publisher']
# book['publisher']=unidecode.unidecode(r_book['publisher'])
book['pubdate']=r_book['pubdate']
if not r_book['languages']:
# if True:
text=r_book['title']+". "
if r_book['comments']:
text=r_book['comments']
s_language, prob=identifier.classify(text)
if prob >= 0.85:
language = iso639.to_iso639_2(s_language)
book['language']=language
else:
book['language']=''
else:
book['language']=iso639.to_iso639_2(r_book['languages'][0])
if r_book['cover']:
book['cover']= True
else:
book['cover']= False
book['last_modified']=r_book['last_modified']
book['timestamp']=r_book['timestamp']
book['formats']=[]
formats=r_book['formats']
for f in formats:
if 'size' in r_book['format_metadata'][f]:
size=int(r_book['format_metadata'][f]['size'])
else:
# print()
# print(f"Size not found for format '{f}' uuid={uuid}: skipped")
pass
#TODO query the size when the function to rebuild the full url is ready
#
# print("Trying to get size online: {}".format('url'))
# try:
# size=get_file_size(s['url'])
# except:
# print("Unable to access size for format '{}' : {} skipped".format(f, uuid))
# continue
book[f]=(size)
book['formats'].append(f)
if not book['formats']:
# if not c_format:
# print()
# print(f"No format found for {book['uuid']} id={book['id']} : skipped")
range+=1
# continue
books.append(book)
range+=1
# print()
print("Saving metadata")
print ('\r {:180.180}'.format(f'Saving metadata from {server}'), end='')
logging.info("Saving metadata from %s", server)
try:
save_books_metadata_from_site(db, books)
print('\r {:180.180}'.format(f'--> Saved {range-1}/{total_num} ebooks from {server}'), end='')
logging.info("Saved %s/%s ebooks from %s", range-1, total_num, server)
except BaseException as err:
print (err)
logging.error(err)
print()
print()
# try:
# save_metadata(db, books)
# except:
# print("Unable to save book metadata")
offset=offset+num
############################
# Query EBooks in Database #
############################
def query(query_str="", dir=data_dir):
"""
Generates a function comment for the given function body in a markdown code block with the correct language syntax.
Parameters:
- query_str (str): The query string to be used in the function.
- dir (str): The directory to search for files. Default is the current directory.
Returns:
- None
"""