Debian Codegraph @

linkify_it/main.py

raw symbols SCIP
1 import copy
2 import re
3 import types
4
5 from .ucre import build_re
6
7 # py>=37: re.Pattern, else: _sre.SRE_Pattern
8 RE_TYPE = type(re.compile(r""))
9
10
11 def _escape_re(string):
12 return re.sub(r"([.?*+^$[\]\\(){}|-])", r"\\\1", string)
13
14
15 def _index_of(text, search_value):
16 try:
17 result = text.index(search_value)
18 except ValueError:
19 result = -1
20
21 return result
22
23
24 class SchemaError(Exception):
25 """Linkify schema error"""
26
27 def __init__(self, name, val):
28 message = f"(LinkifyIt) Invalid schema '{name}': '{val}'"
29 super().__init__(message)
30
31
32 class Match:
33 """Match result.
34
35 Attributes:
36 schema (str): Prefix (protocol) for matched string.
37 index (int): First position of matched string.
38 last_index (int): Next position after matched string.
39 raw (str): Matched string.
40 text (str): Notmalized text of matched string.
41 url (str): Normalized url of matched string.
42
43 Args:
44 linkifyit (:class:`linkify_it.main.LinkifyIt`) LinkifyIt object
45 shift (int): text searh position
46 """
47
48 def __repr__(self):
49 return (
50 f"{self.__class__.__module__}.{self.__class__.__name__}({self.__dict__!r})"
51 )
52
53 def __init__(self, linkifyit, shift):
54 start = linkifyit._index
55 end = linkifyit._last_index
56 text = linkifyit._text_cache[start:end]
57
58 self.schema = linkifyit._schema.lower()
59 self.index = start + shift
60 self.last_index = end + shift
61 self.raw = text
62 self.text = text
63 self.url = text
64
65
66 class LinkifyIt:
67 """Creates new linkifier instance with optional additional schemas.
68
69 By default understands:
70
71 - ``http(s)://...`` , ``ftp://...``, ``mailto:...`` & ``//...`` links
72 - "fuzzy" links and emails (example.com, [email protected]).
73
74 ``schemas`` is an dict where each key/value describes protocol/rule:
75
76 - **key** - link prefix (usually, protocol name with ``:`` at the end, ``skype:``
77 for example). `linkify-it` makes shure that prefix is not preceeded with
78 alphanumeric char. Only whitespaces and punctuation allowed.
79
80 - **value** - rule to check tail after link prefix
81
82 - *str* - just alias to existing rule
83 - *dict*
84
85 - *validate* - either a ``re.Pattern``, ``re str`` (start with ``^``, and don't
86 include the link prefix itself), or a validator ``function`` which, given
87 arguments *self*, *text* and *pos* returns the length of a match in *text*
88 starting at index *pos*. *pos* is the index right after the link prefix.
89 - *normalize* - optional function to normalize text & url of matched
90 result (for example, for @twitter mentions).
91
92 ``options`` is an dict:
93
94 - **fuzzyLink** - recognige URL-s without ``http(s):`` prefix. Default ``True``.
95 - **fuzzyIP** - allow IPs in fuzzy links above. Can conflict with some texts
96 like version numbers. Default ``False``.
97 - **fuzzyEmail** - recognize emails without ``mailto:`` prefix.
98 - **---** - set `True` to terminate link with `---` (if it's considered as long
99 dash).
100
101 Args:
102 schemas (dict): Optional. Additional schemas to validate (prefix/validator)
103 options (dict): { fuzzy_link | fuzzy_email | fuzzy_ip: True | False }.
104 Default: {"fuzzy_link": True, "fuzzy_email": True, "fuzzy_ip": False}.
105 """
106
107 def _validate_http(self, text, pos):
108 tail = text[pos:]
109 if not self.re.get("http"):
110 # compile lazily, because "host"-containing variables can change on
111 # tlds update.
112 self.re["http"] = (
113 "^\\/\\/"
114 + self.re["src_auth"]
115 + self.re["src_host_port_strict"]
116 + self.re["src_path"]
117 )
118
119 founds = re.search(self.re["http"], tail, flags=re.IGNORECASE)
120 if founds:
121 return len(founds.group())
122
123 return 0
124
125 def _validate_double_slash(self, text, pos):
126 tail = text[pos:]
127
128 if not self.re.get("not_http"):
129 # compile lazily, because "host"-containing variables can change on
130 # tlds update.
131 self.re["not_http"] = (
132 "^"
133 + self.re["src_auth"]
134 + "(?:localhost|(?:(?:"
135 + self.re["src_domain"]
136 + ")\\.)+"
137 + self.re["src_domain_root"]
138 + ")"
139 + self.re["src_port"]
140 + self.re["src_host_terminator"]
141 + self.re["src_path"]
142 )
143
144 founds = re.search(self.re["not_http"], tail, flags=re.IGNORECASE)
145 if founds:
146 if pos >= 3 and text[pos - 3] == ":":
147 return 0
148
149 if pos >= 3 and text[pos - 3] == "/":
150 return 0
151
152 return len(founds.group(0))
153
154 return 0
155
156 def _validate_mailto(self, text, pos):
157 tail = text[pos:]
158
159 if not self.re.get("mailto"):
160 self.re["mailto"] = (
161 "^" + self.re["src_email_name"] + "@" + self.re["src_host_strict"]
162 )
163
164 founds = re.search(self.re["mailto"], tail, flags=re.IGNORECASE)
165 if founds:
166 return len(founds.group(0))
167
168 return 0
169
170 def _reset_scan_cache(self):
171 self._index = -1
172 self._text_cache = ""
173
174 def _create_validator(self, regex):
175 def func(text, pos):
176 tail = text[pos:]
177 if isinstance(regex, str):
178 founds = re.search(regex, tail, flags=re.IGNORECASE)
179 else:
180 # re.Pattern
181 founds = re.search(regex, tail)
182
183 if founds:
184 return len(founds.group(0))
185
186 return 0
187
188 return func
189
190 def _create_normalizer(self):
191 def func(match):
192 self.normalize(match)
193
194 return func
195
196 def _create_match(self, shift):
197 match = Match(self, shift)
198 self._compiled[match.schema]["normalize"](match)
199 return match
200
201 def __init__(self, schemas=None, options=None):
202 self.default_options = {
203 "fuzzy_link": True,
204 "fuzzy_email": True,
205 "fuzzy_ip": False,
206 }
207
208 self.default_schemas = {
209 "http:": {"validate": self._validate_http},
210 "https:": "http:",
211 "ftp:": "http:",
212 "//": {"validate": self._validate_double_slash},
213 "mailto:": {"validate": self._validate_mailto},
214 }
215
216 # RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js)
217 self.tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]" # noqa: E501
218
219 # DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead
220 self.tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split( # noqa: E501
221 "|"
222 )
223
224 if options:
225 self.default_options.update(options)
226 self._opts = self.default_options
227 else:
228 self._opts = self.default_options
229
230 # Cache last tested result. Used to skip repeating steps on next `match` call.
231 self._index = -1
232 self._last_index = -1 # Next scan position
233 self._schema = ""
234 self._text_cache = ""
235
236 if schemas:
237 self.default_schemas.update(schemas)
238 self._schemas = self.default_schemas
239 else:
240 self._schemas = self.default_schemas
241
242 self._compiled = {}
243
244 self._tlds = self.tlds_default
245 self._tlds_replaced = False
246
247 self.re = {}
248
249 self._compile()
250
251 def _compile(self):
252 """Schemas compiler. Build regexps."""
253
254 # Load & clone RE patterns.
255 self.re = build_re(self._opts)
256
257 # Define dynamic patterns
258 tlds = copy.deepcopy(self._tlds)
259
260 self._on_compile()
261
262 if not self._tlds_replaced:
263 tlds.append(self.tlds_2ch_src_re)
264 tlds.append(self.re["src_xn"])
265
266 self.re["src_tlds"] = "|".join(tlds)
267
268 def untpl(tpl):
269 return tpl.replace("%TLDS%", self.re["src_tlds"])
270
271 self.re["email_fuzzy"] = untpl(self.re["tpl_email_fuzzy"])
272
273 self.re["link_fuzzy"] = untpl(self.re["tpl_link_fuzzy"])
274
275 self.re["link_no_ip_fuzzy"] = untpl(self.re["tpl_link_no_ip_fuzzy"])
276
277 self.re["host_fuzzy_test"] = untpl(self.re["tpl_host_fuzzy_test"])
278
279 #
280 # Compile each schema
281 #
282
283 aliases = []
284
285 self._compiled = {}
286
287 for name, val in self._schemas.items():
288 # skip disabled methods
289 if val is None:
290 continue
291
292 compiled = {"validate": None, "link": None}
293
294 self._compiled[name] = compiled
295
296 if isinstance(val, dict):
297 if isinstance(val.get("validate"), RE_TYPE):
298 compiled["validate"] = self._create_validator(val.get("validate"))
299 elif isinstance(val.get("validate"), str):
300 compiled["validate"] = self._create_validator(val.get("validate"))
301 elif isinstance(val.get("validate"), types.MethodType):
302 compiled["validate"] = val.get("validate")
303 # Add custom handler
304 elif isinstance(val.get("validate"), types.FunctionType):
305 setattr(LinkifyIt, "func", val.get("validate"))
306 compiled["validate"] = self.func
307 else:
308 raise SchemaError(name, val)
309
310 if isinstance(val.get("normalize"), types.MethodType):
311 compiled["normalize"] = val.get("normalize")
312 # Add custom handler
313 elif isinstance(val.get("normalize"), types.FunctionType):
314 setattr(LinkifyIt, "func", val.get("normalize"))
315 compiled["normalize"] = self.func
316 elif not val.get("normalize"):
317 compiled["normalize"] = self._create_normalizer()
318 else:
319 raise SchemaError(name, val)
320
321 continue
322
323 if isinstance(val, str):
324 aliases.append(name)
325 continue
326
327 raise SchemaError(name, val)
328
329 #
330 # Compile postponed aliases
331 #
332 for alias in aliases:
333 if not self._compiled.get(self._schemas.get(alias)):
334 continue
335
336 self._compiled[alias]["validate"] = self._compiled[self._schemas[alias]][
337 "validate"
338 ]
339 self._compiled[alias]["normalize"] = self._compiled[self._schemas[alias]][
340 "normalize"
341 ]
342
343 # Fake record for guessed links
344 self._compiled[""] = {"validate": None, "normalize": self._create_normalizer()}
345
346 #
347 # Build schema condition
348 #
349 slist = "|".join(
350 [
351 _escape_re(name)
352 for name, val in self._compiled.items()
353 if len(name) > 0 and val
354 ]
355 )
356
357 re_schema_test = (
358 "(^|(?!_)(?:[><\uff5c]|" + self.re["src_ZPCc"] + "))(" + slist + ")"
359 )
360
361 # (?!_) cause 1.5x slowdown
362 self.re["schema_test"] = re_schema_test
363 self.re["schema_search"] = re_schema_test
364 self.re["schema_at_start"] = "^" + self.re["schema_search"]
365
366 self.re["pretest"] = (
367 "(" + re_schema_test + ")|(" + self.re["host_fuzzy_test"] + ")|@"
368 )
369
370 # Cleanup
371
372 self._reset_scan_cache()
373
374 def add(self, schema, definition):
375 """Add new rule definition. (chainable)
376
377 See :class:`linkify_it.main.LinkifyIt` init description for details.
378 ``schema`` is a link prefix (``skype:``, for example), and ``definition``
379 is a ``str`` to alias to another schema, or an ``dict`` with ``validate`` and
380 optionally `normalize` definitions. To disable an existing rule, use
381 ``.add(<schema>, None)``.
382
383 Args:
384 schema (str): rule name (fixed pattern prefix)
385 definition (`str` or `re.Pattern`): schema definition
386
387 Return:
388 :class:`linkify_it.main.LinkifyIt`
389 """
390 self._schemas[schema] = definition
391 self._compile()
392 return self
393
394 def set(self, options):
395 """Override default options. (chainable)
396
397 Missed properties will not be changed.
398
399 Args:
400 options (dict): ``keys``: [``fuzzy_link`` | ``fuzzy_email`` | ``fuzzy_ip``].
401 ``values``: [``True`` | ``False``]
402
403 Return:
404 :class:`linkify_it.main.LinkifyIt`
405 """
406 self._opts.update(options)
407 return self
408
409 def test(self, text):
410 """Searches linkifiable pattern and returns ``True`` on success or ``False``
411 on fail.
412
413 Args:
414 text (str): text to search
415
416 Returns:
417 bool: ``True`` if a linkable pattern was found, otherwise it is ``False``.
418 """
419 self._text_cache = text
420 self._index = -1
421
422 if not len(text):
423 return False
424
425 if re.search(self.re["schema_test"], text, flags=re.IGNORECASE):
426 regex = self.re["schema_search"]
427 last_index = 0
428 matched_iter = re.finditer(regex, text[last_index:], flags=re.IGNORECASE)
429 for matched in matched_iter:
430 last_index = matched.end(0)
431 m = (matched.group(), matched.groups()[0], matched.groups()[1])
432 length = self.test_schema_at(text, m[2], last_index)
433 if length:
434 self._schema = m[2]
435 self._index = matched.start(0) + len(m[1])
436 self._last_index = matched.start(0) + len(m[0]) + length
437 break
438
439 if self._opts.get("fuzzy_link") and self._compiled.get("http:"):
440 # guess schemaless links
441 matched_tld = re.search(
442 self.re["host_fuzzy_test"], text, flags=re.IGNORECASE
443 )
444 if matched_tld:
445 tld_pos = matched_tld.start(0)
446 else:
447 tld_pos = -1
448 if tld_pos >= 0:
449 # if tld is located after found link - no need to check fuzzy pattern
450 if self._index < 0 or tld_pos < self._index:
451 if self._opts.get("fuzzy_ip"):
452 pattern = self.re["link_fuzzy"]
453 else:
454 pattern = self.re["link_no_ip_fuzzy"]
455
456 ml = re.search(pattern, text, flags=re.IGNORECASE)
457 if ml:
458 shift = ml.start(0) + len(ml.groups()[0])
459
460 if self._index < 0 or shift < self._index:
461 self._schema = ""
462 self._index = shift
463 self._last_index = ml.start(0) + len(ml.group())
464
465 if self._opts.get("fuzzy_email") and self._compiled.get("mailto:"):
466 # guess schemaless emails
467 at_pos = _index_of(text, "@")
468 if at_pos >= 0:
469 # We can't skip this check, because this cases are possible:
470 # [email protected], [email protected]
471 me = re.search(self.re["email_fuzzy"], text, flags=re.IGNORECASE)
472 if me:
473 shift = me.start(0) + len(me.groups()[0])
474 next_shift = me.start(0) + len(me.group())
475
476 if (
477 self._index < 0
478 or shift < self._index
479 or (shift == self._index and next_shift > self._last_index)
480 ):
481 self._schema = "mailto:"
482 self._index = shift
483 self._last_index = next_shift
484
485 return self._index >= 0
486
487 def pretest(self, text):
488 """Very quick check, that can give false positives.
489
490 Returns true if link MAY BE can exists. Can be used for speed optimization,
491 when you need to check that link NOT exists.
492
493 Args:
494 text (str): text to search
495
496 Returns:
497 bool: ``True`` if a linkable pattern was found, otherwise it is ``False``.
498 """
499 if re.search(self.re["pretest"], text, flags=re.IGNORECASE):
500 return True
501
502 return False
503
504 def test_schema_at(self, text, name, position):
505 """Similar to :meth:`linkify_it.main.LinkifyIt.test` but checks only
506 specific protocol tail exactly at given position.
507
508 Args:
509 text (str): text to scan
510 name (str): rule (schema) name
511 position (int): length of found pattern (0 on fail).
512
513 Returns:
514 int: text (str): text to search
515 """
516 # If not supported schema check requested - terminate
517 if not self._compiled.get(name.lower()):
518 return 0
519 return self._compiled.get(name.lower()).get("validate")(text, position)
520
521 def match(self, text):
522 """Returns ``list`` of found link descriptions or ``None`` on fail.
523
524 We strongly recommend to use :meth:`linkify_it.main.LinkifyIt.test`
525 first, for best speed.
526
527 Args:
528 text (str): text to search
529
530 Returns:
531 ``list`` or ``None``: Result match description:
532 * **schema** - link schema, can be empty for fuzzy links, or ``//``
533 for protocol-neutral links.
534 * **index** - offset of matched text
535 * **last_index** - offset of matched text
536 * **raw** - offset of matched text
537 * **text** - normalized text
538 * **url** - link, generated from matched text
539 """
540 shift = 0
541 result = []
542
543 # try to take previous element from cache, if .test() called before
544 if self._index >= 0 and self._text_cache == text:
545 result.append(self._create_match(shift))
546 shift = self._last_index
547
548 # Cut head if cache was used
549 tail = text[shift:] if shift else text
550
551 # Scan string until end reached
552 while self.test(tail):
553 result.append(self._create_match(shift))
554
555 tail = tail[self._last_index :]
556 shift += self._last_index
557
558 if len(result):
559 return result
560
561 return None
562
563 def match_at_start(self, text):
564 """Returns fully-formed (not fuzzy) link if it starts at the beginning
565 of the string, and null otherwise.
566
567 Args:
568 text (str): text to search
569
570 Retuns:
571 ``Match`` or ``None``
572 """
573 # Reset scan cache
574 self._text_cache = text
575 self._index = -1
576
577 if not len(text):
578 return None
579
580 founds = re.search(self.re["schema_at_start"], text, flags=re.IGNORECASE)
581 if not founds:
582 return None
583
584 m = (founds.group(), founds.groups()[0], founds.groups()[1])
585 length = self.test_schema_at(text, m[2], len(m[0]))
586 if not length:
587 return None
588
589 self._schema = m[2]
590 self._index = founds.start(0) + len(m[1])
591 self._last_index = founds.start(0) + len(m[0]) + length
592
593 return self._create_match(0)
594
595 def tlds(self, list_tlds, keep_old=False):
596 """Load (or merge) new tlds list. (chainable)
597
598 Those are user for fuzzy links (without prefix) to avoid false positives.
599 By default this algorythm used:
600
601 * hostname with any 2-letter root zones are ok.
602 * biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф
603 are ok.
604 * encoded (`xn--...`) root zones are ok.
605
606 If list is replaced, then exact match for 2-chars root zones will be checked.
607
608 Args:
609 list_tlds (list or str): ``list of tlds`` or ``tlds string``
610 keep_old (bool): merge with current list if q`True`q (q`Falseq` by default)
611 """
612 _list = list_tlds if isinstance(list_tlds, list) else [list_tlds]
613
614 if not keep_old:
615 self._tlds = _list
616 self._tlds_replaced = True
617 self._compile()
618 return self
619
620 self._tlds.extend(_list)
621 self._tlds = sorted(list(set(self._tlds)), reverse=True)
622
623 self._compile()
624 return self
625
626 def normalize(self, match):
627 """Default normalizer (if schema does not define it's own).
628
629 Args:
630 match (:class:`linkify_it.main.Match`): Match result
631 """
632 if not match.schema:
633 match.url = "http://" + match.url
634
635 if match.schema == "mailto:" and not re.search(
636 "^mailto:", match.url, flags=re.IGNORECASE
637 ):
638 match.url = "mailto:" + match.url
639
640 def _on_compile(self):
641 """Override to modify basic RegExp-s."""
642 pass