This repository has been archived by the owner on Feb 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdesearch.go
108 lines (90 loc) · 2.3 KB
/
desearch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Download Research Papers (because information should be free for all)
// A wrapper around sci-hub.tw (credit: Alexandra Elbakyan)
// Author - Kumar Ashwin
// Version - v2.0
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"github.com/fatih/color"
)
func init() {
flag.Usage = func() {
h := `
desearch v2.0
CLI Wrapper for sci-hub.tw, download research papers for free!
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Usage:
desearch [url]
Author:
[Kumar Ashwin]([email protected])
`
fmt.Fprintf(os.Stderr, h)
}
}
func main() {
if len(os.Args) > 2 {
fmt.Print("Enter valid Arguments. Type `desearch -h` for help!\n")
os.Exit(1)
} else {
flag.Parse()
base := "https://sci-hub.tw/"
research := os.Args[1]
completeURL := base + research
response, err := http.Get(completeURL)
checkErr(err)
defer response.Body.Close()
dataInBytes, err := ioutil.ReadAll(response.Body)
checkErr(err)
pageContent := string(dataInBytes)
linkIndex := strings.Index(pageContent, "?download=true")
lastIndex := linkIndex
startIndex := 0
for true {
if strings.Compare(string(pageContent[linkIndex]), "'") == 0 {
startIndex = linkIndex
break
}
linkIndex = linkIndex - 1
}
downloadLink := pageContent[startIndex+1 : lastIndex]
if !strings.HasPrefix(downloadLink, "http") {
downloadLink = "https:" + downloadLink
}
fmt.Print("Downloading Research Paper: ")
// Building FileName from Download Link
fileURL, err := url.Parse(downloadLink)
checkErr(err)
path := fileURL.Path
segment := strings.Split(path, "/")
filename := segment[len(segment)-1]
color.Cyan(filename)
// Creating a file to put in data
output, err := os.Create(filename)
checkErr(err)
defer output.Close()
response, err = http.Get(downloadLink)
checkErr(err)
defer response.Body.Close()
// Checking for response code to be OK
if response.StatusCode != http.StatusOK {
fmt.Printf("Cannot Download File: Status not OK!")
}
// Copy the data to the output file created.
_, err = io.Copy(output, response.Body)
checkErr(err)
fmt.Print("Done\n")
}
}
func checkErr(err error) {
if err != nil {
color.Red("Cannot download specified paper...please check manually @ sci-hub.tw\nSorry for the inconvenience!")
os.Exit(1)
}
}