-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhn.py
2012 lines (1708 loc) · 74.8 KB
/
hn.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 base64
import concurrent.futures
import json
import logging
import os
import pickle
import re
import time
import traceback
import warnings
from urllib.parse import urlparse
from bs4 import BeautifulSoup, XMLParsedAsHTMLWarning
import config
import social_media
import thnr_scrapers
import thumbs
import utils_aws
import utils_file
import utils_hash
import utils_http
import utils_mimetypes_magic
import utils_random
import utils_text
import utils_time
from PageOfStories import PageOfStories
from Story import Story
from thnr_exceptions import UnsupportedStoryType
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# quiet bs4since it's chatty
warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
badge_codes = {
"top": {"letter": "T", "sigil": "Ⓣ", "tooltip": "news"},
"new": {"letter": "N", "sigil": "Ⓝ", "tooltip": "newest"},
"best": {"letter": "B", "sigil": "Ⓑ", "tooltip": "best"},
"active": {"letter": "A", "sigil": "Ⓐ", "tooltip": "active"},
"classic": {"letter": "C", "sigil": "Ⓒ", "tooltip": "classic"},
}
skip_getting_content_type_via_head_request_for_domains = {
"twitter.com",
"bloomberg.com",
}
log_levels_to_funcs = {
logging.INFO: logging.info,
logging.WARNING: logging.warning,
logging.ERROR: logging.error,
}
def generic_exception_handler(
exc: Exception = None,
include_tb: bool = False,
log_detail: str = "",
log_level: int = logging.INFO,
log_prefix: str = "",
postscript: str = "",
raise_after: bool = False,
) -> None:
log_prefix_local = log_prefix + "generic_exception_handler: "
if log_detail:
log_detail += ": "
if postscript:
postscript = " " + postscript
log_func = log_levels_to_funcs[log_level]
exc_module = exc.__class__.__module__
exc_name = exc.__class__.__name__
fq_exc_name = exc_module + "." + exc_name
exc_msg = str(exc)
exc_slug = fq_exc_name + ": " + exc_msg
log_func(log_prefix_local + log_detail + exc_slug + postscript)
if include_tb:
tb_str = traceback.format_exc()
log_func(log_prefix_local + tb_str)
if raise_after:
raise exc
def asdfft1(item_id=None, pos_on_page=None):
log_prefix_id = f"id={item_id}: "
log_prefix_local = log_prefix_id + "asdfft1: "
# try:
# asdfft2(item_id, pos_on_page)
# except Exception as exc:
# if isinstance(exc, UnsupportedStoryType):
# pass
# else:
# exc_name = exc.__class__.__name__
# exc_msg = str(exc)
# exc_slug = f"{exc_name}: {exc_msg}"
# logger.info(
# log_prefix_id + "asdfft2: " + "unexpected exception: " + exc_slug
# )
# tb_str = traceback.format_exc()
# logger.info(log_prefix_id + "asdfft2: " + tb_str)
story_as_dict = None
try:
story_as_dict = query_firebaseio_for_story_data(item_id=item_id)
except Exception as exc:
exc_short_name = exc.__class__.__name__
exc_name = exc.__class__.__module__ + "." + exc_short_name
exc_msg = str(exc)
exc_slug = exc_name + ": " + exc_msg
logger.info(log_prefix_local + exc_slug)
raise exc
if not story_as_dict:
logger.info(
log_prefix_local + "failed to receive story details from firebaseio.com"
)
raise Exception(
log_prefix_local + "failed to receive story details from firebaseio.com"
)
elif story_as_dict["type"] not in ["story", "job"]:
# TODO: eventually handle poll, etc. other types
logger.info(log_prefix_local + f"ignoring item of type {story_as_dict['type']}")
raise UnsupportedStoryType(story_as_dict["type"])
story_object = item_factory(story_as_dict)
if not story_object:
raise Exception(
log_prefix_local + "item_factory: failed to create story object"
)
story_object.time_of_last_firebaseio_query = (
utils_time.get_time_now_in_epoch_seconds_int()
)
if story_object.has_outbound_url:
# get srct
domain, domain_minus_www = utils_text.get_domains_from_url(story_object.url)
if domain in skip_getting_content_type_via_head_request_for_domains:
logger.info(log_prefix_local + f"skip HEAD request for {domain}")
elif domain_minus_www in skip_getting_content_type_via_head_request_for_domains:
logger.info(log_prefix_local + f"skip HEAD request for {domain_minus_www}")
else:
story_object.linked_url_reported_content_type = (
utils_http.get_content_type_via_head_request(
url=story_object.url, log_prefix=log_prefix_local
)
)
if (
story_object.linked_url_reported_content_type
and "," in story_object.linked_url_reported_content_type
):
types = set(
[
x.strip()
for x in story_object.linked_url_reported_content_type.split(",")
]
)
if len(types) == 1:
story_object.linked_url_reported_content_type = types.pop()
else:
logger.info(
log_prefix_local
+ "srct has multiple values: "
+ story_object.linked_url_reported_content_type
+ " ~Tim~"
)
if "text/html" in types:
story_object.linked_url_reported_content_type = "text/html"
else:
story_object.linked_url_reported_content_type = None
if (
story_object.linked_url_reported_content_type == "text/html"
or story_object.linked_url_reported_content_type == "application/xhtml+xml"
or not story_object.linked_url_reported_content_type
):
page_source = None
soup = None
page_source = utils_http.get_page_source(
url=story_object.url,
log_prefix=log_prefix_local,
)
if page_source:
if (
story_object.linked_url_reported_content_type
== "application/xhtml+xml"
):
logger.info(log_prefix_local + "using 'lxml-xml' parser")
parser_to_use = "lxml-xml"
else:
parser_to_use = "lxml"
try:
soup = BeautifulSoup(page_source, parser_to_use)
except Exception as exc:
generic_exception_handler(
exc=exc,
include_tb=True,
log_detail=f"unexpected problem making soup from {story_object.url}",
log_prefix=log_prefix_local,
postscript="~Tim~",
)
if not page_source or not soup:
return story_object
# invariant now: we have page_source and soup
# check for og:image
og_image_url_result = soup.find("meta", {"property": "og:image"})
if og_image_url_result:
if og_image_url_result.has_attr("content"):
meta_og_image_content = og_image_url_result["content"]
if meta_og_image_content.startswith("data:"):
# content="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeUAAACeEAIAAADTU..."
first_128 = meta_og_image_content[:128]
logger.info(
log_prefix_local
+ f"found og:image inline data: '{first_128}...'"
)
match = re.match(
r"^data: *([a-z]+/[a-z\-\+]+) *; *", meta_og_image_content
)
if match:
story_object.og_image_inline_data_srct = match.group(1)
len_match = len(match.group())
meta_og_image_content = meta_og_image_content[len_match:]
if meta_og_image_content.startswith("base64"):
match = re.match(r"^base64 *[;,] *")
if match:
len_match = len(match.group())
meta_og_image_content = meta_og_image_content[
len_match:
]
# using base64, convert meta_og_image_content to binary data and save to a temp file
local_file_with_og_image_inline_data_decoded = (
config.settings["TEMP_DIR"]
+ f"og-image-via-inline-data-{story_object.id}"
)
binary_data = base64.b64decode(
meta_og_image_content
)
with open(
local_file_with_og_image_inline_data_decoded,
"wb",
) as file:
file.write(binary_data)
story_object.og_image_is_inline_data = True
story_object.has_thumb = True # provisionally
logger.info(
log_prefix_local
+ f"saved og:image base64 inline data to {local_file_with_og_image_inline_data_decoded} url={story_object.url} ~Tim~"
)
story_object.og_image_inline_data_decoded_local_path = (
local_file_with_og_image_inline_data_decoded
)
else:
story_object.og_image_url = og_image_url_result["content"]
logger.info(
log_prefix_local
+ f"found og:image url {story_object.og_image_url}"
)
else:
story_object.has_thumb = False
# TODO: in the absence of an og:image, I could always fall back on a generic banner image for the linked article's website
# get reading time
try:
reading_time = utils_text.get_reading_time(
page_source=page_source, log_prefix=log_prefix_id
)
if reading_time:
story_object.reading_time = reading_time
except Exception as exc:
short_exc_name = exc.__class__.__name__
exc_name = exc.__class__.__module__ + "." + short_exc_name
exc_msg = str(exc)
exc_slug = f"{exc_name}: {exc_msg}"
logger.error(
log_prefix_id
+ "get_reading_time: unexpected exception: "
+ exc_slug
)
tb_str = traceback.format_exc()
logger.error(log_prefix_id + tb_str)
## create a slug for the linked URL's social-media website channel, if necessary.
## use details encoded in the url or the html page source
## https://hackernews-insight.vercel.app/domain-analysis
try:
social_media.check_for_social_media_details(
# driver=driver,
story_object=story_object,
page_source_soup=soup,
)
except Exception as exc:
logger.error(
log_prefix_local + f"check_for_social_media_details: {exc}"
)
raise exc
elif story_object.linked_url_reported_content_type.startswith("image/"):
story_object.og_image_url = story_object.url
elif story_object.linked_url_reported_content_type == "text/plain":
# logger.info(
# log_prefix_local
# + f"creating minimal story card for story '{story_object.title}' at url {story_object.url} because its content-type is text/plain"
# )
# create story card with what we have
populate_story_card_html_in_story_object(story_object)
# pickle `story_object` as json to a file
logger.info(log_prefix_local + "saving item to disk for the first time")
save_story_object_to_disk(
story_object=story_object, log_prefix=log_prefix_local
)
story_object.has_thumb = False
return story_object
# if story links to PDF, we'll use 1st page of PDF as thumb instead of og:image (if any)
elif (
story_object.linked_url_reported_content_type == "application/pdf"
or story_object.linked_url_reported_content_type
== "application/octet-stream"
):
story_object.og_image_url = story_object.url
else:
logger.info(
log_prefix_local
+ f"unexpected srct '{story_object.linked_url_reported_content_type}' for url {story_object.url}"
)
if story_object.og_image_url or story_object.og_image_is_inline_data:
if story_object.og_image_url and thumbs.image_url_is_disqualified(
url=story_object.og_image_url, log_prefix=log_prefix_local
):
story_object.has_thumb = False
else:
d_og_image_res = thnr_scrapers.download_og_image1(story_object)
if story_object.og_image_url and d_og_image_res:
story_object.has_thumb = True # provisionally
elif not d_og_image_res:
logger.info(log_prefix_local + "failed to download_og_image()")
story_object.has_thumb = False
else:
logger.error(
log_prefix_local + "unexpected result from download_og_image()"
)
story_object.has_thumb = False
if story_object.has_thumb:
if pos_on_page < 5:
img_loading_attr = "eager"
else:
img_loading_attr = "lazy"
thumbs.populate_image_slug_in_story_object(
story_object, img_loading=img_loading_attr
)
if story_object.has_thumb:
story_object.image_slug = thumbs.create_img_slug_html(
story_object, img_loading=img_loading_attr
)
if not story_object.image_slug:
story_object.has_thumb = False
if story_object.has_thumb and story_object.image_slug:
logger.info(log_prefix_local + "story card will have a thumbnail")
if story_object.has_thumb and not story_object.image_slug:
logger.error(
log_prefix_local
+ "has_thumb is True, but there's no image_slug, so updating as_thumb to False ~Tim~"
)
story_object.has_thumb = False
# apply "[pdf]" label after title if it's not there but is probably applicable
if (
story_object.downloaded_og_image_magic_result
and story_object.downloaded_og_image_magic_result == "application/pdf"
):
if "pdf" not in story_object.title[-12:].lower():
story_object.story_content_type_slug = (
' <span class="story-content-type">[pdf]</span>'
)
logger.info(f"id={story_object.id}: added [pdf] label after title")
return story_object
def asdfft2_preprocess_outbound_link(story_object, log_prefix: str) -> None:
log_prefix_local = log_prefix + "asdfft2_preprocess_outbound_link: "
parsed_url = urlparse(story_object.url)
if (
parsed_url.netloc.endswith("dropbox.com")
and parsed_url.path.endswith(".pdf")
and "dl=0" in parsed_url.query
):
story_object.url = parsed_url._replace(query="dl=1").geturl()
logger.info(
log_prefix_local
+ f"changing url from {story_object.url} to {story_object.url}"
)
return
generic_binary_mimetypes = set(
[
"application/octet-stream",
"application/data",
"application/binary",
"binary/octet",
]
)
def asdfft2(item_id=None, pos_on_page=None):
log_prefix_id = f"id={item_id}: "
log_prefix_local = log_prefix_id + "asdfft2: "
# short delay since asdfft1() and asdfft2() are called in sequence and scrape the same page
time.sleep(utils_random.random_real(0.5, 1.5))
story_as_dict = None
try:
story_as_dict = query_firebaseio_for_story_data(item_id=item_id)
except Exception as exc:
generic_exception_handler(
exc=exc,
include_tb=True,
log_detail="unexpected problem querying firebaseio",
log_prefix=log_prefix_local,
raise_after=True,
)
if not story_as_dict:
logger.info(
log_prefix_local + "failed to receive story details from firebaseio.com"
)
raise Exception("failed to receive story details from firebaseio.com")
elif story_as_dict["type"] not in ["story", "job", "comment"]:
# TODO: eventually handle poll, job, etc. other types
logger.info(
log_prefix_local
+ f"not processing item of item type {story_as_dict['type']}"
)
raise UnsupportedStoryType(story_as_dict["type"])
story_object = item_factory(story_as_dict)
if not story_object:
# we have to give up
err_msg = "item_factory: failed to create story object"
logger.error(log_prefix_local + err_msg)
raise Exception(log_prefix_local + err_msg)
story_object.time_of_last_firebaseio_query = (
utils_time.get_time_now_in_epoch_seconds_int()
)
if not story_object.has_outbound_url:
# probably an Ask HN, etc.
logger.info(log_prefix_local + "story has no outbound url")
return story_object
# invariant now: story_object.has_outbound_url == True
# do some processing of the outbound link in some cases
# TODO: extract this url processing logic to its own function
parsed_url = urlparse(story_object.url)
# dropbox.com
if (
parsed_url.netloc.endswith("dropbox.com")
and parsed_url.path.endswith(".pdf")
and "dl=0" in parsed_url.query
):
new_url = parsed_url._replace(query="dl=1").geturl()
logger.info(
log_prefix_local + f"changing url from {story_object.url} to {new_url}"
)
story_object.url = new_url
parsed_url = urlparse(story_object.url)
response_objects = {}
for each_gro_func in [
utils_http.get_response_object_via_requests,
utils_http.get_response_object_via_hrequests,
]:
time.sleep(utils_random.random_real(0, 1))
ro = each_gro_func(url=story_object.url, log_prefix=log_prefix_local)
if ro:
response_objects[each_gro_func.__name__] = ro
else:
logger.info(
log_prefix_local
+ f"failed to get response object via {each_gro_func.__name__}"
)
if not response_objects:
logger.info(
log_prefix_local
+ f"failed to get any response objects for url {story_object.url} ~Tim~"
)
# create story card with what little we have
story_object.has_thumb = False
populate_story_card_html_in_story_object(story_object)
logger.info(log_prefix_local + "saving item to disk for the first time")
save_story_object_to_disk(
story_object=story_object, log_prefix=log_prefix_local
)
return story_object
# invariant now: we have at least one response object
# let's download the content and determine its content type
local_file_with_response_content_prefix = config.settings["TEMP_DIR"] + str(
story_object.id
)
for k, v in response_objects.items():
utils_file.save_response_content_to_disk(
response=v,
dest_local_file=local_file_with_response_content_prefix + "-" + k[4:],
log_prefix=log_prefix_local,
)
# prefer the response object from requests, because the object from hrequests sometimes handles binary files as utf-8 strings
if "get_response_object_via_requests" in response_objects:
local_file_with_response_content = (
local_file_with_response_content_prefix + "-response_object_via_requests"
)
else:
# TODO: we REALLY REALLY don't want to use hrequest's ro, because it sometimes handles binary files as utf-8 strings
# TODO: use curl or something as a fallback to get the content, in order to avoid using the hrequests ro
# TODO: or maybe wait 30 seconds and try again to get the content via requests
local_file_with_response_content = (
local_file_with_response_content_prefix + "-response_object_via_hrequests"
)
textual_mimetype, page_source, is_wellformed_xml = (
utils_mimetypes_magic.get_textual_mimetype(
local_file=local_file_with_response_content,
log_prefix=log_prefix_local,
context={"url": story_object.url},
)
)
if textual_mimetype:
content_type_to_use = textual_mimetype
story_object.is_wellformed_xml = is_wellformed_xml
else: # textual_mimetype is None
# must be binary, so figure out what kind of binary
# get magic type of the file
mimetype_via_python_magic = utils_mimetypes_magic.get_mimetype_via_python_magic(
local_file=local_file_with_response_content,
log_prefix=log_prefix_local,
)
mimetype_via_file_command = utils_mimetypes_magic.get_mimetype_via_file_command(
local_file=local_file_with_response_content,
log_prefix=log_prefix_local,
)
mimetype_via_exiftool = utils_mimetypes_magic.get_mimetype_via_exiftool2(
local_file=local_file_with_response_content,
log_prefix=log_prefix_local,
)
content_types_guessed_from_uri_extension = (
utils_mimetypes_magic.guess_mimetype_from_uri_extension(
url=story_object.url,
log_prefix=log_prefix_local,
context={"url": story_object.url},
)
)
possible_magic_types = []
if mimetype_via_python_magic:
possible_magic_types.append(mimetype_via_python_magic)
if mimetype_via_file_command:
possible_magic_types.append(mimetype_via_file_command)
if mimetype_via_exiftool:
if isinstance(type(mimetype_via_exiftool), str ):
possible_magic_types.append(mimetype_via_exiftool)
else:
logger.info(
log_prefix_local
+ f"{mimetype_via_exiftool=}, type(mimetype_via_exiftool)={type(mimetype_via_exiftool)} ~Tim~"
)
srct = set(
x
for x in [
get_content_type_from_response(
response=v,
log_prefix=log_prefix_local,
context={
"url": story_object.url,
"response_object_creator": k,
},
)
for (k, v) in response_objects.items()
]
if x
)
if not srct:
logger.info(
log_prefix_local
+ f"failed to get any srct for url={story_object.url} ~Tim~"
)
srct = None
elif len(srct) == 1:
srct = srct.pop()
elif len(srct) > 1:
logger.info(
log_prefix_local
+ f"multiple srct values: {srct} for url={story_object.url} ~Tim~"
)
srct = srct.pop()
all_values = set()
all_values.update(content_types_guessed_from_uri_extension)
all_values.update(possible_magic_types)
if textual_mimetype:
all_values.add(textual_mimetype)
trusted_values = set(
[
mimetype_via_python_magic,
mimetype_via_file_command,
mimetype_via_exiftool,
]
)
if srct:
url_slug = f"for url {story_object.url}"
all_values.add(srct)
content_type_to_use = None
# 1. If all_values has length 1 and this value matches srct, use that:
if len(all_values) == 1 and srct in all_values:
content_type_to_use = srct
logger.info(
log_prefix_local
+ f"{srct=} equals {all_values=} ; {content_type_to_use=} {url_slug}"
)
# 2. If srct is a generic binary mimetype and mimetype_via_python_magic, mimetype_via_file_command, mimetype_via_exiftool all agree, use that:
elif srct in generic_binary_mimetypes:
if len(trusted_values) == 1:
content_type_to_use = trusted_values.pop()
logger.info(
log_prefix_local
+ f"generic {srct=}, but {trusted_values=} ; {content_type_to_use=} {url_slug} ~Tim~"
)
# 3. If srct, mimetype_via_python_magic, mimetype_via_file_command, mimetype_via_exiftool all agree, use that:
elif len(trusted_values) == 1 and srct in trusted_values:
content_type_to_use = srct
logger.info(
log_prefix_local
+ f"{srct=} equals {trusted_values=} ; {content_type_to_use=} {url_slug} ~Tim~"
)
# 4. If srct matches any value in trusted_values, use that:
elif srct in trusted_values:
content_type_to_use = srct
logger.info(
log_prefix_local
+ f"{srct=} matches any of {trusted_values=} ; {content_type_to_use=} {url_slug} ~Tim~"
)
# 5. If srct matches any value in all_values, use that:
elif srct in all_values:
content_type_to_use = srct
logger.info(
log_prefix_local
+ f"{srct=} matches any of {all_values=} ; {content_type_to_use=} {url_slug} ~Tim~"
)
# 6. Just use srct
else:
content_type_to_use = srct
logger.info(
log_prefix_local
+ f"{srct=} instead of {all_values=} ; {content_type_to_use=} {url_slug} ~Tim~"
)
else: # srct is None
# 7. If mimetype_via_python_magic, mimetype_via_file_command, mimetype_via_exiftool all agree, use that:
if len(trusted_values) == 1:
content_type_to_use = trusted_values.pop()
logger.info(
log_prefix_local
+ f"srct=None, but {trusted_values=} ; {content_type_to_use=} {url_slug} ~Tim~"
)
# 8. Fall back on generic 'application/octet-stream'
else:
content_type_to_use = "application/octet-stream"
logger.info(
log_prefix_local
+ f"srct=None, and {all_values=} disagree ; {content_type_to_use=} {url_slug} ~Tim~"
)
# dismiss some very common mimetypes as not interesting
uninteresting_mimetypes = [
"application/pdf",
"application/xhtml+xml",
"text/html",
]
copy_of_all_values = set(all_values)
for each in uninteresting_mimetypes:
copy_of_all_values.discard(each)
is_interesting = True
if not copy_of_all_values:
is_interesting = False
if is_interesting:
copy_of_all_values = list(copy_of_all_values)
copy_of_all_values.sort()
logger.info(
log_prefix_local
+ f"interesting mimetypes from all_values={copy_of_all_values} for url {story_object.url}"
)
# invariant now: content_type_to_use != None
# try make soup from page_source
if page_source and content_type_to_use in ["text/html", "application/xhtml+xml"]:
if content_type_to_use.endswith("xml") and story_object.is_wellformed_xml:
parser_to_use = "lxml-xml"
else:
parser_to_use = "lxml"
try:
soup = BeautifulSoup(page_source, parser_to_use)
except Exception as exc:
generic_exception_handler(
exc=exc,
include_tb=True,
log_detail=f"unexpected problem making soup from {story_object.url}",
log_prefix=log_prefix_local,
postscript="~Tim~",
)
if not soup:
return story_object
# check for og:image
og_image_url_result = soup.find("meta", {"property": "og:image"})
if og_image_url_result:
if og_image_url_result.has_attr("content"):
meta_og_image_content = og_image_url_result["content"]
if meta_og_image_content.startswith("data:"):
# Example:
# <meta property="og:image" content="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeUAAACeEAIAAADTU...">
first_128 = meta_og_image_content[:128]
logger.info(
log_prefix_local
+ f"found og:image inline data: '{first_128}...'"
)
match = re.match(
r"^data: *([a-z]+/[a-z\-\+]+) *; *", meta_og_image_content
)
if match:
story_object.og_image_inline_data_srct = match.group(1)
len_match = len(match.group())
meta_og_image_content = meta_og_image_content[len_match:]
if meta_og_image_content.startswith("base64"):
match = re.match(r"^base64 *[;,] *")
if match:
len_match = len(match.group())
meta_og_image_content = meta_og_image_content[
len_match:
]
# using base64, convert meta_og_image_content to binary data and save to a temp file
local_file_with_og_image_inline_data_decoded = (
config.settings["TEMP_DIR"]
+ f"og-image-via-inline-data-{story_object.id}"
)
binary_data = base64.b64decode(meta_og_image_content)
with open(
local_file_with_og_image_inline_data_decoded,
"wb",
) as file:
file.write(binary_data)
story_object.og_image_is_inline_data = True
story_object.has_thumb = True # provisionally
logger.info(
log_prefix_local
+ f"saved og:image base64 inline data to {local_file_with_og_image_inline_data_decoded} url={story_object.url} ~Tim~"
)
story_object.og_image_inline_data_decoded_local_path = (
local_file_with_og_image_inline_data_decoded
)
else:
# Example:
# <meta property="og:image" content="https://www.esa.int/var/esa/storage/images/esa_multimedia/images/2024/03/webb_hubble_confirm_universe_s_expansion_rate/25971194-1-eng-GB/Webb_Hubble_confirm_Universe_s_expansion_rate_pillars.jpg">
story_object.og_image_url = og_image_url_result["content"]
logger.info(
log_prefix_local
+ f"found og:image url {story_object.og_image_url}"
)
story_object.has_thumb = True # provisionally
else:
story_object.has_thumb = False
# TODO: in the absence of an og:image, I could always fall back on a generic screenshot of the linked article's website
# get reading time via goose
try:
reading_time = utils_text.get_reading_time(
page_source=page_source, log_prefix=log_prefix_id
)
if reading_time:
story_object.reading_time = reading_time
except Exception as exc:
generic_exception_handler(
exc=exc,
include_tb=True,
log_detail="unexpected problem getting reading time",
log_prefix=log_prefix_local,
postscript="~Tim~",
)
# if domain matches social media sites, check for those details
try:
social_media.check_for_social_media_details(
# driver=driver,
story_object=story_object,
page_source_soup=soup,
)
except Exception as exc:
generic_exception_handler(
exc=exc,
include_tb=True,
log_detail="unexpected problem getting social media details",
log_prefix=log_prefix_local,
postscript="~Tim~",
raise_after=True,
)
elif content_type_to_use == "application/pdf":
# use the first page of the PDF as a thumbnail, with dog ear etc.
story_object.og_image_url = story_object.url
# apply "[pdf]" label after title if it's not there but is probably applicable
if "pdf" not in story_object.title[-12:].lower():
story_object.story_content_type_slug = (
' <span class="story-content-type">[pdf]</span>'
)
logger.info(log_prefix_local + "added [pdf] label after title")
elif content_type_to_use.startswith("image/"):
# use the image at the uri as the thumbnail
story_object.og_image_url = story_object.url
elif content_type_to_use.startswith("video/"):
pass
# TODO: extract a frame as a screenshot, OR, even better, extract 12 frames and arrange them in a 4x3 grid: 2024-02-13T15:15:56Z [new] INFO id 39358138: asdfft1(): unexpected linked url content-type video/mp4 for url https://www.goody2.ai/video/goody2-169.mp4
if story_object.og_image_url or story_object.og_image_is_inline_data:
if story_object.og_image_is_inline_data:
# TODO: implement this
story_object.has_thumb = False # since this is a stub
# if story_object.has_thumb:
# if pos_on_page < 5:
# img_loading_attr = "eager"
# else:
# img_loading_attr = "lazy"
# thumbs.populate_image_slug_in_story_object(
# story_object, img_loading=img_loading_attr
# )
# if story_object.has_thumb:
# story_object.image_slug = thumbs.create_img_slug_html(
# story_object, img_loading=img_loading_attr
# )
# if not story_object.image_slug:
# story_object.has_thumb = False
elif story_object.og_image_url and thumbs.image_url_is_disqualified(
url=story_object.og_image_url, log_prefix=log_prefix_local
):
story_object.has_thumb = False
# TODO: the logic around this area can be improved
if story_object.og_image_url and story_object.has_thumb:
d_og_image_res = thnr_scrapers.download_og_image1(story_object)
if story_object.og_image_url and d_og_image_res:
story_object.has_thumb = True # provisionally
elif not d_og_image_res:
logger.info(log_prefix_local + "failed to download_og_image()")
story_object.has_thumb = False
else:
logger.error(
log_prefix_local + "unexpected result from download_og_image()"
)
story_object.has_thumb = False
if story_object.has_thumb:
if pos_on_page < 5:
img_loading_attr = "eager"
else:
img_loading_attr = "lazy"
thumbs.populate_image_slug_in_story_object(
story_object, img_loading=img_loading_attr
)
if story_object.has_thumb:
story_object.image_slug = thumbs.create_img_slug_html(
story_object, img_loading=img_loading_attr
)
if not story_object.image_slug:
story_object.has_thumb = False
if story_object.has_thumb and story_object.image_slug:
logger.info(log_prefix_local + "story card will have a thumbnail")
if story_object.has_thumb and not story_object.image_slug:
logger.error(
log_prefix_local
+ "has_thumb is True, but there's no image_slug, so updating as_thumb to False ~Tim~"
)
story_object.has_thumb = False
if not story_object.has_thumb:
logger.info(log_prefix_local + "story card will not have a thumbnail")
# return story_object
return story_object
def choose_best_page_source(
page_source_via_get, page_source_via_render, url, log_prefix=""
):
log_prefix_local = log_prefix + "choose_best_page_source: "
empty_page_source = "<html><head></head><body></body></html>"
if page_source_via_get:
if page_source_via_get == empty_page_source: