Debian Codegraph @

ddgr

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 # Copyright (C) 2016-2024 Arun Prakash Jana <[email protected]>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import argparse
19 import codecs
20 import collections
21 import functools
22 import gzip
23 import html.entities
24 import html.parser
25 import json
26 import locale
27 import logging
28 import os
29 import platform
30 import shutil
31 import signal
32 from subprocess import Popen, PIPE, DEVNULL
33 import sys
34 import tempfile
35 import textwrap
36 import unicodedata
37 import urllib.error
38 import urllib.parse
39 import urllib.request
40 import webbrowser
41
42 try:
43 import readline
44 except ImportError:
45 pass
46
47 try:
48 import setproctitle
49 setproctitle.setproctitle('ddgr')
50 except (ImportError, Exception):
51 pass
52
53 # Basic setup
54
55 logging.basicConfig(format='[%(levelname)s] %(message)s')
56 LOGGER = logging.getLogger()
57 LOGDBG = LOGGER.debug
58 LOGERR = LOGGER.error
59
60
61 def sigint_handler(signum, frame):
62 print('\nInterrupted.', file=sys.stderr)
63 sys.exit(1)
64
65
66 try:
67 signal.signal(signal.SIGINT, sigint_handler)
68 except ValueError:
69 # signal only works in main thread
70 pass
71
72 # Constants
73
74 _VERSION_ = '2.2'
75
76 COLORMAP = {k: '\x1b[%sm' % v for k, v in {
77 'a': '30', 'b': '31', 'c': '32', 'd': '33',
78 'e': '34', 'f': '35', 'g': '36', 'h': '37',
79 'i': '90', 'j': '91', 'k': '92', 'l': '93',
80 'm': '94', 'n': '95', 'o': '96', 'p': '97',
81 'A': '30;1', 'B': '31;1', 'C': '32;1', 'D': '33;1',
82 'E': '34;1', 'F': '35;1', 'G': '36;1', 'H': '37;1',
83 'I': '90;1', 'J': '91;1', 'K': '92;1', 'L': '93;1',
84 'M': '94;1', 'N': '95;1', 'O': '96;1', 'P': '97;1',
85 'x': '0', 'X': '1', 'y': '7', 'Y': '7;1',
86 }.items()}
87
88 USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
89
90 TEXT_BROWSERS = ['elinks', 'links', 'lynx', 'w3m', 'www-browser']
91
92 INDENT = 5
93
94 # Global helper functions
95
96
97 def open_url(url):
98 """Open an URL in the user's default web browser.
99
100 The string attribute ``open_url.url_handler`` can be used to open URLs
101 in a custom CLI script or utility. A subprocess is spawned with url as
102 the parameter in this case instead of the usual webbrowser.open() call.
103
104 Whether the browser's output (both stdout and stderr) are suppressed
105 depends on the boolean attribute ``open_url.suppress_browser_output``.
106 If the attribute is not set upon a call, set it to a default value,
107 which means False if BROWSER is set to a known text-based browser --
108 elinks, links, lynx, w3m or 'www-browser'; or True otherwise.
109
110 The string attribute ``open_url.override_text_browser`` can be used to
111 ignore env var BROWSER as well as some known text-based browsers and
112 attempt to open url in a GUI browser available.
113 Note: If a GUI browser is indeed found, this option ignores the program
114 option `show-browser-logs`
115 """
116 LOGDBG('Opening %s', url)
117
118 # Custom URL handler gets max priority
119 if hasattr(open_url, 'url_handler'):
120 with Popen([open_url.url_handler, url], stdin=PIPE) as pipe:
121 pipe.communicate()
122 return
123
124 browser = webbrowser.get()
125 if open_url.override_text_browser:
126 browser_output = open_url.suppress_browser_output
127 for name in [b for b in webbrowser._tryorder if b not in TEXT_BROWSERS]:
128 browser = webbrowser.get(name)
129 LOGDBG(browser)
130
131 # Found a GUI browser, suppress browser output
132 open_url.suppress_browser_output = True
133 break
134
135 if open_url.suppress_browser_output:
136 _stderr = os.dup(2)
137 os.close(2)
138 _stdout = os.dup(1)
139 if "microsoft" not in platform.uname()[3].lower():
140 os.close(1)
141 fd = os.open(os.devnull, os.O_RDWR)
142 os.dup2(fd, 2)
143 os.dup2(fd, 1)
144 try:
145 browser.open(url, new=2)
146 finally:
147 if open_url.suppress_browser_output:
148 os.close(fd)
149 os.dup2(_stderr, 2)
150 os.dup2(_stdout, 1)
151
152 if open_url.override_text_browser:
153 open_url.suppress_browser_output = browser_output
154
155
156 def https_get(url, headers=None, proxies=None, expected_code=None):
157 """Sends an HTTPS GET request; returns the HTTP status code and the
158 decoded response payload.
159
160 By default, HTTP 301, 302 and 303 are followed; all other non-2XX
161 responses result in a urllib.error.HTTPError. If expected_code is
162 supplied, a urllib.error.HTTPError is raised unless the status code
163 matches expected_code.
164 """
165 headers = headers or {}
166 proxies = {'https': proxies['https']} if proxies.get('https') else {}
167 opener = urllib.request.build_opener(
168 urllib.request.HTTPSHandler,
169 urllib.request.ProxyHandler(proxies),
170 urllib.request.HTTPRedirectHandler,
171 )
172 req = urllib.request.Request(
173 url,
174 )
175 resp = opener.open(req)
176 code = resp.getcode()
177 if expected_code is not None and code != expected_code:
178 raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp)
179 payload = resp.read()
180 try:
181 payload = gzip.decompress(payload)
182 except OSError:
183 pass
184 finally:
185 payload = payload.decode('utf-8')
186 return code, payload
187
188
189 def https_post(url, data=None, headers=None, proxies=None, expected_code=None):
190 """Sends an HTTPS POST request; returns the HTTP status code and the
191 decoded response payload.
192
193 By default, HTTP 301, 302 and 303 are followed; all other non-2XX
194 responses result in a urllib.error.HTTPError. If expected_code is
195 supplied, a urllib.error.HTTPError is raised unless the status code
196 matches expected_code.
197 """
198 data = data or {}
199 headers = headers or {}
200 proxies = {'https': proxies['https']} if proxies.get('https') else {}
201 opener = urllib.request.build_opener(
202 urllib.request.HTTPSHandler,
203 urllib.request.ProxyHandler(proxies),
204 urllib.request.HTTPRedirectHandler,
205 )
206 req = urllib.request.Request(
207 url,
208 data=urllib.parse.urlencode(data).encode('ascii'),
209 headers=headers,
210 )
211 resp = opener.open(req)
212 code = resp.getcode()
213 if expected_code is not None and code != expected_code:
214 raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp)
215 payload = resp.read()
216 try:
217 payload = gzip.decompress(payload)
218 except OSError:
219 pass
220 finally:
221 payload = payload.decode('utf-8')
222 return code, payload
223
224
225 def unwrap(text):
226 """Unwrap text."""
227 lines = text.split('\n')
228 result = ''
229 for i in range(len(lines) - 1):
230 result += lines[i]
231 if not lines[i]:
232 # Paragraph break
233 result += '\n\n'
234 elif lines[i + 1]:
235 # Next line is not paragraph break, add space
236 result += ' '
237 # Handle last line
238 result += lines[-1] if lines[-1] else '\n'
239 return result
240
241
242 def check_stdout_encoding():
243 """Make sure stdout encoding is utf-8.
244
245 If not, print error message and instructions, then exit with
246 status 1.
247
248 This function is a no-op on win32 because encoding on win32 is
249 messy, and let's just hope for the best. /s
250 """
251 if sys.platform == 'win32':
252 return
253
254 # Use codecs.lookup to resolve text encoding alias
255 encoding = codecs.lookup(sys.stdout.encoding).name
256 if encoding != 'utf-8':
257 locale_lang, locale_encoding = locale.getlocale()
258 if locale_lang is None:
259 locale_lang = '<unknown>'
260 if locale_encoding is None:
261 locale_encoding = '<unknown>'
262 ioencoding = os.getenv('PYTHONIOENCODING', 'not set')
263 sys.stderr.write(unwrap(textwrap.dedent("""\
264 stdout encoding '{encoding}' detected. ddgr requires utf-8 to
265 work properly. The wrong encoding may be due to a non-UTF-8
266 locale or an improper PYTHONIOENCODING. (For the record, your
267 locale language is {locale_lang} and locale encoding is
268 {locale_encoding}; your PYTHONIOENCODING is {ioencoding}.)
269
270 Please set a UTF-8 locale (e.g., en_US.UTF-8) or set
271 PYTHONIOENCODING to utf-8.
272 """.format(
273 encoding=encoding,
274 locale_lang=locale_lang,
275 locale_encoding=locale_encoding,
276 ioencoding=ioencoding,
277 ))))
278 sys.exit(1)
279
280
281 def printerr(msg):
282 """Print message, verbatim, to stderr.
283
284 ``msg`` could be any stringifiable value.
285 """
286 print(msg, file=sys.stderr)
287
288
289 # Monkeypatch textwrap for CJK wide characters.
290 def monkeypatch_textwrap_for_cjk():
291 try:
292 if textwrap.wrap.patched:
293 return
294 except AttributeError:
295 pass
296 psl_textwrap_wrap = textwrap.wrap
297
298 def textwrap_wrap(text, width=70, **kwargs):
299 width = max(width, 2)
300 # We first add a U+0000 after each East Asian Fullwidth or East
301 # Asian Wide character, then fill to width - 1 (so that if a NUL
302 # character ends up on a new line, we still have one last column
303 # to spare for the preceding wide character). Finally we strip
304 # all the NUL characters.
305 #
306 # East Asian Width: https://www.unicode.org/reports/tr11/
307 return [
308 line.replace('\0', '')
309 for line in psl_textwrap_wrap(
310 ''.join(
311 ch + '\0' if unicodedata.east_asian_width(ch) in ('F', 'W') else ch
312 for ch in unicodedata.normalize('NFC', text)
313 ),
314 width=width - 1,
315 **kwargs
316 )
317 ]
318
319 def textwrap_fill(text, width=70, **kwargs):
320 return '\n'.join(textwrap_wrap(text, width=width, **kwargs))
321 textwrap.wrap = textwrap_wrap
322 textwrap.fill = textwrap_fill
323 textwrap.wrap.patched = True
324 textwrap.fill.patched = True
325
326
327 monkeypatch_textwrap_for_cjk()
328
329
330 # Classes
331
332 class DdgUrl:
333 """
334 This class constructs the DuckDuckGo Search/News URL.
335
336 This class is modeled on urllib.parse.ParseResult for familiarity,
337 which means it supports reading of all six attributes -- scheme,
338 netloc, path, params, query, fragment -- of
339 urllib.parse.ParseResult, as well as the geturl() method.
340
341 However, the attributes (properties) and methods listed below should
342 be the preferred methods of access to this class.
343
344 Parameters
345 ----------
346 opts : dict or argparse.Namespace, optional
347 See the ``opts`` parameter of `update`.
348
349 Other Parameters
350 ----------------
351 See "Other Parameters" of `update`.
352
353 Attributes
354 ----------
355 hostname : str
356 Read-write property.
357 keywords : str or list of strs
358 Read-write property.
359 news : bool
360 Read-only property.
361 url : str
362 Read-only property.
363
364 Methods
365 -------
366 full()
367 update(opts=None, **kwargs)
368 set_queries(**kwargs)
369 unset_queries(*args)
370 next_page()
371 prev_page()
372 first_page()
373
374 """
375
376 def __init__(self, opts=None, **kwargs):
377 self.scheme = 'https'
378 # self.netloc is a calculated property
379 self.path = '/html/'
380 self.params = ''
381 # self.query is a calculated property
382 self.fragment = ''
383
384 self._duration = '' # duration as day, week, month or unlimited
385 self._region = '' # Region code
386 self._qrycnt = 0 # Number of search results fetched in most recent query
387 self._curindex = 1 # Index of total results in pages fetched so far + 1
388 self._page = 0 # Current page number
389 self._keywords = []
390 self._sites = None
391 self._safe = 1 # Safe search parameter value
392 self.np_prev = '' # nextParams from last html page Previous button
393 self.np_next = '' # nextParams from last html page Next button
394 self.vqd = '' # vqd parameter (from next/prev button)
395 self._query_dict = {
396 }
397 self.update(opts, **kwargs)
398
399 def __str__(self):
400 return self.url
401
402 @property
403 def url(self):
404 """The full DuckDuckGo URL you want."""
405 return self.full()
406
407 @property
408 def hostname(self):
409 """The hostname."""
410 return self.netloc
411
412 @hostname.setter
413 def hostname(self, hostname):
414 self.netloc = hostname
415
416 @property
417 def keywords(self):
418 """The keywords, either a str or a list of strs."""
419 return self._keywords
420
421 @keywords.setter
422 def keywords(self, keywords):
423 self._keywords = keywords
424
425 @property
426 def news(self):
427 """Whether the URL is for DuckDuckGo News."""
428 return 'tbm' in self._query_dict and self._query_dict['tbm'] == 'nws'
429
430 def full(self):
431 """Return the full URL.
432
433 Returns
434 -------
435 str
436
437 """
438 q = ''
439 if self._keywords:
440 if isinstance(self._keywords, list):
441 q += '+'.join(list(self._keywords))
442 else:
443 q += self._keywords
444
445 url = (self.scheme + ':') if self.scheme else ''
446 url += '//' + self.netloc + '/?q=' + q
447 return url
448
449 def update(self, opts=None, **kwargs):
450 """Update the URL with the given options.
451
452 Parameters
453 ----------
454 opts : dict or argparse.Namespace, optional
455 Carries options that affect the DuckDuckGo Search/News URL. The
456 list of currently recognized option keys with expected value
457 types:
458
459 keywords: str or list of strs
460 num: int
461
462 Other Parameters
463 ----------------
464 kwargs
465 The `kwargs` dict extends `opts`, that is, options can be
466 specified either way, in `opts` or as individual keyword
467 arguments.
468
469 """
470
471 if opts is None:
472 opts = {}
473 if hasattr(opts, '__dict__'):
474 opts = opts.__dict__
475 opts.update(kwargs)
476
477 if 'keywords' in opts:
478 self._keywords = opts['keywords']
479 self._duration = opts['duration']
480 if 'region' in opts:
481 self._region = opts['region']
482 if 'num' in opts:
483 self._qrycnt = 0
484 if 'sites' in opts:
485 self._sites = opts['sites']
486 if 'unsafe' in opts and opts['unsafe']:
487 self._safe = -2
488
489 def set_queries(self, **kwargs):
490 """Forcefully set queries outside the normal `update` mechanism.
491
492 Other Parameters
493 ----------------
494 kwargs
495 Arbitrary key value pairs to be set in the query string. All
496 keys and values should be stringifiable.
497
498 Note that certain keys, e.g., ``q``, have their values
499 constructed on the fly, so setting those has no actual
500 effect.
501
502 """
503 for k, v in kwargs.items():
504 self._query_dict[k] = v
505
506 def unset_queries(self, *args):
507 """Forcefully unset queries outside the normal `update` mechanism.
508
509 Other Parameters
510 ----------------
511 args
512 Arbitrary keys to be unset. No exception is raised if a key
513 does not exist in the first place.
514
515 Note that certain keys, e.g., ``q``, are always included in
516 the resulting URL, so unsetting those has no actual effect.
517
518 """
519 for k in args:
520 self._query_dict.pop(k, None)
521
522 def next_page(self):
523 """Navigate to the next page."""
524 self._page = self._page + 1
525
526 if self._curindex > 0:
527 self._curindex = self._curindex + self._qrycnt
528 else:
529 self._curindex = -self._curindex
530
531 def prev_page(self):
532 """Navigate to the previous page.
533
534 Raises
535 ------
536 ValueError
537 If already at the first page (``page=0`` in the current
538 query string).
539
540 """
541 if self._page == 0:
542 raise ValueError('Already at the first page.')
543
544 self._page = self._page - 1
545
546 if self._curindex > 0:
547 self._curindex = -self._curindex # A negative index is used when fetching previous page
548 else:
549 self._curindex = self._curindex + self._qrycnt
550
551 def first_page(self):
552 """Navigate to the first page.
553
554 Raises
555 ------
556 ValueError
557 If already at the first page (``page=0`` in the current
558 query string).
559
560 """
561 if self._page == 0:
562 raise ValueError('Already at the first page.')
563 self._page = 0
564 self._qrycnt = 0
565 self._curindex = 1
566
567 @property
568 def netloc(self):
569 """The hostname."""
570 return 'duckduckgo.com'
571
572 def query(self):
573 """The query string."""
574 qd = {}
575 qd.update(self._query_dict)
576 qd['duration'] = self._duration
577 qd['region'] = self._region
578 qd['curindex'] = self._curindex
579 qd['page'] = self._page
580 qd['safe'] = self._safe
581 if self._curindex < 0:
582 qd['nextParams'] = self.np_prev
583 else:
584 qd['nextParams'] = self.np_next
585 qd['vqd'] = self.vqd
586
587 # Construct the q query
588 q = ''
589 keywords = self._keywords
590 sites = self._sites
591 if keywords:
592 if isinstance(keywords, list):
593 q += ' '.join(list(keywords))
594 else:
595 q += keywords
596 if sites:
597 q += ' site:' + ','.join(urllib.parse.quote_plus(site) for site in sites)
598 qd['q'] = q
599
600 return qd
601
602 def update_num(self, count):
603 self._qrycnt = count
604
605
606 class DdgAPIUrl:
607 """
608 This class constructs the DuckDuckGo Instant Answer API URL.
609
610 Attributes
611 ----------
612 hostname : str
613 Read-write property.
614 keywords : str or list of strs
615 Read-write property.
616 url : str
617 Read-only property.
618 netloc : str
619 Read-only property.
620
621 Methods
622 -------
623 full()
624
625 """
626
627 def __init__(self, keywords):
628 self.scheme = 'https'
629 self.path = '/'
630 self.params = ''
631 self._format = 'format=json'
632 self._keywords = keywords
633
634 def __str__(self):
635 return self.url
636
637 @property
638 def url(self):
639 """The full DuckDuckGo URL you want."""
640 return self.full()
641
642 @property
643 def hostname(self):
644 """The hostname."""
645 return self.netloc
646
647 @hostname.setter
648 def hostname(self, hostname):
649 self.netloc = hostname
650
651 @property
652 def keywords(self):
653 """The keywords, either a str or a list of strs."""
654 return self._keywords
655
656 @keywords.setter
657 def keywords(self, keywords):
658 self._keywords = keywords
659
660 @property
661 def netloc(self):
662 """The hostname."""
663 return 'api.duckduckgo.com'
664
665 def full(self):
666 """Return the full URL.
667
668 Returns
669 -------
670 str
671
672 """
673 q = ''
674 if self._keywords:
675 if isinstance(self._keywords, list):
676 q += '+'.join(list(self._keywords))
677 else:
678 q += self._keywords
679
680 url = (self.scheme + ':') if self.scheme else ''
681 url += '//' + self.netloc + '/?q=' + q + "&" + self._format
682 return url
683
684
685 class DDGConnectionError(Exception):
686 pass
687
688
689 class DdgConnection:
690 """
691 This class facilitates connecting to and fetching from DuckDuckGo.
692
693 Parameters
694 ----------
695 See http.client.HTTPSConnection for documentation of the
696 parameters.
697
698 Raises
699 ------
700 DDGConnectionError
701
702 Methods
703 -------
704 fetch_page(url)
705
706 """
707
708 def __init__(self, proxy=None, ua=''):
709 self._u = 'https://html.duckduckgo.com/html'
710
711 self._proxies = {
712 'https': proxy if proxy is not None else (os.getenv('https_proxy')
713 if os.getenv('https_proxy') is not None
714 else os.getenv('HTTPS_PROXY'))
715 }
716 self._ua = ua
717
718 def fetch_page(self, url):
719 """Fetch a URL.
720
721 Allows one reconnection and one redirection before failing and
722 raising DDGConnectionError.
723
724 Parameters
725 ----------
726 url : str
727 The URL to fetch, relative to the host.
728
729 Raises
730 ------
731 DDGConnectionError
732 When not getting HTTP 200 even after the allowed one
733 reconnection and/or one redirection, or when DuckDuckGo is
734 blocking query due to unsual activity.
735
736 Returns
737 -------
738 str
739 Response payload, gunzipped (if applicable) and decoded (in UTF-8).
740
741 """
742 dic = url.query()
743 page = dic['page']
744 LOGDBG('q:%s, region:%s, page:%d, curindex:%d, safe:%d', dic['q'], dic['region'], page, dic['curindex'], dic['safe'])
745 LOGDBG('nextParams:%s', dic['nextParams'])
746 LOGDBG('vqd:%s', dic['vqd'])
747 LOGDBG('proxy:%s', self._proxies)
748 LOGDBG('ua:%s', self._ua)
749
750 try:
751 if page == 0:
752 _, r = https_post(self._u,
753 headers={
754 'Accept-Encoding': 'gzip',
755 'User-Agent': self._ua,
756 'DNT': '1',
757 },
758 data={
759 'q': dic['q'],
760 'b': '',
761 'df': dic['duration'],
762 'kf': '-1',
763 'kh': '1',
764 'kl': dic['region'],
765 'kp': dic['safe'],
766 'k1': '-1',
767 },
768 proxies=self._proxies,
769 expected_code=200)
770 else:
771 _, r = https_post(self._u,
772 headers={
773 'Accept-Encoding': 'gzip',
774 'User-Agent': self._ua,
775 'DNT': '1',
776 },
777 data={
778 'q': dic['q'], # The query string
779 's': str(50 * (page - 1) + 30), # Page index
780 'nextParams': dic['nextParams'], # nextParams from last visited page
781 'v': 'l',
782 'o': 'json',
783 'dc': str(dic['curindex']), # Start from total fetched result index
784 'df': dic['duration'],
785 'api': '/d.js',
786 'kf': '-1', # Disable favicons
787 'kh': '1', # HTTPS always ON
788 'kl': dic['region'], # Region code
789 'kp': dic['safe'], # Safe search
790 'k1': '-1', # Advertisements off
791 'vqd': dic['vqd'], # vqd string from button
792 },
793 proxies=self._proxies,
794 expected_code=200)
795 except Exception as e:
796 LOGERR(e)
797 return None
798
799 return r
800
801
802 def annotate_tag(annotated_starttag_handler):
803 # See parser logic within the DdgParser class for documentation.
804 #
805 # annotated_starttag_handler(self, tag: str, attrsdict: dict) -> annotation
806 # Returns: HTMLParser.handle_starttag(self, tag: str, attrs: list) -> None
807
808 def handler(self, tag, attrs):
809 attrs = dict(attrs)
810 annotation = annotated_starttag_handler(self, tag, attrs)
811 self.insert_annotation(tag, annotation)
812
813 return handler
814
815
816 def retrieve_tag_annotation(annotated_endtag_handler):
817 # See parser logic within the DdgParser class for documentation.
818 #
819 # annotated_endtag_handler(self, tag: str, annotation) -> None
820 # Returns: HTMLParser.handle_endtag(self, tag: str) -> None
821
822 def handler(self, tag):
823 try:
824 annotation = self.tag_annotations[tag].pop()
825 except IndexError:
826 # Malformed HTML -- more close tags than open tags
827 annotation = None
828 annotated_endtag_handler(self, tag, annotation)
829
830 return handler
831
832
833 class DdgParser(html.parser.HTMLParser):
834 """The members of this class parse the result HTML
835 page fetched from DuckDuckGo server for a query.
836
837 The custom parser looks for tags enclosing search
838 results and extracts the URL, title and text for
839 each search result.
840
841 After parsing the complete HTML page results are
842 returned in a list of objects of class Result.
843 """
844
845 # Parser logic:
846 #
847 # - Guiding principles:
848 #
849 # 1. Tag handlers are contextual;
850 #
851 # 2. Contextual starttag and endtag handlers should come in pairs
852 # and have a clear hierarchy;
853 #
854 # 3. starttag handlers should only yield control to a pair of
855 # child handlers (that is, one level down the hierarchy), and
856 # correspondingly, endtag handlers should only return control
857 # to the parent (that is, the pair of handlers that gave it
858 # control in the first place).
859 #
860 # Principle 3 is meant to enforce a (possibly implicit) stack
861 # structure and thus prevent careless jumps that result in what's
862 # essentially spaghetti code with liberal use of GOTOs.
863 #
864 # - HTMLParser.handle_endtag gives us a bare tag name without
865 # context, which is not good for enforcing principle 3 when we
866 # have, say, nested div tags.
867 #
868 # In order to precisely identify the matching opening tag, we
869 # maintain a stack for each tag name with *annotations*. Important
870 # opening tags (e.g., the ones where child handlers are
871 # registered) can be annotated so that when we can watch for the
872 # annotation in the endtag handler, and when the appropriate
873 # annotation is popped, we perform the corresponding action (e.g.,
874 # switch back to old handlers).
875 #
876 # To facilitate this, each starttag handler is decorated with
877 # @annotate_tag, which accepts a return value that is the
878 # annotation (None by default), and additionally converts attrs to
879 # a dict, which is much easier to work with; and each endtag
880 # handler is decorated with @retrieve_tag_annotation which sends
881 # an additional parameter that is the retrieved annotation to the
882 # handler.
883 #
884 # Note that some of our tag annotation stacks leak over time: this
885 # happens to tags like <img> and <hr> which are not
886 # closed. However, these tags play no structural role, and come
887 # only in small quantities, so it's not really a problem.
888 #
889 # - All textual data (result title, result abstract, etc.) are
890 # processed through a set of shared handlers. These handlers store
891 # text in a shared buffer self.textbuf which can be retrieved and
892 # cleared at appropriate times.
893 #
894 # Data (including charrefs and entityrefs) are ignored initially,
895 # and when data needs to be recorded, the start_populating_textbuf
896 # method is called to register the appropriate data, charref and
897 # entityref handlers so that they append to self.textbuf. When
898 # recording ends, pop_textbuf should be called to extract the text
899 # and clear the buffer. stop_populating_textbuf returns the
900 # handlers to their pristine state (ignoring data).
901 #
902 # Methods:
903 # - start_populating_textbuf(self, data_transformer: Callable[[str], str]) -> None
904 # - pop_textbuf(self) -> str
905 # - stop_populating_textbuf(self) -> None
906 #
907 # - Outermost starttag and endtag handler methods: root_*. The whole
908 # parser starts and ends in this state.
909 #
910 # - Each result is wrapped in a <div> tag with class "links_main".
911 #
912 # <!-- within the scope of root_* -->
913 # <div class="links_main"> <!-- annotate as 'result', hand over to result_* -->
914 # </div> <!-- hand back to root_*, register result -->
915 #
916 # - For each result, the first <h2> tag with class "result__title" contains the
917 # hyperlinked title.
918 #
919 # <!-- within the scope of result_* -->
920 # <h2 class="result__title"> <!-- annotate as 'title', hand over to title_* -->
921 # </h2> <!-- hand back to result_* -->
922 #
923 # - Abstracts are within the scope of <div> tag with class "links_main". Links in
924 # abstract are ignored as they are available within <h2> tag.
925 #
926 # <!-- within the scope of result_* -->
927 # <a class="result__snippet"> <!-- annotate as 'abstract', hand over to abstract_* -->
928 # </a> <!-- hand back to result_* -->
929 #
930 # - Each title looks like
931 #
932 # <h2 class="result__title">
933 # <!-- within the scope of title_* -->
934 # <a href="result url"> <!-- register self.url, annotate as 'title_link',
935 # start_populating_textbuf -->
936 # result title
937 # <span> <!-- filetype (optional), annotate as title_filetype,
938 # start_populating_textbuf -->
939 # file type (e.g. [PDF])
940 # </span> <!-- stop_populating_textbuf, update self.filetype,
941 # start_populating_tetbuf -->
942 # </a> <!-- stop_populating_textbuf, pop to self.title
943 # prepend self.filetype, if available -->
944 # </h2>
945
946 def __init__(self, offset=0):
947 html.parser.HTMLParser.__init__(self)
948
949 self.title = ''
950 self.url = ''
951 self.abstract = ''
952 self.filetype = ''
953
954 self.results = []
955 self.index = offset
956 self.textbuf = ''
957 self.click_result = ''
958 self.tag_annotations = {}
959 self.np_prev_button = ''
960 self.np_next_button = ''
961 self.npfound = False # First next params found
962 self.set_handlers_to('root')
963 self.vqd = '' # vqd returned from button, required for search query to get next set of results
964
965 # Tag handlers
966
967 @annotate_tag
968 def root_start(self, tag, attrs):
969 if tag == 'div':
970 if 'zci__result' in self.classes(attrs):
971 self.start_populating_textbuf()
972 return 'click_result'
973
974 if 'links_main' in self.classes(attrs):
975 # Initialize result field registers
976 self.title = ''
977 self.url = ''
978 self.abstract = ''
979 self.filetype = ''
980
981 self.set_handlers_to('result')
982 return 'result'
983
984 if 'nav-link' in self.classes(attrs):
985 self.set_handlers_to('input')
986 return 'input'
987 return ''
988
989 @retrieve_tag_annotation
990 def root_end(self, tag, annotation):
991 if annotation == 'click_result':
992 self.stop_populating_textbuf()
993 self.click_result = self.pop_textbuf()
994 self.set_handlers_to('root')
995
996 @annotate_tag
997 def result_start(self, tag, attrs):
998 if tag == 'h2' and 'result__title' in self.classes(attrs):
999 self.set_handlers_to('title')
1000 return 'title'
1001
1002 if tag == 'a' and 'result__snippet' in self.classes(attrs) and 'href' in attrs:
1003 self.start_populating_textbuf()
1004 return 'abstract'
1005
1006 return ''
1007
1008 @retrieve_tag_annotation
1009 def result_end(self, tag, annotation):
1010 if annotation == 'abstract':
1011 self.stop_populating_textbuf()
1012 self.abstract = self.pop_textbuf()
1013 elif annotation == 'result':
1014 if self.url:
1015 self.index += 1
1016 result = Result(self.index, self.title, self.url, self.abstract, None)
1017 self.results.append(result)
1018 self.set_handlers_to('root')
1019
1020 @annotate_tag
1021 def title_start(self, tag, attrs):
1022 if tag == 'span':
1023 # Print a space after the filetype indicator
1024 self.start_populating_textbuf(lambda text: '[' + text + ']')
1025 return 'title_filetype'
1026
1027 if tag == 'a' and 'href' in attrs:
1028 # Skip 'News for', 'Images for' search links
1029 if attrs['href'].startswith('/search'):
1030 return ''
1031
1032 self.url = attrs['href']
1033 try:
1034 start = self.url.index('?q=') + len('?q=')
1035 end = self.url.index('&sa=', start)
1036 self.url = urllib.parse.unquote_plus(self.url[start:end])
1037 except ValueError:
1038 pass
1039 self.start_populating_textbuf()
1040 return 'title_link'
1041
1042 return ''
1043
1044 @retrieve_tag_annotation
1045 def title_end(self, tag, annotation):
1046 if annotation == 'title_filetype':
1047 self.stop_populating_textbuf()
1048 self.filetype = self.pop_textbuf()
1049 self.start_populating_textbuf()
1050 elif annotation == 'title_link':
1051 self.stop_populating_textbuf()
1052 self.title = self.pop_textbuf()
1053 if self.filetype != '':
1054 self.title = self.filetype + self.title
1055 elif annotation == 'title':
1056 self.set_handlers_to('result')
1057
1058 @annotate_tag
1059 def abstract_start(self, tag, attrs):
1060 if tag == 'span' and 'st' in self.classes(attrs):
1061 self.start_populating_textbuf()
1062 return 'abstract_text'
1063 return ''
1064
1065 @retrieve_tag_annotation
1066 def abstract_end(self, tag, annotation):
1067 if annotation == 'abstract_text':
1068 self.stop_populating_textbuf()
1069 self.abstract = self.pop_textbuf()
1070 elif annotation == 'abstract':
1071 self.set_handlers_to('result')
1072
1073 @annotate_tag
1074 def input_start(self, tag, attrs):
1075 if tag == 'input' and 'name' in attrs:
1076 if attrs['name'] == 'nextParams':
1077 # The previous button always shows before next button
1078 # If there's only 1 button (page 1), it's the next button
1079 if self.npfound is True:
1080 self.np_prev_button = self.np_next_button
1081 else:
1082 self.npfound = True
1083
1084 self.np_next_button = attrs['value']
1085 return
1086 if attrs['name'] == 'vqd' and attrs['value'] != '':
1087 # vqd required to be passed for next/previous search page
1088 self.vqd = attrs['value']
1089 return
1090
1091 @retrieve_tag_annotation
1092 def input_end(self, tag, annotation):
1093 return
1094
1095 # Generic methods
1096
1097 # Set handle_starttag to SCOPE_start, and handle_endtag to SCOPE_end.
1098 def set_handlers_to(self, scope):
1099 self.handle_starttag = getattr(self, scope + '_start')
1100 self.handle_endtag = getattr(self, scope + '_end')
1101
1102 def insert_annotation(self, tag, annotation):
1103 if tag not in self.tag_annotations:
1104 self.tag_annotations[tag] = []
1105 self.tag_annotations[tag].append(annotation)
1106
1107 def start_populating_textbuf(self, data_transformer=None):
1108 if data_transformer is None:
1109 # Record data verbatim
1110 self.handle_data = self.record_data
1111 else:
1112 def record_transformed_data(data):
1113 self.textbuf += data_transformer(data)
1114
1115 self.handle_data = record_transformed_data
1116
1117 self.handle_entityref = self.record_entityref
1118 self.handle_charref = self.record_charref
1119
1120 def pop_textbuf(self):
1121 text = self.textbuf
1122 self.textbuf = ''
1123 return text
1124
1125 def stop_populating_textbuf(self):
1126 self.handle_data = lambda data: None
1127 self.handle_entityref = lambda ref: None
1128 self.handle_charref = lambda ref: None
1129
1130 def record_data(self, data):
1131 self.textbuf += data
1132
1133 def record_entityref(self, ref):
1134 try:
1135 self.textbuf += chr(html.entities.name2codepoint[ref])
1136 except KeyError:
1137 # Entity name not found; most likely rather sloppy HTML
1138 # where a literal ampersand is not escaped; For instance,
1139 # containing the following tag
1140 #
1141 # <p class="_e4b"><a href="...">expected market return s&p 500</a></p>
1142 #
1143 # where &p is interpreted by HTMLParser as an entity (this
1144 # behaviour seems to be specific to Python 2.7).
1145 self.textbuf += '&' + ref
1146
1147 def record_charref(self, ref):
1148 if ref.startswith('x'):
1149 char = chr(int(ref[1:], 16))
1150 else:
1151 char = chr(int(ref))
1152 self.textbuf += char
1153
1154 @staticmethod
1155 def classes(attrs):
1156 """Get tag's classes from its attribute dict."""
1157 return attrs.get('class', '').split()
1158
1159 def error(self, message):
1160 raise NotImplementedError("subclasses of ParserBase must override error()")
1161
1162
1163 Colors = collections.namedtuple('Colors', 'index, title, url, metadata, abstract, prompt, reset')
1164
1165
1166 class Result:
1167 """
1168 Container for one search result, with output helpers.
1169
1170 Parameters
1171 ----------
1172 index : int or str
1173 title : str
1174 url : str
1175 abstract : str
1176 metadata : str, optional
1177 Only applicable to DuckDuckGo News results, with publisher name and
1178 publishing time.
1179
1180 Attributes
1181 ----------
1182 index : str
1183 title : str
1184 url : str
1185 abstract : str
1186 metadata : str or None
1187
1188 Class Variables
1189 ---------------
1190 colors : str
1191
1192 Methods
1193 -------
1194 print()
1195 jsonizable_object()
1196 urltable()
1197
1198 """
1199
1200 # Class variables
1201 colors = None
1202 urlexpand = False
1203
1204 def __init__(self, index, title, url, abstract, metadata=None):
1205 index = str(index)
1206 self.index = index
1207 self.title = title
1208 self.url = url
1209 self.abstract = abstract
1210 self.metadata = metadata
1211
1212 self._urltable = {index: url}
1213
1214 def _print_title_and_url(self, index, title, url):
1215 indent = INDENT - 2
1216 colors = self.colors
1217
1218 if not self.urlexpand:
1219 url = '[' + urllib.parse.urlparse(url).netloc + ']'
1220
1221 if colors:
1222 # Adjust index to print result index clearly
1223 print(" %s%-*s%s" % (colors.index, indent, index + '.', colors.reset), end='')
1224 if not self.urlexpand:
1225 print(' ' + colors.title + title + colors.reset + ' ' + colors.url + url + colors.reset)
1226 else:
1227 print(' ' + colors.title + title + colors.reset)
1228 print(' ' * (INDENT) + colors.url + url + colors.reset)
1229 else:
1230 if self.urlexpand:
1231 print(' %-*s %s' % (indent, index + '.', title))
1232 print(' %s%s' % (' ' * (indent + 1), url))
1233 else:
1234 print(' %-*s %s %s' % (indent, index + '.', title, url))
1235
1236 def _print_metadata_and_abstract(self, abstract, metadata=None):
1237 colors = self.colors
1238 try:
1239 columns, _ = os.get_terminal_size()
1240 except OSError:
1241 columns = 0
1242
1243 if metadata:
1244 if colors:
1245 print(' ' * INDENT + colors.metadata + metadata + colors.reset)
1246 else:
1247 print(' ' * INDENT + metadata)
1248
1249 if colors:
1250 print(colors.abstract, end='')
1251 if columns > INDENT + 1:
1252 # Try to fill to columns
1253 fillwidth = columns - INDENT - 1
1254 for line in textwrap.wrap(abstract.replace('\n', ''), width=fillwidth):
1255 print('%s%s' % (' ' * INDENT, line))
1256 print('')
1257 else:
1258 print('%s\n' % abstract.replace('\n', ' '))
1259 if colors:
1260 print(colors.reset, end='')
1261
1262 def print(self):
1263 """Print the result entry."""
1264
1265 self._print_title_and_url(self.index, self.title, self.url)
1266 self._print_metadata_and_abstract(self.abstract, metadata=self.metadata)
1267
1268 def print_paginated(self, display_index):
1269 """Print the result entry with custom index."""
1270
1271 self._print_title_and_url(display_index, self.title, self.url)
1272 self._print_metadata_and_abstract(self.abstract, metadata=self.metadata)
1273
1274 def jsonizable_object(self):
1275 """Return a JSON-serializable dict representing the result entry."""
1276 obj = {
1277 'title': self.title,
1278 'url': self.url,
1279 'abstract': self.abstract
1280 }
1281 if self.metadata:
1282 obj['metadata'] = self.metadata
1283 return obj
1284
1285 def urltable(self):
1286 """Return a index-to-URL table for the current result.
1287
1288 Normally, the table contains only a single entry, but when the result
1289 contains sitelinks, all sitelinks are included in this table.
1290
1291 Returns
1292 -------
1293 dict
1294 A dict mapping indices (strs) to URLs (also strs).
1295
1296 """
1297 return self._urltable
1298
1299
1300 class DdgCmdException(Exception):
1301 pass
1302
1303
1304 class NoKeywordsException(DdgCmdException):
1305 pass
1306
1307
1308 def require_keywords(method):
1309 # Require keywords to be set before we run a DdgCmd method. If
1310 # no keywords have been set, raise a NoKeywordsException.
1311 @functools.wraps(method)
1312 def enforced_method(self, *args, **kwargs):
1313 if not self.keywords:
1314 raise NoKeywordsException('No keywords.')
1315 method(self, *args, **kwargs)
1316
1317 return enforced_method
1318
1319
1320 def no_argument(method):
1321 # Normalize a do_* method of DdgCmd that takes no argument to
1322 # one that takes an arg, but issue a warning when an nonempty
1323 # argument is given.
1324 @functools.wraps(method)
1325 def enforced_method(self, arg):
1326 if arg:
1327 method_name = arg.__name__
1328 command_name = method_name[3:] if method_name.startswith('do_') else method_name
1329 LOGGER.warning("Argument to the '%s' command ignored.", command_name)
1330 method(self)
1331
1332 return enforced_method
1333
1334
1335 class DdgCmd:
1336 """
1337 Command line interpreter and executor class for ddgr.
1338
1339 Inspired by PSL cmd.Cmd.
1340
1341 Parameters
1342 ----------
1343 opts : argparse.Namespace
1344 Options and/or arguments.
1345
1346 Attributes
1347 ----------
1348 options : argparse.Namespace
1349 Options that are currently in effect. Read-only attribute.
1350 keywords : str or list or strs
1351 Current keywords. Read-only attribute
1352
1353 Methods
1354 -------
1355 fetch()
1356 display_instant_answer(json_output=False)
1357 display_results(prelude='\n', json_output=False)
1358 fetch_and_display(prelude='\n', json_output=False)
1359 read_next_command()
1360 help()
1361 cmdloop()
1362
1363 """
1364
1365 def __init__(self, opts, ua):
1366 super().__init__()
1367 self.cmd = ''
1368 self.index = 0
1369 self._opts = opts
1370
1371 self._ddg_url = DdgUrl(opts)
1372 proxy = opts.proxy if hasattr(opts, 'proxy') else None
1373 self._conn = DdgConnection(proxy=proxy, ua=ua)
1374
1375 self.results = []
1376 self.instant_answer = ''
1377 self._urltable = {}
1378
1379 colors = self.colors
1380 message = 'ddgr (? for help)'
1381 self.prompt = ((colors.prompt + message + colors.reset + ' ')
1382 if (colors and os.getenv('DISABLE_PROMPT_COLOR') is None) else (message + ': '))
1383
1384 @property
1385 def options(self):
1386 """Current options."""
1387 return self._opts
1388
1389 @property
1390 def keywords(self):
1391 """Current keywords."""
1392 return self._ddg_url.keywords
1393
1394 @require_keywords
1395 def fetch(self):
1396 """Fetch a page and parse for results.
1397
1398 Results are stored in ``self.results``.
1399 Instant answer is stored in ``self.instant_answer``.
1400
1401 Raises
1402 ------
1403 DDGConnectionError
1404
1405 See Also
1406 --------
1407 fetch_and_display
1408
1409 """
1410 # This method also sets self._urltable.
1411 page = self._conn.fetch_page(self._ddg_url)
1412
1413 if page is None:
1414 return
1415
1416 if LOGGER.isEnabledFor(logging.DEBUG):
1417 fd, tmpfile = tempfile.mkstemp(prefix='ddgr-response-')
1418 os.close(fd)
1419 with open(tmpfile, 'w', encoding='utf-8') as fp:
1420 fp.write(page)
1421 LOGDBG("Response body written to '%s'.", tmpfile)
1422
1423 if self._opts.num:
1424 _index = len(self._urltable)
1425 else:
1426 _index = 0
1427 self._urltable = {}
1428
1429 parser = DdgParser(offset=_index)
1430 parser.feed(page)
1431
1432 if self._opts.num:
1433 self.results.extend(parser.results)
1434 else:
1435 self.results = parser.results
1436
1437 for r in parser.results:
1438 self._urltable.update(r.urltable())
1439
1440 self._ddg_url.np_prev = parser.np_prev_button
1441 self._ddg_url.np_next = parser.np_next_button
1442 self._ddg_url.vqd = parser.vqd
1443
1444 if parser.click_result:
1445 self.instant_answer = parser.click_result.strip()
1446 else:
1447 self.instant_answer = ''
1448
1449 self._ddg_url.update_num(len(parser.results))
1450
1451 @require_keywords
1452 def display_instant_answer(self, json_output=False):
1453 """Display instant answer stored in ``self.instant_answer``.
1454
1455 Parameters
1456 ----------
1457 json_output : bool, optional
1458 Whether to dump results in JSON format. Default is False.
1459
1460 See Also
1461 --------
1462 fetch_and_display
1463
1464 """
1465 if self.index == 0 and self.instant_answer and not json_output:
1466 if self.colors:
1467 print(self.colors.abstract)
1468
1469 try:
1470 columns, _ = os.get_terminal_size()
1471 except OSError:
1472 columns = 0
1473
1474 fillwidth = columns - INDENT
1475 for line in textwrap.wrap(self.instant_answer, width=fillwidth):
1476 print('%s%s' % (' ' * INDENT, line))
1477
1478 if self.colors:
1479 print(self.colors.reset, end='')
1480
1481 if self._opts.reverse:
1482 print('')
1483
1484 @require_keywords
1485 def display_results(self, prelude='\n', json_output=False):
1486 """Display results stored in ``self.results``.
1487
1488 Parameters
1489 ----------
1490 See `fetch_and_display`.
1491
1492 """
1493
1494 if self._opts.num:
1495 results = self.results[self.index:(self.index + self._opts.num)]
1496 else:
1497 results = self.results
1498
1499 if self._opts.reverse:
1500 results.reverse()
1501
1502 if json_output:
1503 # JSON output
1504 results_object = [r.jsonizable_object() for r in results]
1505 print(json.dumps(results_object, indent=2, sort_keys=True, ensure_ascii=False))
1506 elif not results:
1507 print('No results.', file=sys.stderr)
1508 else:
1509 sys.stderr.write(prelude)
1510
1511 if self._opts.num: # Paginated output
1512 for i, r in enumerate(results):
1513 if self._opts.reverse:
1514 r.print_paginated(str(len(results) - i))
1515 else:
1516 r.print_paginated(str(i + 1))
1517 else: # Regular output
1518 for r in results:
1519 r.print()
1520
1521 @require_keywords
1522 def fetch_and_display(self, prelude='\n', json_output=False):
1523 """Fetch a page and display results.
1524
1525 Results are stored in ``self.results``.
1526
1527 Parameters
1528 ----------
1529 prelude : str, optional
1530 A string that is written to stderr before showing actual results,
1531 usually serving as a separator. Default is an empty line.
1532 json_output : bool, optional
1533 Whether to dump results in JSON format. Default is False.
1534
1535 Raises
1536 ------
1537 DDGConnectionError
1538
1539 See Also
1540 --------
1541 fetch
1542 display_instant_answer
1543 display_results
1544
1545 """
1546 self.fetch()
1547 if not self._opts.reverse:
1548 self.display_instant_answer()
1549 self.display_results(prelude=prelude, json_output=json_output)
1550 else:
1551 self.display_results(prelude=prelude, json_output=json_output)
1552 self.display_instant_answer()
1553
1554 def read_next_command(self):
1555 """Show omniprompt and read user command line.
1556
1557 Command line is always stripped, and each consecutive group of
1558 whitespace is replaced with a single space character. If the
1559 command line is empty after stripping, when ignore it and keep
1560 reading. Exit with status 0 if we get EOF or an empty line
1561 (pre-strip, that is, a raw <enter>) twice in a row.
1562
1563 The new command line (non-empty) is stored in ``self.cmd``.
1564
1565 """
1566 enter_count = 0
1567 while True:
1568 try:
1569 cmd = input(self.prompt)
1570 except EOFError:
1571 sys.exit(0)
1572
1573 if not cmd:
1574 enter_count += 1
1575 if enter_count == 2:
1576 # Double <enter>
1577 sys.exit(0)
1578 else:
1579 enter_count = 0
1580
1581 cmd = ' '.join(cmd.split())
1582 if cmd:
1583 self.cmd = cmd
1584 break
1585
1586 @staticmethod
1587 def help():
1588 DdgArgumentParser.print_omniprompt_help(sys.stderr)
1589 printerr('')
1590
1591 @require_keywords
1592 @no_argument
1593 def do_first(self):
1594 if self._opts.num:
1595 if self.index < self._opts.num:
1596 print('Already at the first page.', file=sys.stderr)
1597 else:
1598 self.index = 0
1599 self.display_results()
1600 return
1601
1602 try:
1603 self._ddg_url.first_page()
1604 except ValueError as e:
1605 print(e, file=sys.stderr)
1606 return
1607
1608 self.fetch_and_display()
1609
1610 def do_ddg(self, arg):
1611 if self._opts.num:
1612 self.index = 0
1613 self.results = []
1614 self._urltable = {}
1615 # Update keywords and reconstruct URL
1616 self._opts.keywords = arg
1617 self._ddg_url = DdgUrl(self._opts)
1618 # If there is a Bang, let DuckDuckGo do the work
1619 if arg[0] == '!' or (len(arg) > 1 and arg[1] == '!'):
1620 open_url(self._ddg_url.full())
1621 else:
1622 self.fetch_and_display()
1623
1624 @require_keywords
1625 @no_argument
1626 def do_next(self):
1627 if self._opts.num:
1628 count = len(self.results)
1629 if self._ddg_url._qrycnt == 0 and self.index >= count:
1630 print('No results.', file=sys.stderr)
1631 return
1632
1633 self.index += self._opts.num
1634 if count - self.index < self._opts.num:
1635 self._ddg_url.next_page()
1636 self.fetch_and_display()
1637 else:
1638 self.display_results()
1639 elif self._ddg_url._qrycnt == 0:
1640 # If no results were fetched last time, we have hit the last page already
1641 print('No results.', file=sys.stderr)
1642 else:
1643 self._ddg_url.next_page()
1644 self.fetch_and_display()
1645
1646 def handle_range(self, nav, low, high):
1647 try:
1648 if self._opts.num:
1649 vals = [int(x) + self.index for x in nav.split('-')]
1650 else:
1651 vals = [int(x) for x in nav.split('-')]
1652
1653 if len(vals) != 2:
1654 printerr('Invalid range %s.' % nav)
1655 return
1656
1657 if vals[0] > vals[1]:
1658 vals[0], vals[1] = vals[1], vals[0]
1659
1660 for _id in range(vals[0], vals[1] + 1):
1661 if self._opts.num and _id not in range(low, high):
1662 printerr('Invalid index %s.' % (_id - self.index))
1663 continue
1664
1665 if str(_id) in self._urltable:
1666 open_url(self._urltable[str(_id)])
1667 else:
1668 printerr('Invalid index %s.' % _id)
1669 except ValueError:
1670 printerr('Invalid range %s.' % nav)
1671
1672 @require_keywords
1673 def do_open(self, low, high, *args):
1674 if not args:
1675 printerr('Index or range missing.')
1676 return
1677
1678 for nav in args:
1679 if nav == 'a':
1680 for key, _ in sorted(self._urltable.items()):
1681 if self._opts.num and int(key) not in range(low, high):
1682 continue
1683 open_url(self._urltable[key])
1684 elif nav in self._urltable:
1685 if self._opts.num:
1686 nav = str(int(nav) + self.index)
1687 if int(nav) not in range(low, high):
1688 printerr('Invalid index %s.' % (int(nav) - self.index))
1689 continue
1690 open_url(self._urltable[nav])
1691 elif '-' in nav:
1692 self.handle_range(nav, low, high)
1693 else:
1694 printerr('Invalid index %s.' % nav)
1695
1696 @require_keywords
1697 @no_argument
1698 def do_previous(self):
1699 if self._opts.num:
1700 if self.index < self._opts.num:
1701 print('Already at the first page.', file=sys.stderr)
1702 else:
1703 self.index -= self._opts.num
1704 self.display_results()
1705 return
1706
1707 try:
1708 self._ddg_url.prev_page()
1709 except ValueError as e:
1710 print(e, file=sys.stderr)
1711 return
1712
1713 self.fetch_and_display()
1714
1715 def copy_url(self, idx):
1716 try:
1717 content = self._urltable[str(idx)].encode('utf-8')
1718
1719 # try copying the url to clipboard using native utilities
1720 copier_params = []
1721 if sys.platform.startswith(('linux', 'freebsd', 'openbsd')):
1722 if shutil.which('xsel') is not None:
1723 copier_params = ['xsel', '-b', '-i']
1724 elif shutil.which('xclip') is not None:
1725 copier_params = ['xclip', '-selection', 'clipboard']
1726 elif shutil.which('wl-copy') is not None:
1727 copier_params = ['wl-copy']
1728 # If we're using Termux (Android) use its 'termux-api'
1729 # add-on to set device clipboard.
1730 elif shutil.which('termux-clipboard-set') is not None:
1731 copier_params = ['termux-clipboard-set']
1732 elif sys.platform == 'darwin':
1733 copier_params = ['pbcopy']
1734 elif sys.platform == 'win32':
1735 copier_params = ['clip']
1736 elif sys.platform.startswith('haiku'):
1737 copier_params = ['clipboard', '-i']
1738
1739 if copier_params:
1740 Popen(copier_params, stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL).communicate(content)
1741 return
1742
1743 # If native clipboard utilities are absent, try to use terminal multiplexers
1744 # tmux
1745 if os.getenv('TMUX_PANE'):
1746 copier_params = ['tmux', 'set-buffer']
1747 Popen(copier_params + [content], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL).communicate()
1748 print('URL copied to tmux buffer.')
1749 return
1750
1751 # GNU Screen paste buffer
1752 if os.getenv('STY'):
1753 copier_params = ['screen', '-X', 'readbuf', '-e', 'utf8']
1754 tmpfd, tmppath = tempfile.mkstemp()
1755 try:
1756 with os.fdopen(tmpfd, 'wb') as fp:
1757 fp.write(content)
1758 copier_params.append(tmppath)
1759 Popen(copier_params, stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL).communicate()
1760 finally:
1761 os.unlink(tmppath)
1762 return
1763
1764 printerr('failed to locate suitable clipboard utility')
1765 except Exception as e:
1766 raise NoKeywordsException from e
1767
1768 def cmdloop(self):
1769 """Run REPL."""
1770 if self.keywords:
1771 if self.keywords[0][0] == '!' or (
1772 len(self.keywords[0]) > 1 and self.keywords[0][1] == '!'
1773 ):
1774 open_url(self._ddg_url.full())
1775 else:
1776 self.fetch_and_display()
1777
1778 while True:
1779 self.read_next_command()
1780 # Automatic dispatcher
1781 #
1782 # We can't write a dispatcher for now because that could
1783 # change behaviour of the prompt. However, we have already
1784 # laid a lot of ground work for the dispatcher, e.g., the
1785 # `no_argument' decorator.
1786
1787 _num = self._opts.num
1788 try:
1789 cmd = self.cmd
1790 if cmd == 'f':
1791 self.do_first('')
1792 elif cmd.startswith('d '):
1793 self.do_ddg(cmd[2:])
1794 elif cmd == 'n':
1795 self.do_next('')
1796 elif cmd.startswith('o '):
1797 self.do_open(self.index + 1, self.index + self._opts.num + 1, *cmd[2:].split())
1798 elif cmd.startswith('O '):
1799 open_url.override_text_browser = True
1800 self.do_open(self.index + 1, self.index + self._opts.num + 1, *cmd[2:].split())
1801 open_url.override_text_browser = False
1802 elif cmd == 'p':
1803 self.do_previous('')
1804 elif cmd == 'q':
1805 break
1806 elif cmd == '?':
1807 self.help()
1808 elif _num and cmd.isdigit() and int(cmd) in range(1, _num + 1):
1809 open_url(self._urltable[str(int(cmd) + self.index)])
1810 elif _num == 0 and cmd in self._urltable:
1811 open_url(self._urltable[cmd])
1812 elif self.keywords and cmd.isdigit() and int(cmd) < 100:
1813 printerr('Index out of bound. To search for the number, use d.')
1814 elif cmd == 'x':
1815 Result.urlexpand = not Result.urlexpand
1816 self.display_results()
1817 elif cmd.startswith('c ') and cmd[2:].isdigit():
1818 idx = int(cmd[2:])
1819 if 0 < idx <= min(self._opts.num, len(self._urltable)):
1820 self.copy_url(int(self.index) + idx)
1821 else:
1822 printerr("invalid index")
1823 else:
1824 self.do_ddg(cmd)
1825 except KeyError:
1826 printerr('Index out of bound. To search for the number, use d.')
1827 except NoKeywordsException:
1828 printerr('Initiate a query first.')
1829
1830
1831 class DdgArgumentParser(argparse.ArgumentParser):
1832 """Custom argument parser for ddgr."""
1833
1834 # Print omniprompt help
1835 @staticmethod
1836 def print_omniprompt_help(file=None):
1837 file = sys.stderr if file is None else file
1838 file.write(textwrap.dedent("""
1839 omniprompt keys:
1840 n, p, f fetch the next, prev or first set of search results
1841 index open the result corresponding to index in browser
1842 o [index|range|a ...] open space-separated result indices, ranges or all
1843 O [index|range|a ...] like key 'o', but try to open in a GUI browser
1844 d keywords new DDG search for 'keywords' with original options
1845 should be used to search omniprompt keys and indices
1846 x toggle url expansion
1847 c index copy url to clipboard
1848 q, ^D, double Enter exit ddgr
1849 ? show omniprompt help
1850 * other inputs are considered as new search keywords
1851 """))
1852
1853 # Print information on ddgr
1854 @staticmethod
1855 def print_general_info(file=None):
1856 file = sys.stderr if file is None else file
1857 file.write(textwrap.dedent("""
1858 Version %s
1859 Copyright © 2016-2024 Arun Prakash Jana <[email protected]>
1860 License: GPLv3
1861 Webpage: https://github.com/jarun/ddgr
1862 """ % _VERSION_))
1863
1864 # Augment print_help to print more than synopsis and options
1865 def print_help(self, file=None):
1866 super().print_help(file)
1867 self.print_omniprompt_help(file)
1868 self.print_general_info(file)
1869
1870 # Automatically print full help text on error
1871 def error(self, message):
1872 sys.stderr.write('%s: error: %s\n\n' % (self.prog, message))
1873 self.print_help(sys.stderr)
1874 self.exit(2)
1875
1876 # Type guards
1877 @staticmethod
1878 def positive_int(arg):
1879 """Try to convert a string into a positive integer."""
1880 try:
1881 n = int(arg)
1882 assert n > 0
1883 return n
1884 except (ValueError, AssertionError) as e:
1885 raise argparse.ArgumentTypeError('%s is not a positive integer' % arg) from e
1886
1887 @staticmethod
1888 def nonnegative_int(arg):
1889 """Try to convert a string into a nonnegative integer <= 25."""
1890 try:
1891 n = int(arg)
1892 assert n >= 0
1893 assert n <= 25
1894 return n
1895 except (ValueError, AssertionError) as e:
1896 raise argparse.ArgumentTypeError('%s is not a non-negative integer <= 25' % arg) from e
1897
1898 @staticmethod
1899 def is_duration(arg):
1900 """Check if a string is a valid duration accepted by DuckDuckGo.
1901
1902 A valid duration is of the form dNUM, where d is a single letter h
1903 (hour), d (day), w (week), m (month), or y (year), and NUM is a
1904 non-negative integer.
1905 """
1906 try:
1907 if arg[0] not in ('h', 'd', 'w', 'm', 'y') or int(arg[1:]) < 0:
1908 raise ValueError
1909 except (TypeError, IndexError, ValueError) as e:
1910 raise argparse.ArgumentTypeError('%s is not a valid duration' % arg) from e
1911 return arg
1912
1913 @staticmethod
1914 def is_colorstr(arg):
1915 """Check if a string is a valid color string."""
1916 try:
1917 assert len(arg) == 6
1918 for c in arg:
1919 assert c in COLORMAP
1920 except AssertionError as e:
1921 raise argparse.ArgumentTypeError('%s is not a valid color string' % arg) from e
1922 return arg
1923
1924
1925 # Miscellaneous functions
1926
1927 def python_version():
1928 return '%d.%d.%d' % sys.version_info[:3]
1929
1930
1931 def get_colorize(colorize):
1932 if colorize == 'always':
1933 return True
1934
1935 if colorize == 'auto':
1936 return sys.stdout.isatty()
1937
1938 # colorize = 'never'
1939 return False
1940
1941
1942 def set_win_console_mode():
1943 # VT100 control sequences are supported on Windows 10 Anniversary Update and later.
1944 # https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
1945 # https://docs.microsoft.com/en-us/windows/console/setconsolemode
1946 if platform.release() == '10':
1947 STD_OUTPUT_HANDLE = -11
1948 STD_ERROR_HANDLE = -12
1949 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
1950 try:
1951 from ctypes import windll, wintypes, byref
1952 kernel32 = windll.kernel32
1953 for nhandle in (STD_OUTPUT_HANDLE, STD_ERROR_HANDLE):
1954 handle = kernel32.GetStdHandle(nhandle)
1955 old_mode = wintypes.DWORD()
1956 if not kernel32.GetConsoleMode(handle, byref(old_mode)):
1957 raise RuntimeError('GetConsoleMode failed')
1958 new_mode = bin(old_mode.value) | ENABLE_VIRTUAL_TERMINAL_PROCESSING
1959 if not kernel32.SetConsoleMode(handle, new_mode):
1960 raise RuntimeError('SetConsoleMode failed')
1961 # Note: No need to restore at exit. SetConsoleMode seems to
1962 # be limited to the calling process.
1963 except Exception:
1964 pass
1965
1966
1967 # Query autocompleter
1968
1969 # This function is largely experimental and could raise any exception;
1970 # you should be prepared to catch anything. When it works though, it
1971 # returns a list of strings the prefix could autocomplete to (however,
1972 # it is not guaranteed that they start with the specified prefix; for
1973 # instance, they won't if the specified prefix ends in a punctuation
1974 # mark.)
1975 def completer_fetch_completions(prefix):
1976 # One can pass the 'hl' query param to specify the language. We
1977 # ignore that for now.
1978 api_url = ('https://duckduckgo.com/ac/?q=%s&kl=wt-wt' %
1979 urllib.parse.quote(prefix, safe=''))
1980 # A timeout of 3 seconds seems to be overly generous already.
1981 with urllib.request.urlopen(api_url, timeout=3) as resp:
1982 with json.loads(resp.read().decode('utf-8')) as respobj:
1983 return [entry['phrase'] for entry in respobj]
1984
1985
1986 def completer_run(prefix):
1987 if prefix:
1988 completions = completer_fetch_completions('+'.join(prefix.split()))
1989 if completions:
1990 print('\n'.join(completions))
1991 sys.exit(0)
1992
1993
1994 def parse_args(args=None, namespace=None):
1995 """Parse ddgr arguments/options.
1996
1997 Parameters
1998 ----------
1999 args : list, optional
2000 Arguments to parse. Default is ``sys.argv``.
2001 namespace : argparse.Namespace
2002 Namespace to write to. Default is a new namespace.
2003
2004 Returns
2005 -------
2006 argparse.Namespace
2007 Namespace with parsed arguments / options.
2008
2009 """
2010
2011 colorstr_env = os.getenv('DDGR_COLORS')
2012
2013 argparser = DdgArgumentParser(description='DuckDuckGo from the terminal.')
2014 addarg = argparser.add_argument
2015 addarg('-n', '--num', type=argparser.nonnegative_int, default=10, metavar='N',
2016 help='show N (0<=N<=25) results per page (default 10); N=0 shows actual number of results fetched per page')
2017 addarg('-r', '--reg', dest='region', default='us-en', metavar='REG',
2018 help="region-specific search e.g. 'us-en' for US (default); visit https://duckduckgo.com/params")
2019 addarg('--colorize', nargs='?', choices=['auto', 'always', 'never'],
2020 const='always', default='auto',
2021 help="""whether to colorize output; defaults to 'auto', which enables
2022 color when stdout is a tty device; using --colorize without an argument
2023 is equivalent to --colorize=always""")
2024 addarg('-C', '--nocolor', action='store_true', help='equivalent to --colorize=never')
2025 addarg('--colors', dest='colorstr', type=argparser.is_colorstr, default=colorstr_env if colorstr_env else 'oCdgxy', metavar='COLORS',
2026 help='set output colors (see man page for details)')
2027 addarg('-j', '--ducky', action='store_true', help='open the first result in a web browser; implies --np')
2028 addarg('-t', '--time', dest='duration', metavar='SPAN', default='', choices=('d', 'w', 'm', 'y'), help='time limit search '
2029 '[d (1 day), w (1 wk), m (1 month), y (1 year)]')
2030 addarg('-w', '--site', dest='sites', action='append', metavar='SITE', help='search sites using DuckDuckGo')
2031 addarg('-x', '--expand', action='store_true', help='Show complete url in search results')
2032 addarg('-p', '--proxy', metavar='URI', help='tunnel traffic through an HTTPS proxy; URI format: [http[s]://][user:pwd@]host[:port]')
2033 addarg('--unsafe', action='store_true', help='disable safe search')
2034 addarg('--noua', action='store_true', help='disable user agent')
2035 addarg('--json', action='store_true', help='output in JSON format; implies --np')
2036 addarg('--gb', '--gui-browser', dest='gui_browser', action='store_true', help='open a bang directly in gui browser')
2037 addarg('--np', '--noprompt', dest='noninteractive', action='store_true', help='perform search and exit, do not prompt')
2038 addarg('--rev', '--reverse', dest='reverse', action='store_true', help='list entries in reversed order')
2039 addarg('--url-handler', metavar='UTIL', help='custom script or cli utility to open results')
2040 addarg('--show-browser-logs', action='store_true', help='do not suppress browser output (stdout and stderr)')
2041 addarg('-v', '--version', action='version', version=_VERSION_)
2042 addarg('-d', '--debug', action='store_true', help='enable debugging')
2043 addarg('keywords', nargs='*', metavar='KEYWORD', help='search keywords')
2044 addarg('--complete', help=argparse.SUPPRESS)
2045
2046 parsed = argparser.parse_args(args, namespace)
2047 if parsed.nocolor:
2048 parsed.colorize = 'never'
2049
2050 return parsed
2051
2052
2053 def main():
2054 opts = parse_args()
2055
2056 # Set logging level
2057 if opts.debug:
2058 LOGGER.setLevel(logging.DEBUG)
2059 LOGDBG('ddgr version %s Python version %s', _VERSION_, python_version())
2060
2061 # Handle query completer
2062 if opts.complete is not None:
2063 completer_run(opts.complete)
2064
2065 check_stdout_encoding()
2066
2067 # Add cmdline args to readline history
2068 if opts.keywords:
2069 try:
2070 readline.add_history(' '.join(opts.keywords))
2071 except Exception:
2072 pass
2073
2074 # Set colors
2075 colorize = get_colorize(opts.colorize)
2076
2077 colors = Colors(*[COLORMAP[c] for c in opts.colorstr], reset=COLORMAP['x']) if colorize else None
2078 Result.colors = colors
2079 Result.urlexpand = opts.expand
2080 DdgCmd.colors = colors
2081
2082 # Try to enable ANSI color support in cmd or PowerShell on Windows 10
2083 if sys.platform == 'win32' and sys.stdout.isatty() and colorize:
2084 set_win_console_mode()
2085
2086 if opts.url_handler is not None:
2087 open_url.url_handler = opts.url_handler
2088 else:
2089 open_url.override_text_browser = bool(opts.gui_browser)
2090
2091 # Handle browser output suppression
2092 open_url.suppress_browser_output = not (opts.show_browser_logs or (os.getenv('BROWSER') in TEXT_BROWSERS))
2093
2094 try:
2095 repl = DdgCmd(opts, '' if opts.noua else USER_AGENT)
2096
2097 if opts.json or opts.ducky or opts.noninteractive:
2098 # Non-interactive mode
2099 if repl.keywords and (
2100 repl.keywords[0][0] == '!' or
2101 (len(repl.keywords[0]) > 1 and repl.keywords[0][1] == '!')
2102 ):
2103 # Handle bangs
2104 open_url(repl._ddg_url.full())
2105 else:
2106 repl.fetch()
2107 if opts.ducky:
2108 if repl.results:
2109 open_url(repl.results[0].url)
2110 else:
2111 print('No results.', file=sys.stderr)
2112 else:
2113 if not opts.reverse:
2114 repl.display_instant_answer(json_output=opts.json)
2115 repl.display_results(prelude='', json_output=opts.json)
2116 else:
2117 repl.display_results(prelude='', json_output=opts.json)
2118 repl.display_instant_answer(json_output=opts.json)
2119
2120 sys.exit(0)
2121
2122 # Interactive mode
2123 repl.cmdloop()
2124 except Exception as e:
2125 # If debugging mode is enabled, let the exception through for a traceback;
2126 # otherwise, only print the exception error message.
2127 if LOGGER.isEnabledFor(logging.DEBUG):
2128 raise
2129
2130 LOGERR(e)
2131 sys.exit(1)
2132
2133
2134 if __name__ == '__main__':
2135 main()