« get me outta code hell

crawl-http.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/crawl-http.js
blob: 4925f1238a40f20602da0ed4a5fcae7decace22b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env node

'use strict'

const fetch = require('node-fetch')
const cheerio = require('cheerio')
const url = require('url')
const path = require('path')
const processArgv = require('./process-argv')

function crawl(absURL, opts = {}, internals = {}) {
  // Recursively crawls a given URL, following every link to a deeper path and
  // recording all links in a tree (in the same format playlists use). Makes
  // multiple attempts to download failed paths.

  const {
    verbose = false,

    maxAttempts = 5,

    keepSeparateHosts = false,

    keepAnyFileType = false,
    fileTypes = ['wav', 'ogg', 'oga', 'mp3', 'mp4', 'm4a', 'mov'],

    filterRegex = null
  } = opts

  if (!internals.attempts) internals.attempts = 0

  // TODO: Should absURL initially be added into this array? I'd like to
  // re-program this entire crawl function to make more sense - "internal"
  // dictionaries aren't quite easy to reason about!
  if (!internals.allURLs) internals.allURLs = []

  const verboseLog = text => {
    if (verbose) {
      console.log(text)
    }
  }

  const absURLObj = new url.URL(absURL)

  return fetch(absURL)
    .then(
      res => res.text().then(text => {
        const links = getHTMLLinks(text)

        return Promise.all(links.map(link => {
          let [ name, href ] = link

          // If the name (that's the content inside of <a>..</a>) ends with a
          // slash, that's probably just an artifact of a directory lister;
          // not actually part of the intended content. So we remove it!
          if (name.endsWith('/')) {
            name = name.slice(0, -1)
          }

          const urlObj = new url.URL(href, absURL)
          const linkURL = url.format(urlObj)

          if (internals.allURLs.includes(linkURL)) {
            verboseLog("[Ignored] Already done this URL: " + linkURL)

            return false
          }

          internals.allURLs.push(linkURL)

          if (filterRegex && !(filterRegex.test(linkURL))) {
            verboseLog("[Ignored] Failed regex: " + linkURL)

            return false
          }

          if (!keepSeparateHosts && urlObj.host !== absURLObj.host) {
            verboseLog("[Ignored] Inconsistent host: " + linkURL)

            return false
          }

          if (href.endsWith('/')) {
            // It's a directory!

            verboseLog("[Dir] " + linkURL)

            return crawl(linkURL, opts, Object.assign({}, internals))
              .then(({ items }) => ({name, items}))
          } else {
            // It's a file!

            const extensions = fileTypes.map(t => '.' + t)

            if (
              !keepAnyFileType &&
              !(extensions.includes(path.extname(href)))
            ) {
              verboseLog("[Ignored] Bad extension: " + linkURL)

              return false
            }

            verboseLog("[File] " + linkURL)
            return Promise.resolve({name, downloaderArg: linkURL})
          }
        }).filter(Boolean)).then(items => ({items}))
      }),

      err => {
        console.warn("Failed to download: " + absURL)

        if (internals.attempts < maxAttempts) {
          console.warn(
            `Trying again. Attempt ${internals.attempts + 1}/${maxAttempts}...`
          )

          return crawl(absURL, opts, Object.assign({}, internals, {
            attempts: internals.attempts + 1
          }))
        } else {
          console.error(
            "We've hit the download attempt limit (" + maxAttempts + "). " +
            "Giving up on this path."
          )

          throw 'FAILED_DOWNLOAD'
        }
      }
    )
    .catch(error => {
      if (error === 'FAILED_DOWNLOAD') {
        // Debug logging for this is already handled above.
        return []
      } else {
        throw error
      }
    })
}

function getHTMLLinks(text) {
  // Never parse HTML with a regex!
  const $ = cheerio.load(text)

  return $('a').get().map(el => {
    const $el = $(el)
    return [$el.text(), $el.attr('href')]
  })
}

async function main(args) {
  if (args.length === 0) {
    console.log("Usage: crawl-http http://.../example/path/ [opts]")
    return
  }

  // Should be 'topURL' or something (also change 'absURL'). We don't want to
  // shadow 'const url = require(..)'.
  const url = args[0]

  let maxDownloadAttempts = 5
  let verbose = false
  let filterRegex = null

  await processArgv(args.slice(1), {
    '-max-download-attempts': function(util) {
      // --max-download-attempts <max>  (alias: -m)
      // Sets the maximum number of times to attempt downloading the index for
      // any one directory. Defaults to 5.

      maxDownloadAttempts = util.nextArg()
    },

    'm': util => util.alias('-max-download-attempts'),

    '-regex': function(util) {
      // --regex <regex>  (alias: -r)
      // Sets the regular expression string used for filtering specific URLs.
      // This regex is tested against every crawled URL. If the test matches,
      // the URL it is given is kept; otherwise it is skipped. Defaults to no
      // regex.

      filterRegex = new RegExp(util.nextArg())
    },

    'r': util => util.alias('-regex'),

    '-verbose': function(util) {
      // --verbose  (alias: -v)
      // Logs out extra verbose data about what files are being crawled and
      // such. Defaults to false.

      verbose = true
      console.log('Outputting verbosely.')
    },

    'v': util => util.alias('-verbose'),
  })

  const downloadedPlaylist = await crawl(url, {
    maxAttempts: maxDownloadAttempts,
    verbose: verbose,
    filterRegex: filterRegex
  })

  console.log(JSON.stringify(downloadedPlaylist, null, 2))
}

module.exports = {main, crawl}

if (require.main === module) {
  main(process.argv.slice(2))
    .catch(err => console.error(err))
}