« get me outta code hell

crawl-recursive.js - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/crawl-recursive.js
blob: 8d33deddd25739918b6afbcce1f9a064cf388fca (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
'use strict'

const MAX_DOWNLOAD_ATTEMPTS = 5

const fetch = require('node-fetch')
const { getHTMLLinks } = require('./crawl-links')

function crawl(absURL, attempts = 0) {
	return fetch(absURL)
		.then(res => res.text().then(text => playlistifyParse(text, absURL)), err => {
			console.error('Failed to download: ' + absURL)

			if (attempts < MAX_DOWNLOAD_ATTEMPTS) {
				console.error(
					'Trying again. Attempt ' + (attempts + 1) +
					'/' + MAX_DOWNLOAD_ATTEMPTS + '...'
				)
				return crawl(absURL, attempts + 1)
			} else {
				console.error(
					'We\'ve hit the download attempt limit (' +
					MAX_DOWNLOAD_ATTEMPTS + '). 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 playlistifyParse(text, absURL) {
	const links = getHTMLLinks(text)
	const verbose = process.argv.includes('--verbose')

	return Promise.all(links.map(link => {
		const [ title, href ] = link

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

			if (verbose) console.log('[Dir] ' + absURL + href)
			return crawl(absURL + href)
				.then(res => [title, res])
		} else {
			// It's a file!

			if (verbose) console.log('[File] ' + absURL + href)
			return Promise.resolve([title, absURL + href])
		}
	}))
}

if (process.argv.length === 2) {
	console.log('Usage: crawl-recursive http://example.com/example/path')
} else {
	let url = process.argv[2]

	if (!(url.endsWith('/'))) {
		url = url + '/'
	}

	crawl(url)
		.then(res => console.log(JSON.stringify(res, null, 2)))
		.catch(err => console.error(err))
}