Debian Codegraph @

nquire

raw
1 #!/bin/bash
2
3 # ===========================================================================
4 #
5 # PUBLIC DOMAIN NOTICE
6 # National Center for Biotechnology Information (NCBI)
7 #
8 # This software/database is a "United States Government Work" under the
9 # terms of the United States Copyright Act. It was written as part of
10 # the author's official duties as a United States Government employee and
11 # thus cannot be copyrighted. This software/database is freely available
12 # to the public for use. The National Library of Medicine and the U.S.
13 # Government do not place any restriction on its use or reproduction.
14 # We would, however, appreciate having the NCBI and the author cited in
15 # any work or product based on this material.
16 #
17 # Although all reasonable efforts have been taken to ensure the accuracy
18 # and reliability of the software and data, the NLM and the U.S.
19 # Government do not and cannot warrant the performance or results that
20 # may be obtained by using this software or data. The NLM and the U.S.
21 # Government disclaim all warranties, express or implied, including
22 # warranties of performance, merchantability or fitness for any particular
23 # purpose.
24 #
25 # ===========================================================================
26 #
27 # File Name: nquire
28 #
29 # Author: Jonathan Kans, Aaron Ucko
30 #
31 # Version Creation Date: 03/28/2020
32 #
33 # ==========================================================================
34
35 # environment variable turns on shell tracing
36
37 if [ -n "${EDIRECT_TRACE}" ] && [ "${EDIRECT_TRACE}" = true ]
38 then
39 set -x
40 fi
41
42 # pth must contain cacert.pem certificate (previously within aux/lib/perl5/Mozilla/CA/ subdirectory)
43
44 pth=$( dirname "$0" )
45
46 case "$pth" in
47 /* )
48 ;; # already absolute
49 * )
50 pth=$(cd "$pth" && pwd)
51 ;;
52 esac
53
54 case ":$PATH:" in
55 *:"$pth":* )
56 ;;
57 * )
58 PATH="$PATH:$pth"
59 export PATH
60 ;;
61 esac
62
63 # set up colors for error report
64
65 ColorSetup() {
66
67 if [ -z "$TERM" ] || [ ! -t 2 ]
68 then
69 RED=""
70 BLUE=""
71 BOLD=""
72 FLIP=""
73 INIT=""
74 elif command -v tput >/dev/null
75 then
76 RED="$(tput setaf 1)"
77 BLUE="$(tput setaf 4)"
78 BOLD="$(tput bold)"
79 FLIP="$(tput rev)"
80 INIT="$(tput sgr0)"
81 else
82 # assume ANSI
83 escape="$(printf '\033')"
84 RED="${escape}[31m"
85 BLUE="${escape}[34m"
86 BOLD="${escape}[1m"
87 FLIP="${escape}[7m"
88 INIT="${escape}[0m"
89 fi
90 LOUD="${INIT}${RED}${BOLD}"
91 INVT="${LOUD}${FLIP}"
92 # clear color on terminal if "export EDIRECT_TRACE=true" has been used
93 echo "${INIT}" > /dev/null
94 }
95
96 ColorSetup
97
98 # highlighted error function
99
100 DisplayError() {
101
102 if [ $# -gt 0 ]
103 then
104 msg="$1"
105 echo "${INVT} ERROR: ${LOUD} ${msg}${INIT}" >&2
106 fi
107 }
108
109 # allow environment variable to set preference for curl or wget (undocumented)
110
111 helper=""
112
113 if [ -n "${NQUIRE_HELPER}" ]
114 then
115 helper="${NQUIRE_HELPER}"
116 fi
117
118 # allow environment variable to set curl connection timeout (undocumented)
119
120 timeout=20
121
122 if [ -n "${NQUIRE_TIMEOUT}" ]
123 then
124 timeout="${NQUIRE_TIMEOUT}"
125 fi
126
127 # allow environment variable to set IPv4 flag (undocumented)
128
129 ip_ver_flag=""
130
131 case "${NQUIRE_IPV4}" in
132 [TtYy]* | 1 | [Oo][Nn] )
133 # force IPv4
134 ip_ver_flag=-4
135 ;;
136 "" | * )
137 ;;
138 esac
139
140 # return contents of XML object or element
141
142 ParseXMLObject() {
143
144 mesg=$1
145 objc=$2
146
147 echo "$mesg" | sed -n "s|.*<$objc[^>]*>\\(.*\\)</$objc>.*|\\1|p"
148 }
149
150 # NCBI servers now require Aspera Connect client version 4.2 or above.
151
152 # To download the free client, open the IBM Aspera Connect subsection in:
153 # https://www.ibm.com/products/aspera/downloads#cds
154
155 # Also see discussion in:
156 # https://www.biostars.org/p/9553092/
157
158 APPPATH=""
159 KEYPATH=""
160 KEYNAME=aspera_tokenauth_id_rsa
161
162 # the old KEYNAME, asperaweb_id_dsa.openssh, is no longer used
163
164 HasAspera() {
165
166 # check to see if the Aspera Connect client is installed
167
168 if [ -n "${EDIRECT_NO_ASPERA}" ] && [ "${EDIRECT_NO_ASPERA}" = true ]
169 then
170 return 1
171 fi
172
173 case "$( uname -s )" in
174 Darwin )
175 sysdir='/Applications/IBM Aspera Connect.app/Contents/Resources'
176 sysdir2=/bin
177 userdir=$HOME$sysdir
178 ;;
179 CYGWIN_NT* )
180 sysdir='/cygdrive/c/Program Files/Aspera/Aspera Connect/bin'
181 sysdir2='/cygdrive/c/Program Files (x86)/Aspera/Aspera Connect/bin'
182 userdir="$( cygpath -H )/$USER/AppData/Local/Programs/Aspera/Aspera Connect/bin"
183 ;;
184 * )
185 sysdir=/opt/aspera/bin
186 sysdir2=/bin
187 userdir=$HOME/.aspera/connect/bin
188 ;;
189 esac
190 for d in "$sysdir" "$sysdir2" "$userdir"
191 do
192 if "$d/ascp" --version 2>&1 | grep -e '^Aspera' -e '^IBM Aspera' >/dev/null
193 then
194 APPPATH=$d
195 break
196 fi
197 done
198 if [ -z "$APPPATH" ] && ascp --version 2>&1 | grep -e '^Aspera' -e '^IBM Aspera' >/dev/null
199 then
200 APPPATH=$( type -path ascp )
201 APPPATH=$( dirname "$APPPATH" )
202 fi
203 if [ -z "$APPPATH" ]
204 then
205 return 1
206 fi
207
208 for d in "$APPPATH" "$sysdir" "$sysdir2" "$userdir"
209 do
210 if [ -f "$d/../etc/$KEYNAME" ]
211 then
212 KEYPATH=$d/../etc
213 break
214 elif [ -f "$d/$KEYNAME" ]
215 then
216 KEYPATH=$d
217 break
218 fi
219 done
220 if [ -z "$KEYPATH" ]
221 then
222 return 1
223 fi
224
225 return 0
226 }
227
228 # check for leading flags
229
230 debug=false
231 log=false
232 timer=false
233 raw=false
234 bulk=false
235
236 while [ $# -gt 0 ]
237 do
238 case "$1" in
239 -newmode | -oldmode )
240 shift
241 ;;
242 -version )
243 version=$( einfo -version )
244 echo "$version"
245 exit 0
246 ;;
247 -h | -help | --help | help )
248 version=$( einfo -version )
249 echo "nquire $version"
250 echo ""
251 cat "$pth/help/nquire-help.txt"
252 echo ""
253 exit 0
254 ;;
255 -examples )
256 version=$( einfo -version )
257 echo "nquire $version"
258 echo ""
259 cat "$pth/help/nquire-examples.txt"
260 echo ""
261 exit 0
262 ;;
263 -hasaspera )
264 # report whether Aspera is installed (undocumented)
265 HasAspera
266 if [ "$?" = 1 ]
267 then
268 echo "false"
269 else
270 echo "true"
271 fi
272 exit 0
273 ;;
274 -puglist )
275 shift
276 res=$( cat | tr -d '\n' )
277 obj=$( ParseXMLObject "$res" IdentifierList )
278 numx=$( ParseXMLObject "$obj" Size )
279 dbsx=$( ParseXMLObject "$obj" EntrezDB )
280 webx=$( ParseXMLObject "$obj" EntrezWebEnv )
281 keyx=$( ParseXMLObject "$obj" EntrezQueryKey )
282 echo "<ENTREZ_DIRECT>"
283 if [ -n "$dbsx" ]
284 then
285 echo " <Db>${dbsx}</Db>"
286 fi
287 if [ -n "$webx" ]
288 then
289 echo " <WebEnv>${webx}</WebEnv>"
290 fi
291 if [ -n "$keyx" ]
292 then
293 echo " <QueryKey>${keyx}</QueryKey>"
294 fi
295 if [ -n "$numx" ]
296 then
297 echo " <Count>${numx}</Count>"
298 fi
299 echo "</ENTREZ_DIRECT>"
300 exit 0
301 ;;
302 -pugwait )
303 shift
304 res=$( cat | tr -d '\n' )
305 obj=$( ParseXMLObject "$res" Waiting )
306 lkey=$( ParseXMLObject "$obj" ListKey )
307 goOn=true
308 count=0
309
310 while [ "$goOn" = true ]
311 do
312 count=$((count + 1))
313 sleep 5
314 poll=$( nquire -pugrest compound listkey "$lkey" cids XML )
315 obj=$( ParseXMLObject "$poll" Waiting )
316 wtng=$( ParseXMLObject "$obj" Message )
317 if [ -z "$wtng" ]
318 then
319 goOn=false
320 fi
321 if [ "$count" -gt 40 ]
322 then
323 DisplayError "Search $lkey timed out"
324 exit 1
325 fi
326 done
327 cids=$(
328 echo "$poll" |
329 xtract -pattern IdentifierList -sep "\n" -element CID |
330 sort -n | uniq
331 )
332 numx=$( echo "$cids" | wc -l | tr -d ' ' )
333 echo "<ENTREZ_DIRECT>"
334 echo " <Db>pccompound</Db>"
335 echo " <Count>${numx}</Count>"
336 echo "$cids" |
337 while read uid
338 do
339 echo " <Id>${uid}</Id>"
340 done
341 echo "</ENTREZ_DIRECT>"
342 exit 0
343 ;;
344 -debug )
345 debug=true
346 shift
347 ;;
348 -log )
349 log=true
350 shift
351 ;;
352 -timer )
353 timer=true
354 shift
355 ;;
356 -raw )
357 raw=true
358 shift
359 ;;
360 -bulk )
361 bulk=true
362 shift
363 ;;
364 -curl )
365 # override setting from environment variable (undocumented)
366 helper="curl"
367 shift
368 ;;
369 -wget )
370 # override setting from environment variable (undocumented)
371 helper="wget"
372 shift
373 ;;
374 * )
375 # break out of loop if none of the above, allows while loop to check for multiple flags
376 break
377 ;;
378 esac
379 done
380
381 # elapsed time variable
382
383 elapsed=""
384
385 # accommodate CYGWIN using Windows version of curl that fails to recognize Cygwin paths
386
387 isCygwin=false
388 fix_path="printf %s"
389 case "$(uname -s)" in
390 CYGWIN_NT* )
391 isCygwin=true
392 if curl --version | grep -q Windows
393 then
394 fix_path="cygpath -w"
395 fi
396 ;;
397 esac
398
399 # check for presence of curl or wget
400
401 case "$helper" in
402 curl | CURL | CUrl | Curl | cUrl | cURL )
403 binary=$( command -v curl )
404 if [ ! -x "$binary" ]
405 then
406 DisplayError "nquire is unable to find curl executable"
407 exit 1
408 fi
409 ;;
410 wget | WGET | WGet | Wget | wGet | wGET )
411 binary=$( command -v wget )
412 if [ ! -x "$binary" ]
413 then
414 DisplayError "nquire is unable to find wget executable"
415 exit 1
416 fi
417 ;;
418 * )
419 if [ "$isCygwin" = true ]
420 then
421 # if CYGWIN try wget before curl
422 binary=$( command -v wget )
423 if [ ! -x "$binary" ]
424 then
425 binary=$( command -v curl )
426 fi
427 else
428 # otherwise try curl before wget
429 binary=$( command -v curl )
430 if [ ! -x "$binary" ]
431 then
432 binary=$( command -v wget )
433 fi
434 fi
435 if [ ! -x "$binary" ]
436 then
437 DisplayError "nquire is unable to find either curl or wget"
438 exit 1
439 fi
440 ;;
441 esac
442
443 # subset of perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"'
444
445 Escape() {
446
447 echo "$1" |
448 sed -e "s/%/%25/g" \
449 -e "s/!/%21/g" \
450 -e "s/#/%23/g" \
451 -e "s/&/%26/g" \
452 -e "s/'/%27/g" \
453 -e "s/*/%2A/g" \
454 -e "s/+/%2B/g" \
455 -e "s/,/%2C/g" \
456 -e "s|/|%2F|g" \
457 -e "s/:/%3A/g" \
458 -e "s/;/%3B/g" \
459 -e "s/=/%3D/g" \
460 -e "s/?/%3F/g" \
461 -e "s/@/%40/g" \
462 -e "s/|/%7C/g" \
463 -e "s/ /%20/g" |
464 sed -e 's/\$/%24/g' \
465 -e 's/(/%28/g' \
466 -e 's/)/%29/g' \
467 -e 's/</%3C/g' \
468 -e 's/>/%3E/g' \
469 -e 's/\[/%5B/g' \
470 -e 's/\]/%5D/g' \
471 -e 's/\^/%5E/g' \
472 -e 's/{/%7B/g' \
473 -e 's/}/%7D/g'
474 }
475
476 # initialize variables
477
478 mode=""
479
480 content_type=""
481 http_version="1.0"
482 user_agent=""
483
484 api_key=""
485
486 url=""
487 sls=""
488
489 arg=""
490 amp=""
491 cmd=""
492 pfx=""
493
494 isPugRest=false
495 isDatasets=false
496
497 justDash=false
498
499 # optionally include nextra.sh script, if present, for internal NCBI maintenance functions (undocumented)
500
501 if [ -f "$pth"/nextra.sh ]
502 then
503 # dot command is equivalent of "source"
504 . "$pth"/nextra.sh
505 fi
506
507 # include nhance.sh script, which should be present in public release, for external shortcut extensions
508
509 if [ -f "$pth"/nhance.sh ]
510 then
511 # dot command is equivalent of "source"
512 . "$pth"/nhance.sh
513 fi
514
515 # collect optional HTTP headers
516
517 while [ $# -gt 0 ]
518 do
519 case "$1" in
520 -content-type )
521 shift
522 if [ $# -gt 0 ]
523 then
524 content-type="$1"
525 shift
526 fi
527 ;;
528 -http-version )
529 shift
530 if [ $# -gt 0 ]
531 then
532 http_version="$1"
533 shift
534 fi
535 ;;
536 -user-agent )
537 shift
538 if [ $# -gt 0 ]
539 then
540 user_agent="$1"
541 shift
542 fi
543 ;;
544 * )
545 # break if none of the above
546 break
547 ;;
548 esac
549 done
550
551 # get extraction method or shortcut
552
553 if [ $# -gt 0 ]
554 then
555 case "$1" in
556 -url | -get | -len )
557 # HTTP commands
558 mode="$1"
559 shift
560 ;;
561 -lst | -dir | -ftp | -dwn | -asp )
562 # FTP commands
563 mode="$1"
564 shift
565 ;;
566 -lstN | -dirN | -ftpN | -dwnN | -aspN | \
567 -lst-ncbi | -dir-ncbi | -ftp-ncbi | -dw-ncbi-ncbi | -asp-ncbi )
568 # shortcuts for FTP commands with NCBI FTP server base (undocumented)
569 mode=$( echo "$1" | cut -c 1-4 )
570 shift
571 url="ftp://ftp.ncbi.nlm.nih.gov"
572 sls="/"
573 ;;
574 -ncbi )
575 # shortcut for NCBI base
576 shift
577 url="https://www.ncbi.nlm.nih.gov"
578 sls="/"
579 mode="-url"
580 ;;
581 -eutils )
582 # shortcut for EUtils base
583 shift
584 url="https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
585 sls="/"
586 mode="-url"
587 ;;
588 -preview )
589 # shortcut for EUtils preview server base
590 shift
591 url="https://eutilspreview.ncbi.nlm.nih.gov/entrez/eutils"
592 sls="/"
593 mode="-url"
594 ;;
595 -edict )
596 # shortcut for localhost base
597 shift
598 url="localhost:8080"
599 # allow environment variable to override default -edict URL
600 if [ -n "${NQUIRE_EDICT_SERVER}" ]
601 then
602 url="${NQUIRE_EDICT_SERVER}"
603 fi
604 sls="/"
605 mode="-url"
606 ;;
607 -pubchem )
608 # shortcut for PubChem base (replaces -pubchem legacy shortcut)
609 shift
610 url="https://pubchem.ncbi.nlm.nih.gov"
611 sls="/"
612 mode="-url"
613 ;;
614 -pugrest )
615 # shortcut for PubChem Power User Gateway (PUG) REST base
616 shift
617 url="https://pubchem.ncbi.nlm.nih.gov/rest/pug"
618 sls="/"
619 mode="-url"
620 isPugRest=true
621 ;;
622 -pugview )
623 # shortcut for PubChem Power User Gateway (PUG) View base
624 shift
625 url="https://pubchem.ncbi.nlm.nih.gov/rest/pug_view"
626 sls="/"
627 mode="-url"
628 ;;
629 -pubrest )
630 exec >&2
631 DisplayError "'$1' is a misspelling - use '-pugrest' with a 'g'"
632 exit 1
633 ;;
634 -pubview )
635 exec >&2
636 DisplayError "'$1' is a misspelling - use '-pugview' with a 'g'"
637 exit 1
638 ;;
639 -dataset | -datasets )
640 # shortcut for NCBI Datasets base
641 shift
642 url="https://api.ncbi.nlm.nih.gov/datasets/v2alpha"
643 sls="/"
644 isDatasets=true
645 # set appropriate values for HTTP request header
646 content_type="application/json"
647 if [ -n "${NCBI_API_KEY}" ]
648 then
649 api_key="${NCBI_API_KEY}"
650 fi
651 ;;
652 -* )
653 exec >&2
654 DisplayError "'$1' is not a recognized nquire option"
655 exit 1
656 ;;
657 * )
658 DisplayError "'$1' is not a recognized nquire command"
659 exit 1
660 ;;
661 esac
662 fi
663
664 # collect URL directory components
665
666 while [ $# -gt 0 ]
667 do
668 case "$1" in
669 -* )
670 # otherwise leading dash indicates end of path, switch to arguments
671 break
672 ;;
673 * )
674 dir="$1"
675 # remove trailing slash directory delimiter
676 dir=${dir%/}
677 shift
678 url="$url$sls$dir"
679 sls="/"
680 ;;
681 esac
682 done
683
684 # collect argument tags paired with (escaped) values
685
686 isInChI=false
687
688 while [ $# -gt 0 ]
689 do
690 case "$1" in
691 - )
692 justDash=true
693 shift
694 ;;
695 -* )
696 isInChI=false
697 cmd="$1"
698 if [ "$cmd" = "-inchi" ]
699 then
700 isInChI=true
701 fi
702 # remove leading dash from argument
703 cmd=${cmd#-}
704 # add argument and command
705 arg="$arg$amp$cmd"
706 # subsequent commands preceded by ampersand
707 amp="&"
708 # precede first value (if any) with equal sign
709 pfx="="
710 shift
711 ;;
712 * )
713 val="$1"
714 # remove initial backslash used to protect leading minus sign
715 val=${val#\\}
716 # add "InChI=" prefix if missing in -inchi argument to -pugrest
717 if [ "$isPugRest" = true ] && [ "$isInChI" = true ]
718 then
719 case "$val" in
720 "InChI="* )
721 ;;
722 * )
723 val="InChI=${val}"
724 ;;
725 esac
726 fi
727 # URL encoding
728 if [ "$raw" = true ]
729 then
730 val=$( echo "$val" | sed -e "s/&/%26/g" -e "s/=/%3D/g" )
731 else
732 val=$( Escape "$val" )
733 fi
734 arg="$arg$pfx$val"
735 # concatenate run of values with commas
736 pfx=","
737 shift
738 ;;
739 esac
740 done
741
742 # datasets GET vs. POST decision based on:
743 # https://www.ncbi.nlm.nih.gov/datasets/docs/v2/reference-docs/rest-api/
744
745 GetObjectsFromStdin() {
746
747 uids=$( cat )
748 if [ -n "$uids" ]
749 then
750 echo "$uids" | join-into-groups-of 100
751 fi
752 }
753
754 GetStringsFromStdin() {
755
756 uids=$( cat )
757 if [ -n "$uids" ]
758 then
759 echo "$uids" | join-into-groups-of 100 | quote-grouped-elements
760 fi
761 }
762
763 if [ "$isDatasets" = true ]
764 then
765 case "$url" in
766 *virus/genome/download* )
767 mode="-url"
768 list=$( GetStringsFromStdin )
769 if [ -n "$list" ]
770 then
771 pfx='{"accessions":['
772 sfx=']}'
773 arg=$( echo "${pfx}${list}${sfx}" )
774 fi
775 ;;
776 *virus/taxon/sars2/protein* | *virus/taxon/sars2/protein/download* )
777 mode="-url"
778 ;;
779 *virus/accession* | *virus/taxon* )
780 mode="-get"
781 ;;
782 *virus* )
783 mode="-url"
784 list=$( GetStringsFromStdin )
785 if [ -n "$list" ]
786 then
787 pfx='{"accessions":['
788 sfx=']}'
789 arg=$( echo "${pfx}${list}${sfx}" )
790 fi
791 ;;
792 *genome/accession* | *genome/bioproject* | *genome/taxon* )
793 mode="-get"
794 ;;
795 *genome/* )
796 mode="-url"
797 ;;
798 *gene/taxon/counts* )
799 mode="-url"
800 ;;
801 *gene/id* )
802 mode="-get"
803 ;;
804 *gene/accession* | *gene/symbol* | *gene/taxon* )
805 mode="-get"
806 ;;
807 *gene/download* )
808 mode="-url"
809 list=$( GetObjectsFromStdin )
810 if [ -n "$list" ]
811 then
812 pfx='{"gene_ids":['
813 sfx=']}'
814 arg=$( echo "${pfx}${list}${sfx}" )
815 fi
816 ;;
817 *gene/download_summary* )
818 mode="-url"
819 list=$( GetObjectsFromStdin )
820 if [ -n "$list" ]
821 then
822 pfx='{"gene_ids":['
823 sfx=']}'
824 arg=$( echo "${pfx}${list}${sfx}" )
825 fi
826 ;;
827 *gene/links* )
828 mode="-url"
829 list=$( GetObjectsFromStdin )
830 if [ -n "$list" ]
831 then
832 pfx='{"gene_ids":['
833 sfx=']}'
834 arg=$( echo "${pfx}${list}${sfx}" )
835 fi
836 ;;
837 *gene* )
838 mode="-url"
839 list=$( GetObjectsFromStdin )
840 if [ -n "$list" ]
841 then
842 pfx='{"gene_ids":['
843 sfx=']}'
844 arg=$( echo "${pfx}${list}${sfx}" )
845 fi
846 ;;
847 *protein/accession/download* )
848 mode="-url"
849 ;;
850 *protein/accession/*/download* )
851 mode="-get"
852 ;;
853 *taxonomy/taxon* )
854 mode="-get"
855 ;;
856 *taxonomy/filtered_subtree* )
857 mode="-url"
858 list=$( GetStringsFromStdin )
859 if [ -n "$list" ]
860 then
861 pfx='{"taxons":['
862 sfx=']}'
863 arg=$( echo "${pfx}${list}${sfx}" )
864 fi
865 ;;
866 *taxonomy* )
867 mode="-url"
868 list=$( GetStringsFromStdin )
869 if [ -n "$list" ]
870 then
871 pfx='{"taxons":['
872 sfx=']}'
873 arg=$( echo "${pfx}${list}${sfx}" )
874 fi
875 ;;
876 *version* )
877 mode="-get"
878 ;;
879 * )
880 DisplayError "Unrecognized nquire -datasets argument"
881 exit 1
882 ;;
883 esac
884 if [ "$mode" = "-url" ]
885 then
886 # arg='{"gene_ids":[2652,3043]}'
887 if [ -z "$arg" ]
888 then
889 DisplayError "nquire -datasets does not yet support this particular POST query"
890 exit 1
891 fi
892 fi
893 fi
894
895 # reality checks
896
897 if [ -z "$mode" ]
898 then
899 DisplayError "nquire mode (-url, -get, -len, -lst, -dir, -ftp, -dwn, -asp) is missing"
900 exit 1
901 elif [ -z "$url" ]
902 then
903 DisplayError "nquire is missing the URL"
904 exit 1
905 fi
906
907 # debugging output to stderr
908
909 if [ "$debug" = true ]
910 then
911 if [ -z "$arg" ]
912 then
913 echo "curl -fsSL \"$url\"" >&2
914 elif [ "$mode" = "-url" ]
915 then
916 echo "curl -fsSL \"$url\" -d \"$arg\"" >&2
917 elif [ "$mode" = "-get" ]
918 then
919 echo "curl -fsSL \"$url?$arg\"" >&2
920 else
921 echo "PTH $pth" >&2
922 echo "URL $url" >&2
923 echo "ARG $arg" >&2
924 fi
925 exit 0
926 fi
927
928 # pause if Entrez Utilities server to avoid exceeding request frequency limit
929
930 slow=false
931
932 case "${SLOW_EDIRECT}" in
933 "" | [FfNn]* | 0 | [Oo][Ff][Ff] )
934 ;;
935 * )
936 slow=true
937 ;;
938 esac
939
940 hasperl=$( command -v perl )
941 haspython=$( command -v python3 )
942
943 case $url in
944 *"dev.ncbi.nlm.nih.gov/entrez/eutils/"* | *"internal.ncbi.nlm.nih.gov/entrez/eutils/"* )
945 if [ "$slow" = true ]
946 then
947 sleep 1
948 elif [ -x "$hasperl" ]
949 then
950 perl -MTime::HiRes -e 'Time::HiRes::usleep(1000)'
951 fi
952 ;;
953 *"eutilspreview.ncbi.nlm.nih.gov/entrez/eutils/"* )
954 if [ "$slow" = true ]
955 then
956 sleep 1
957 elif [ -x "$hasperl" ]
958 then
959 perl -MTime::HiRes -e 'Time::HiRes::usleep(350000)'
960 else
961 sleep 1
962 fi
963 ;;
964 *"/entrez/eutils/"* )
965 if [ "$slow" = true ]
966 then
967 sleep 1
968 elif [ -x "$hasperl" ]
969 then
970 case $arg in
971 *"api_key="* )
972 perl -MTime::HiRes -e 'Time::HiRes::usleep(110000)'
973 ;;
974 * )
975 perl -MTime::HiRes -e 'Time::HiRes::usleep(350000)'
976 ;;
977 esac
978 else
979 sleep 1
980 fi
981 ;;
982 *"ncbi.nlm.nih.gov/datasets/"* )
983 if [ "$slow" = true ]
984 then
985 sleep 1
986 elif [ -x "$hasperl" ]
987 then
988 if [ -n "$api_key" ]
989 then
990 perl -MTime::HiRes -e 'Time::HiRes::usleep(110000)'
991 else
992 perl -MTime::HiRes -e 'Time::HiRes::usleep(350000)'
993 fi
994 else
995 sleep 1
996 fi
997 ;;
998 *"pubchem.ncbi.nlm.nih.gov/rest/"* )
999 if [ -x "$hasperl" ]
1000 then
1001 perl -MTime::HiRes -e 'Time::HiRes::usleep(210000)'
1002 else
1003 sleep 1
1004 fi
1005 ;;
1006 *"ftp.ncbi.nlm.nih.gov"* | *"ftp.nlm.nih.gov"* | *"nlmpubs.nlm.nih.gov"* )
1007 sleep 1
1008 ;;
1009 * )
1010 if [ "$bulk" = true ]
1011 then
1012 sleep 1
1013 fi
1014 ;;
1015 esac
1016
1017 # try to get time in milliseconds, but use seconds as a fallback
1018
1019 timeUnit="MILLISECONDS"
1020 if [ ! -x "$hasperl" ] && [ ! -x "$haspython" ]
1021 then
1022 timeUnit="SECONDS"
1023 fi
1024
1025 GetTime() {
1026
1027 if [ -x "$hasperl" ]
1028 then
1029 perl -MTime::HiRes -e 'printf("%.0f\n",Time::HiRes::time()*1000)'
1030 elif [ -x "$haspython" ]
1031 then
1032 python3 -c 'import datetime; print(int(datetime.datetime.now().timestamp()*1000))'
1033 else
1034 echo $(($(date +'%s')))
1035 fi
1036 }
1037
1038 # common function to execute curl or wget command
1039
1040 SendRequest() {
1041
1042 when=$( date )
1043
1044 starttime=$( GetTime )
1045
1046 case "$binary" in
1047 */curl )
1048 if [ "$log" = true ]
1049 then
1050 echo "${BLUE}$@${INIT}" >&2
1051 fi
1052
1053 temp=$(mktemp /tmp/NQUIRE_HEADER.XXXXXXXXX)
1054
1055 if [ "$bulk" = true ]
1056 then
1057 curl -fsSL $ip_ver_flag -D "$($fix_path "$temp")" "$@"
1058 elif [ -f "$pth"/cacert.pem ]
1059 then
1060 curl ${http_version:+ "--http${http_version}"} \
1061 --connect-timeout "$timeout" \
1062 ${content_type:+ -H "Content-Type:${content_type}"} \
1063 ${api_key:+ -H "api-key:${api_key}"} \
1064 -fsSL $ip_ver_flag \
1065 --cacert "$($fix_path "$pth"/cacert.pem)" \
1066 -D "$($fix_path "$temp")" "$@"
1067 else
1068 curl ${http_version:+ "--http${http_version}"} \
1069 --connect-timeout "$timeout" \
1070 ${content_type:+ -H "Content-Type:${content_type}"} \
1071 ${api_key:+ -H "api-key:${api_key}"} \
1072 -fsSL $ip_ver_flag \
1073 -D "$($fix_path "$temp")" "$@"
1074 fi
1075
1076 # capture and check curl return value
1077 res=$?
1078 if [ "$res" -ne 0 ]
1079 then
1080 # report failure
1081 DisplayError "curl command failed ( $when ) with: ${res}"
1082 echo "${BLUE}$@${INIT}" >&2
1083 # show return code in first line of header
1084 head -n 1 "$temp" >&2
1085 fi
1086
1087 rm "$temp"
1088 ;;
1089 */wget )
1090 if [ "$log" = true ]
1091 then
1092 echo "${BLUE}$@${INIT}" >&2
1093 fi
1094
1095 temp=$(mktemp /tmp/NQUIRE_HEADER.XXXXXXXXX)
1096
1097 # wget needs --no-remove-listing for ftp listing?
1098
1099 if [ "$bulk" = true ]
1100 then
1101 wget -qS -O - --no-check-certificate "$@" 2> "$temp"
1102 elif [ -f "$pth"/cacert.pem ]
1103 then
1104 wget -qS -O - --ca-certificate="$pth"/cacert.pem "$@" 2> "$temp"
1105 else
1106 wget -qS -O - --no-check-certificate "$@" 2> "$temp"
1107 fi
1108
1109 # capture and check wget return value
1110 res=$?
1111 if [ "$res" -ne 0 ]
1112 then
1113 # report failure
1114 DisplayError "wget command failed ( $when ) with: ${res}"
1115 echo "${BLUE}$@${INIT}" >&2
1116 # show return code in first line of header
1117 head -n 1 "$temp" >&2
1118 fi
1119
1120 rm "$temp"
1121 ;;
1122 esac
1123
1124 stoptime=$(GetTime)
1125 elapsed=$((stoptime - starttime))
1126 }
1127
1128 # can use Aspera if installed
1129
1130 if [ "$mode" = "-asp" ]
1131 then
1132 HasAspera
1133 if [ "$?" = 1 ]
1134 then
1135 # Aspera not found, revert to download with FTP
1136 mode="-dwn"
1137 else
1138 # add colon before first slash in URL for Aspera
1139 url=$(echo "$url" | sed -e 's|/|:/|')
1140 fi
1141 fi
1142
1143 # common method for file download
1144
1145 failed=0
1146
1147 DownloadOneFile() {
1148
1149 urlfl="$1"
1150 fl="$2"
1151
1152 if [ ! -f "$fl" ]
1153 then
1154 # only download if local file does not already exist
1155 case "$mode" in
1156 -dwn )
1157 SendRequest "$urlfl" > "$fl"
1158 ;;
1159 -asp )
1160 if [ -z "${ASPERA_SCP_PASS}" ]
1161 then
1162 # this value is a public default key published in an IBM document:
1163 # https://delivery04.dhe.ibm.com/sar/CMA/OSA/08orb/0/IBM_Aspera_Faspex_Admin_4.4.0_Linux.pdf
1164 export ASPERA_SCP_PASS=743128bf-3bf3-45b5-ab14-4602c67f2950
1165 fi
1166 starttime=$( GetTime )
1167 "$APPPATH/ascp" -T -q -k 1 -l 500m -i "$KEYPATH/$KEYNAME" \
1168 "anonftp@$urlfl" "."
1169 stoptime=$(GetTime)
1170 elapsed=$((stoptime - starttime))
1171 ;;
1172 esac
1173 if [ ! -f "$fl" ]
1174 then
1175 failed=$((failed + 1))
1176 # report failure to download requested file
1177 echo "" >&2
1178 echo "${RED}${fl} FAILED${INIT}" >&2
1179 fi
1180 fi
1181 }
1182
1183 # datasets extract zip file and pipe data_report.jsonl
1184 # nquire -datasets gene id 2562,3043 download
1185
1186 if [ "$isDatasets" = true ] && [ "$justDash" = true ]
1187 then
1188 if [ "$mode" = "-get" ] && [ -z "$arg" ]
1189 then
1190 tempZip=$(mktemp /tmp/NQUIRE_TEMP.XXXXXXXXX)
1191 nquire -get "$url" > "$tempZip"
1192 unzip -p "$tempZip" "ncbi_dataset/data/data_report.jsonl"
1193 rm "$tempZip"
1194 exit 0
1195 fi
1196 fi
1197
1198 # send request with method-specific arguments
1199
1200 case "$mode" in
1201 -url )
1202 case "$binary" in
1203 */curl )
1204 if [ -n "$arg" ]
1205 then
1206 SendRequest -X POST "$url" -d "$arg"
1207 else
1208 SendRequest -X POST "$url"
1209 fi
1210 ;;
1211 */wget )
1212 if [ -n "$arg" ]
1213 then
1214 SendRequest --post-data="$arg" "$url"
1215 else
1216 SendRequest --post-data="" "$url"
1217 fi
1218 ;;
1219 esac
1220 ;;
1221 -get )
1222 case "$binary" in
1223 */curl )
1224 if [ -n "$arg" ]
1225 then
1226 SendRequest -X GET "$url?$arg"
1227 else
1228 SendRequest -X GET "$url"
1229 fi
1230 ;;
1231 */wget )
1232 if [ -n "$arg" ]
1233 then
1234 SendRequest "$url?$arg"
1235 else
1236 SendRequest "$url"
1237 fi
1238 ;;
1239 esac
1240 ;;
1241 -len )
1242 case "$binary" in
1243 */curl )
1244 if [ -n "$arg" ]
1245 then
1246 SendRequest -I "$url?$arg" |
1247 grep -i Content-Length | tr -d '\r' | cut -d ' ' -f 2
1248 else
1249 SendRequest -I "$url" |
1250 grep -i Content-Length | tr -d '\r' | cut -d ' ' -f 2
1251 fi
1252 ;;
1253 */wget )
1254 DisplayError "-len not supported for wget"
1255 exit 1
1256 ;;
1257 esac
1258 ;;
1259 -lst )
1260 case "$binary" in
1261 */curl )
1262 SendRequest "$url/" |
1263 tr -s ' ' | tr ' ' '\t' | cut -f 9 | grep '.'
1264 ;;
1265 */wget )
1266 DisplayError "-lst not supported for wget"
1267 exit 1
1268 ;;
1269 esac
1270 ;;
1271 -dir )
1272 case "$binary" in
1273 */curl )
1274 if [ "$raw" = true ]
1275 then
1276 SendRequest "$url/" |
1277 tr -s ' ' | tr ' ' '\t' | grep '.'
1278 else
1279 SendRequest "$url/" |
1280 tr -s ' ' | tr ' ' '\t' | cut -f 5,9 | grep '.'
1281 fi
1282 ;;
1283 */wget )
1284 DisplayError "-dir not supported for wget"
1285 exit 1
1286 esac
1287 ;;
1288 -ftp )
1289 if [ -t 0 ]
1290 then
1291 SendRequest "$url"
1292 else
1293 # read file names from stdin, URL contains base address of server
1294 while IFS=$'\t' read fl
1295 do
1296 SendRequest "$url/$fl"
1297 done
1298 fi
1299 ;;
1300 -dwn | -asp )
1301 if [ -t 0 ]
1302 then
1303 # file name is included in URL constructed from command line arguments
1304 fl=$( basename "$url" )
1305 DownloadOneFile "$url" "$fl"
1306 else
1307 # read file names from stdin, URL contains base address of server
1308 while IFS=$'\t' read fl
1309 do
1310 DownloadOneFile "$url/$fl" "$fl"
1311 done
1312 fi
1313 sfx=""
1314 if [ "$failed" -gt 0 ]
1315 then
1316 if [ "$failed" -gt 1 ]
1317 then
1318 sfx="S"
1319 fi
1320 echo "" >&2
1321 echo "${LOUD}FAILED TO DOWNLOAD $failed FILE${sfx}${INIT}"
1322 exit 1
1323 fi
1324 ;;
1325 * )
1326 DisplayError "'$1' is not a recognized nquire option"
1327 exit 1
1328 ;;
1329 esac
1330
1331 if [ "$timer" = true ]
1332 then
1333 printf "NQUIRE %s %s ELAPSED\n" "$elapsed" "$timeUnit" >&2
1334 fi