-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
content.py
2411 lines (2210 loc) · 82.6 KB
/
content.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
__filename__ = "content.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "1.5.0"
__maintainer__ = "Bob Mottram"
__email__ = "[email protected]"
__status__ = "Production"
__module_group__ = "Core"
import difflib
import math
import html
import os
import email.parser
import urllib.parse
from shutil import copyfile
from dateutil.parser import parse
from flags import is_pgp_encrypted
from flags import contains_pgp_public_key
from flags import is_float
from flags import is_right_to_left_text
from utils import replace_strings
from utils import data_dir
from utils import remove_link_tracking
from utils import string_contains
from utils import string_ends_with
from utils import is_account_dir
from utils import get_url_from_post
from utils import language_right_to_left
from utils import binary_is_image
from utils import get_content_from_post
from utils import get_full_domain
from utils import get_user_paths
from utils import convert_published_to_local_timezone
from utils import has_object_dict
from utils import valid_hash_tag
from utils import dangerous_svg
from utils import remove_domain_port
from utils import get_image_extensions
from utils import load_json
from utils import save_json
from utils import file_last_modified
from utils import get_link_prefixes
from utils import dangerous_markup
from utils import acct_dir
from utils import get_currencies
from utils import remove_html
from utils import remove_eol
from petnames import get_pet_name
from session import download_image
MUSIC_SITES = ('soundcloud.com', 'bandcamp.com', 'resonate.coop')
MAX_LINK_LENGTH = 40
REMOVE_MARKUP = (
'b', 'i', 'ul', 'ol', 'li', 'em', 'strong',
'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5'
)
INVALID_CONTENT_STRINGS = (
'mute', 'unmute', 'editeventpost', 'notifypost',
'delete', 'options', 'page', 'repeat',
'bm', 'tl', 'actor', 'unrepeat', 'eventid',
'unannounce', 'like', 'unlike', 'bookmark',
'unbookmark', 'likedBy', 'time',
'year', 'month', 'day', 'editnewpost',
'graph', 'showshare', 'category', 'showwanted',
'rmshare', 'rmwanted', 'repeatprivate',
'unrepeatprivate', 'replyto',
'replyfollowers', 'replydm', 'replychat', 'editblogpost',
'handle', 'blockdomain'
)
def valid_url_lengths(content: str, max_url_length: int) -> bool:
"""Returns true if the given content contains urls which are too long
"""
if '://' not in content:
return True
sections = content.split('://')
ctr = 0
for text in sections:
if ctr == 0:
ctr += 1
continue
if '"' not in text:
continue
url = text.split('"')[0]
if '<' not in url and '>' not in url:
if len(url) > max_url_length:
return False
return True
def remove_html_tag(html_str: str, tag: str) -> str:
"""Removes a given tag from a html string
"""
tag_found = True
while tag_found:
match_str = ' ' + tag + '="'
if match_str not in html_str:
tag_found = False
break
sections = html_str.split(match_str, 1)
if '"' not in sections[1]:
tag_found = False
break
html_str = sections[0] + sections[1].split('"', 1)[1]
return html_str
def _remove_quotes_within_quotes(content: str) -> str:
"""Removes any blockquote inside blockquote
"""
if '<blockquote>' not in content:
return content
if '</blockquote>' not in content:
return content
ctr = 1
found = True
while found:
prefix = content.split('<blockquote>', ctr)[0] + '<blockquote>'
quoted_str = content.split('<blockquote>', ctr)[1]
if '</blockquote>' not in quoted_str:
found = False
continue
end_str = quoted_str.split('</blockquote>')[1]
quoted_str = quoted_str.split('</blockquote>')[0]
if '<blockquote>' not in end_str:
found = False
if '<blockquote>' in quoted_str:
quoted_str = quoted_str.replace('<blockquote>', '')
content = prefix + quoted_str + '</blockquote>' + end_str
ctr += 1
return content
def html_replace_email_quote(content: str) -> str:
"""Replaces an email style quote "> Some quote" with html blockquote
"""
if is_pgp_encrypted(content) or contains_pgp_public_key(content):
return content
# replace quote paragraph
if '<p>"' in content:
if '"</p>' in content:
if content.count('<p>"') == content.count('"</p>'):
replacements = {
'<p>"': '<p><blockquote>',
'"</p>': '</blockquote></p>'
}
content = replace_strings(content, replacements)
if '>\u201c' in content:
if '\u201d<' in content:
if content.count('>\u201c') == content.count('\u201d<'):
replacements = {
'>\u201c': '><blockquote>',
'\u201d<': '</blockquote><'
}
content = replace_strings(content, replacements)
# replace email style quote
if '>> ' not in content:
return content
content_str = content.replace('<p>', '')
content_lines = content_str.split('</p>')
new_content = ''
for line_str in content_lines:
if not line_str:
continue
if '>> ' not in line_str:
if line_str.startswith('> '):
replacements = {
'> ': '<blockquote>',
'>': '<br>'
}
line_str = replace_strings(line_str, replacements)
new_content += '<p>' + line_str + '</blockquote></p>'
else:
new_content += '<p>' + line_str + '</p>'
continue
line_str = line_str.replace('>> ', '><blockquote>')
if line_str.startswith('>'):
line_str = line_str.replace('>', '<blockquote>', 1)
else:
line_str = line_str.replace('>', '<br>')
new_content += '<p>' + line_str + '</blockquote></p>'
return _remove_quotes_within_quotes(new_content)
def html_replace_quote_marks(content: str) -> str:
"""Replaces quotes with html formatting
"hello" becomes <q>hello</q>
"""
if is_pgp_encrypted(content) or contains_pgp_public_key(content):
return content
if '"' not in content:
if '"' not in content:
return content
# only if there are a few quote marks
if content.count('"') > 4:
return content
if content.count('"') > 4:
return content
new_content = content
if '"' in content:
sections = content.split('"')
if len(sections) > 1:
new_content = ''
open_quote = True
markup = False
for char in content:
curr_char = char
if char == '<':
markup = True
elif char == '>':
markup = False
elif char == '"' and not markup:
if open_quote:
curr_char = '“'
else:
curr_char = '”'
open_quote = not open_quote
new_content += curr_char
if '"' in new_content:
open_quote = True
content = new_content
new_content = ''
ctr = 0
sections = content.split('"')
no_of_sections = len(sections)
for sec in sections:
new_content += sec
if ctr < no_of_sections - 1:
if open_quote:
new_content += '“'
else:
new_content += '”'
open_quote = not open_quote
ctr += 1
return new_content
def dangerous_css(filename: str, allow_local_network_access: bool) -> bool:
"""Returns true is the css file contains code which
can create security problems
"""
if not os.path.isfile(filename):
return False
content = None
try:
with open(filename, 'r', encoding='utf-8') as fp_css:
content = fp_css.read().lower()
except OSError:
print('EX: unable to read css file ' + filename)
if not content:
return False
css_matches = (
'behavior:', ':expression', '?php', '.php',
'google', 'regexp', 'localhost',
'127.0.', '192.168', '10.0.', '@import'
)
for cssmatch in css_matches:
if cssmatch in content:
return True
# search for non-local web links
if 'url(' in content:
url_list = content.split('url(')
ctr = 0
for url_str in url_list:
if ctr == 0:
ctr = 1
continue
if ')' in url_str:
url_str = url_str.split(')')[0]
if string_contains(url_str, ('http', 'ipfs', 'ipns')):
print('ERROR: non-local web link in CSS ' +
filename)
return True
ctr += 1
# an attacker can include html inside of the css
# file as a comment and this may then be run from the html
if dangerous_markup(content, allow_local_network_access, []):
return True
return False
def switch_words(base_dir: str, nickname: str, domain: str, content: str,
rules: [] = []) -> str:
"""Performs word replacements. eg. Trump -> The Orange Menace
"""
if is_pgp_encrypted(content) or contains_pgp_public_key(content):
return content
if not rules:
switch_words_filename = \
acct_dir(base_dir, nickname, domain) + '/replacewords.txt'
if not os.path.isfile(switch_words_filename):
return content
try:
with open(switch_words_filename, 'r',
encoding='utf-8') as fp_words:
rules = fp_words.readlines()
except OSError:
print('EX: unable to read switches ' + switch_words_filename)
for line in rules:
replace_str = remove_eol(line)
splitters = ('->', ':', ',', ';', '-')
word_transform = None
for split_str in splitters:
if split_str in replace_str:
word_transform = replace_str.split(split_str)
break
if not word_transform:
continue
if len(word_transform) == 2:
replace_str1 = word_transform[0].strip().replace('"', '')
replace_str2 = word_transform[1].strip().replace('"', '')
content = content.replace(replace_str1, replace_str2)
return content
def _save_custom_emoji(session, base_dir: str, emoji_name: str, url: str,
debug: bool) -> None:
"""Saves custom emoji to file
"""
if not session:
if debug:
print('EX: _save_custom_emoji no session')
return
if '.' not in url:
return
ext = url.split('.')[-1]
if ext != 'png':
if debug:
print('EX: Custom emoji is wrong format ' + url)
return
emoji_name = emoji_name.replace(':', '').strip().lower()
custom_emoji_dir = base_dir + '/emojicustom'
if not os.path.isdir(custom_emoji_dir):
os.mkdir(custom_emoji_dir)
emoji_image_filename = custom_emoji_dir + '/' + emoji_name + '.' + ext
if not download_image(session, url,
emoji_image_filename, debug, False):
if debug:
print('EX: custom emoji not downloaded ' + url)
return
emoji_json_filename = custom_emoji_dir + '/emoji.json'
emoji_json = {}
if os.path.isfile(emoji_json_filename):
emoji_json = load_json(emoji_json_filename)
if not emoji_json:
emoji_json = {}
if not emoji_json.get(emoji_name):
emoji_json[emoji_name] = emoji_name
save_json(emoji_json, emoji_json_filename)
if debug:
print('EX: Saved custom emoji ' + emoji_json_filename)
elif debug:
print('EX: cusom emoji already saved')
def _get_emoji_name_from_code(base_dir: str, emoji_code: str) -> str:
"""Returns the emoji name from its code
"""
emojis_filename = base_dir + '/emoji/emoji.json'
if not os.path.isfile(emojis_filename):
emojis_filename = base_dir + '/emoji/default_emoji.json'
if not os.path.isfile(emojis_filename):
return None
emojis_json = load_json(emojis_filename)
if not emojis_json:
return None
for emoji_name, code in emojis_json.items():
if code == emoji_code:
return emoji_name
return None
def _update_common_emoji(base_dir: str, emoji_content: str) -> None:
"""Updates the list of commonly used emoji
"""
if '.' in emoji_content:
emoji_content = emoji_content.split('.')[0]
emoji_content = emoji_content.replace(':', '')
if emoji_content.startswith('0x'):
# lookup the name for an emoji code
emoji_code = emoji_content[2:]
emoji_content = _get_emoji_name_from_code(base_dir, emoji_code)
if not emoji_content:
return
common_emoji_filename = data_dir(base_dir) + '/common_emoji.txt'
common_emoji = None
if os.path.isfile(common_emoji_filename):
try:
with open(common_emoji_filename, 'r',
encoding='utf-8') as fp_emoji:
common_emoji = fp_emoji.readlines()
except OSError:
print('EX: unable to load common emoji file')
if common_emoji:
new_common_emoji = []
emoji_found = False
for line in common_emoji:
if ' ' + emoji_content in line:
if not emoji_found:
emoji_found = True
counter = 1
count_str = line.split(' ')[0]
if count_str.isdigit():
counter = int(count_str) + 1
count_str = str(counter).zfill(16)
line = count_str + ' ' + emoji_content
new_common_emoji.append(line)
else:
line1 = remove_eol(line)
new_common_emoji.append(line1)
if not emoji_found:
new_common_emoji.append(str(1).zfill(16) + ' ' + emoji_content)
new_common_emoji.sort(reverse=True)
try:
with open(common_emoji_filename, 'w+',
encoding='utf-8') as fp_emoji:
for line in new_common_emoji:
fp_emoji.write(line + '\n')
except OSError:
print('EX: error writing common emoji 1')
return
else:
line = str(1).zfill(16) + ' ' + emoji_content + '\n'
try:
with open(common_emoji_filename, 'w+',
encoding='utf-8') as fp_emoji:
fp_emoji.write(line)
except OSError:
print('EX: error writing common emoji 2')
return
def replace_emoji_from_tags(session, base_dir: str,
content: str, tag: [], message_type: str,
debug: bool, screen_readable: bool) -> str:
"""Uses the tags to replace :emoji: with html image markup
"""
for tag_item in tag:
if not isinstance(tag_item, dict):
continue
if not tag_item.get('type'):
continue
if tag_item['type'] != 'Emoji':
continue
if not tag_item.get('name'):
continue
if not tag_item.get('icon'):
continue
if not tag_item['icon'].get('url'):
continue
url_str = get_url_from_post(tag_item['icon']['url'])
if '/' not in url_str:
continue
if tag_item['name'] not in content:
continue
tag_url = remove_html(url_str)
if not tag_url:
continue
icon_name = tag_url.split('/')[-1]
if len(icon_name) <= 1:
continue
if not (icon_name[0].isdigit() and '.' in icon_name):
continue
icon_name = icon_name.split('.')[0]
# see https://unicode.org/
# emoji/charts/full-emoji-list.html
if '-' not in icon_name:
# a single code
replaced = False
try:
replace_char = chr(int("0x" + icon_name, 16))
if not screen_readable:
replace_char = \
'<span aria-hidden="true">' + \
replace_char + '</span>'
content = \
content.replace(tag_item['name'],
replace_char)
replaced = True
except BaseException:
if debug:
print('EX: replace_emoji_from_tags 1 ' +
'no conversion of ' +
str(icon_name) + ' to chr ' +
tag_item['name'] + ' ' +
tag_url)
if not replaced:
_save_custom_emoji(session, base_dir,
tag_item['name'],
tag_url, debug)
_update_common_emoji(base_dir, icon_name)
else:
_update_common_emoji(base_dir,
"0x" + icon_name)
else:
# sequence of codes
icon_codes = icon_name.split('-')
icon_code_sequence = ''
for icode in icon_codes:
replaced = False
try:
icon_code_sequence += chr(int("0x" +
icode, 16))
replaced = True
except BaseException:
icon_code_sequence = ''
if debug:
print('EX: ' +
'replace_emoji_from_tags 2 ' +
'no conversion of ' +
str(icode) + ' to chr ' +
tag_item['name'] + ' ' +
tag_url)
if not replaced:
_save_custom_emoji(session, base_dir,
tag_item['name'],
tag_url, debug)
_update_common_emoji(base_dir,
icon_name)
else:
_update_common_emoji(base_dir,
"0x" + icon_name)
if icon_code_sequence:
if not screen_readable:
icon_code_sequence = \
'<span aria-hidden="true">' + \
icon_code_sequence + '</span>'
content = content.replace(tag_item['name'],
icon_code_sequence)
html_class = 'emoji'
if message_type == 'post header':
html_class = 'emojiheader'
if message_type == 'profile':
html_class = 'emojiprofile'
if screen_readable:
emoji_tag_name = tag_item['name'].replace(':', '')
else:
emoji_tag_name = ''
url_str = get_url_from_post(tag_item['icon']['url'])
tag_url = remove_html(url_str)
emoji_html = "<img src=\"" + tag_url + "\" alt=\"" + \
emoji_tag_name + \
"\" align=\"middle\" class=\"" + html_class + "\"/>"
content = content.replace(tag_item['name'], emoji_html)
return content
def _add_music_tag(content: str, tag: str) -> str:
"""If a music link is found then ensure that the post is
tagged appropriately
"""
if '#podcast' in content or '#documentary' in content:
return content
if '#' not in tag:
tag = '#' + tag
if tag in content:
return content
music_site_found = False
for site in MUSIC_SITES:
if site + '/' in content:
music_site_found = True
break
if not music_site_found:
return content
return ':music: ' + content + ' ' + tag + ' '
def _shorten_linked_urls(content: str) -> str:
"""If content comes with a web link included then make sure
that it is short enough
"""
if 'href=' not in content:
return content
if '>' not in content:
return content
if '<' not in content:
return content
sections = content.split('>')
ctr = 0
for section_text in sections:
if ctr == 0:
ctr += 1
continue
if '<' not in section_text:
ctr += 1
continue
section_text = section_text.split('<')[0]
if ' ' in section_text:
continue
if len(section_text) > MAX_LINK_LENGTH:
content = content.replace('>' + section_text + '<',
'>' +
section_text[:MAX_LINK_LENGTH-1] + '<')
ctr += 1
return content
def _contains_doi_reference(wrd: str, replace_dict: {}) -> bool:
"""Handle DOI scientific references
"""
if not wrd.startswith('doi:') and \
not wrd.startswith('DOI:'):
return False
doi_ref_str = wrd.split(':', 1)[1]
doi_site = 'https://sci-hub.ru'
markup = '<a href="' + doi_site + '/' + \
doi_ref_str + '" tabindex="10" ' + \
'rel="nofollow noopener noreferrer" ' + \
'target="_blank">' + \
'<span class="ellipsis">doi:' + doi_ref_str + \
'</span></a>'
replace_dict[wrd] = markup
return True
def _contains_arxiv_reference(wrd: str, replace_dict: {}) -> bool:
"""Handle arxiv scientific references
"""
if not wrd.startswith('arXiv:') and \
not wrd.startswith('arx:') and \
not wrd.startswith('arxiv:'):
return False
arxiv_ref_str = wrd.split(':', 1)[1].lower()
if '.' in arxiv_ref_str:
arxiv_ref = arxiv_ref_str.split('.')
elif ':' in arxiv_ref_str:
arxiv_ref = arxiv_ref_str.split(':')
else:
return False
if len(arxiv_ref) != 2:
return False
if not arxiv_ref[0].isdigit():
return False
arxiv_day = arxiv_ref[1]
if 'v' in arxiv_day:
arxiv_day = arxiv_day.split('v')[0]
if not arxiv_day.isdigit():
return False
ref_str = arxiv_ref[0] + '.' + arxiv_ref[1]
markup = '<a href="https://arxiv.org/abs/' + \
ref_str + '" tabindex="10" ' + \
'rel="nofollow noopener noreferrer" ' + \
'target="_blank">' + \
'<span class="ellipsis">arXiv:' + ref_str + \
'</span></a>'
replace_dict[wrd] = markup
return True
def _contains_academic_references(content: str) -> bool:
"""Does the given content contain academic references
"""
prefixes = (
'arXiv:', 'arx:', 'arxiv:',
'doi:', 'DOI:'
)
for reference in prefixes:
if reference in content:
return True
return False
def remove_link_trackers_from_content(content: str) -> str:
""" Removes any link trackers from urls within the content
"""
if '?utm_' not in content:
return content
sections = content.split('?utm_')
ctr = 0
new_content = ''
for section_str in sections:
if ctr == 0:
new_content = section_str
ctr = 1
continue
if '"' in section_str:
new_content += '"' + section_str.split('"', 1)[1]
else:
new_content += section_str
ctr += 1
return new_content
def add_web_links(content: str) -> str:
"""Adds markup for web links
"""
content = _shorten_linked_urls(content)
if ':' not in content:
return content
prefixes = get_link_prefixes()
# do any of these prefixes exist within the content?
prefix_found = False
for prefix in prefixes:
if prefix in content:
prefix_found = True
break
# if there are no prefixes then just keep the content we have
if not prefix_found:
if _contains_academic_references(content):
prefix_found = True
else:
return content
content = content.replace('\r', '')
words = content.replace('\n', ' --linebreak-- ').split(' ')
replace_dict = {}
for wrd in words:
if ':' not in wrd:
continue
if _contains_arxiv_reference(wrd, replace_dict):
continue
if _contains_doi_reference(wrd, replace_dict):
continue
# does the word begin with a link prefix?
prefix_found = False
for prefix in prefixes:
if wrd.startswith(prefix):
prefix_found = True
break
if not prefix_found:
continue
# the word contains a link prefix
url = wrd
if url.endswith('.') or wrd.endswith(';'):
url = url[:-1]
url = remove_link_tracking(url)
markup = '<a href="' + url + '" tabindex="10" ' + \
'rel="nofollow noopener noreferrer" target="_blank">'
for prefix in prefixes:
if url.startswith(prefix):
markup += '<span class="invisible">' + prefix + '</span>'
break
link_text = url
for prefix in prefixes:
link_text = link_text.replace(prefix, '')
# prevent links from becoming too long
if len(link_text) > MAX_LINK_LENGTH:
markup += '<span class="ellipsis">' + \
link_text[:MAX_LINK_LENGTH] + '</span>'
markup += '<span class="invisible">' + \
link_text[MAX_LINK_LENGTH:] + '</span></a>'
else:
markup += '<span class="ellipsis">' + link_text + '</span></a>'
replace_dict[url] = markup
# do the replacements
for url, markup in replace_dict.items():
content = content.replace(url, markup)
# replace any line breaks
content = content.replace(' --linebreak-- ', '<br>')
return content
def safe_web_text(arbitrary_html: str) -> str:
"""Turns arbitrary html into something safe.
So if the arbitrary html contains attack scripts those will be removed
"""
# first remove the markup, so that we have something safe
safe_text = remove_html(arbitrary_html)
if not safe_text:
return ''
# remove any spurious characters found in podcast descriptions
remove_chars = ('Œ', 'â€', 'ğŸ', '�', ']]', '__')
for remchar in remove_chars:
safe_text = safe_text.replace(remchar, '')
# recreate any url links safely
return add_web_links(safe_text)
def _add_hash_tags(word_str: str, http_prefix: str, domain: str,
replace_hashtags: {}, post_hashtags: {}) -> bool:
"""Detects hashtags and adds them to the replacements dict
Also updates the hashtags list to be added to the post
"""
if replace_hashtags.get(word_str):
return True
hashtag = word_str[1:]
if not valid_hash_tag(hashtag):
return False
hashtag_url = http_prefix + "://" + domain + "/tags/" + hashtag
post_hashtags[hashtag] = {
'href': hashtag_url,
'name': '#' + hashtag,
'type': 'Hashtag'
}
replace_hashtags[word_str] = "<a href=\"" + hashtag_url + \
"\" class=\"mention hashtag\" rel=\"tag\" tabindex=\"10\">" + \
"<span aria-hidden=\"true\">#</span><span>" + \
hashtag + "</span></a>"
return True
def replace_remote_hashtags(content: str,
nickname: str, domain: str) -> str:
"""Replaces remote hashtags with a local version
"""
if not domain:
return content
if ' href="' not in content:
return content
sections = content.split(' href="')
ctr = 0
replacements = {}
for section in sections:
if ctr == 0:
ctr += 1
continue
if '"' not in section:
ctr += 1
continue
link = section.split('"')[0]
if '://' not in link:
continue
if '?remotetag=' in link:
ctr += 1
continue
if '/tags/' not in link:
ctr += 1
continue
if '/' + domain not in link:
new_link = '/users/' + nickname + \
'?remotetag=' + link.replace('/', '--')
replacements[link] = new_link
ctr += 1
if not replacements:
return content
for old_link, new_link in replacements.items():
content = content.replace('"' + old_link + '"',
'"' + new_link + '"')
return content
def _add_emoji(base_dir: str, word_str: str,
http_prefix: str, domain: str,
replace_emoji: {}, post_tags: {},
emoji_dict: {}) -> bool:
"""Detects Emoji and adds them to the replacements dict
Also updates the tags list to be added to the post
"""
if not word_str.startswith(':'):
return False
if not word_str.endswith(':'):
return False
if len(word_str) < 3:
return False
if replace_emoji.get(word_str):
return True
# remove leading and trailing : characters
emoji = word_str[1:]
emoji = emoji[:-1]
# is the text of the emoji valid?
if not valid_hash_tag(emoji):
return False
if not emoji_dict.get(emoji):
return False
emoji_filename = base_dir + '/emoji/' + emoji_dict[emoji] + '.png'
if not os.path.isfile(emoji_filename):
emoji_filename = \
base_dir + '/emojicustom/' + emoji_dict[emoji] + '.png'
if not os.path.isfile(emoji_filename):
return False
emoji_url = http_prefix + "://" + domain + \
"/emoji/" + emoji_dict[emoji] + '.png'
post_tags[emoji] = {
'icon': {
'mediaType': 'image/png',
'type': 'Image',
'url': emoji_url
},
'name': ':' + emoji + ':',
"updated": file_last_modified(emoji_filename),
"id": emoji_url.replace('.png', ''),
'type': 'Emoji'
}
return True
def post_tag_exists(tag_type: str, tag_name: str, tags: {}) -> bool:
"""Returns true if a tag exists in the given dict
"""
for tag in tags:
if tag['name'] == tag_name and tag['type'] == tag_type:
return True
return False
def _mention_to_url(base_dir: str, http_prefix: str,
domain: str, nickname: str) -> str:
"""Convert https://somedomain/@somenick to
https://somedomain/users/somenick
This uses the hack of trying the cache directory to see if
there is a matching actor
"""
possible_paths = get_user_paths()
cache_dir = base_dir + '/cache/actors'
cache_path_start = cache_dir + '/' + http_prefix + ':##' + domain
for users_path in possible_paths:
users_path = users_path.replace('/', '#')
possible_cache_entry = \
cache_path_start + users_path + nickname + '.json'
if os.path.isfile(possible_cache_entry):
return http_prefix + '://' + \
domain + users_path.replace('#', '/') + nickname
possible_cache_entry = \
cache_path_start + '#' + nickname + '.json'
if os.path.isfile(possible_cache_entry):
return http_prefix + '://' + domain + '/' + nickname
return http_prefix + '://' + domain + '/users/' + nickname
def _add_mention(base_dir: str, word_str: str, http_prefix: str,
following: [], petnames: [], replace_mentions: {},
recipients: [], tags: {}) -> bool:
"""Detects mentions and adds them to the replacements dict and
recipients list
"""
possible_handle = word_str[1:]
# @nick
if following and '@' not in possible_handle:
# fall back to a best effort match against the following list
# if no domain was specified. eg. @nick
possible_nickname = possible_handle
for follow in following:
if '@' not in follow:
continue
follow_nick = follow.split('@')[0]
if possible_nickname != follow_nick:
continue
follow_str = remove_eol(follow)
replace_domain = follow_str.split('@')[1]
recipient_actor = \
_mention_to_url(base_dir, http_prefix,
replace_domain, possible_nickname)
if recipient_actor not in recipients:
recipients.append(recipient_actor)
tags[word_str] = {
'href': recipient_actor,
'name': word_str,
'type': 'Mention'
}
replace_mentions[word_str] = \
"<span class=\"h-card\"><a href=\"" + recipient_actor + \
"\" tabindex=\"10\" class=\"u-url mention\">@<span>" + \
possible_nickname + "</span></a></span>"
return True
# try replacing petnames with mentions
follow_ctr = 0
for follow in following:
if '@' not in follow:
follow_ctr += 1
continue
pet = remove_eol(petnames[follow_ctr])
if pet:
if possible_nickname != pet:
follow_ctr += 1
continue
follow_str = remove_eol(follow)
replace_nickname = follow_str.split('@')[0]
replace_domain = follow_str.split('@')[1]
recipient_actor = \
_mention_to_url(base_dir, http_prefix,
replace_domain, replace_nickname)
if recipient_actor not in recipients:
recipients.append(recipient_actor)
tags[word_str] = {
'href': recipient_actor,
'name': word_str,
'type': 'Mention'
}
replace_mentions[word_str] = \
"<span class=\"h-card\"><a href=\"" + \
recipient_actor + "\" tabindex=\"10\" " + \