ukiyo / update.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
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// update once per day unless forced
var SITE_UPDATE_FREQUENCY = int64(86400) * 7
var CHAPTER_UPDATE_FREQUENCY = int64(86400)
var MAX_CONCURRENT_WORKERS = 3

func dictcat(a, b []map[string]string) []map[string]string {
	r := make([]map[string]string, len(a)+len(b))
	copy(r, a)
	copy(r[len(a):], b)
	return r
}

func UpdateSites(force ...bool) {
	Force := DefaultFalse(force...)

	var sites []Site
	now := time.Now().Unix()
	after := now
	if !Force {
		after -= SITE_UPDATE_FREQUENCY
	}

	q := "select name, url, priority, updated from sites WHERE updated < ? ORDER BY priority"
	rows, err := config.db.Query(q, after)
	if err != nil {
		panic(err)
	}

	for rows.Next() {
		site := new(Site)
		err = rows.Scan(&site.Name, &site.Url, &site.Priority, &site.Updated)
		if err != nil {
			fmt.Printf("Error: %s\n", err)
		}
		sites = append(sites, *site)
	}

	if len(sites) == 0 {
		return
	}

	if !Force {
		vPrintf("Updating %d sites last updated over 1 week ago:\n", len(sites))
	} else {
		vPrintf("Force-updating %d sites:\n", len(sites))
	}

	sem := make(chan bool, MAX_CONCURRENT_WORKERS)
	results := make([]map[string]string, 0)

	for _, s := range sites {
		sem <- true
		go func(site Site) {
			defer func() { <-sem }()
			ret := UpdateSite(site)
			results = dictcat(results, ret)
		}(s)
	}
	for i := 0; i < cap(sem); i++ {
		sem <- true
	}

	tx := Begin(config.db)

	vPrintf("Received %d total results\n", len(results))

	q = `insert or replace into series 
		(name, key, url, site, updated) values 
		(?, ?, ?, ?, coalesce((select updated from series where url = ?), 0))`

	for _, r := range results {
		tx.Exec(q, r["name"], r["key"], r["url"], r["site"], r["url"])
	}
	for _, s := range sites {
		tx.Exec("update sites set updated = ? where name = ?", now, s.Name)
	}
	tx.Commit()
}

func PrintDict(dict map[string]string) {
	fmt.Printf("{\n")
	for key, val := range dict {
		fmt.Printf("  \"%s\": \"%s\",\n", key, val)
	}
	fmt.Printf("}\n")
}

var UpdateUrls = map[string]string{
	"manga-access": "/manga/list",
	"mangahere":    "/mangalist/",
	"mangareader":  "/alphabetical",
	"mangafox":     "/manga/",
}

func UpdateMangaaccess(site *Site, doc *Document) []map[string]string {
	series := doc.CssSelect("#inner_page >div a")
	data := make([]map[string]string, len(series))
	for i, anchor := range series {
		data[i] = map[string]string{
			"site": site.Name,
			"name": strings.Trim(anchor.Text(), "\t "),
			"url":  UrlJoin(site.Url, anchor.Attr("href")),
		}
		spl := strings.Split(data[i]["url"], "/")
		data[i]["key"] = spl[len(spl)-1]
		data[i]["url"] = data[i]["url"] + "?mature_confirm=1"
	}

	fmt.Printf("Found %d series for manga-access\n", len(data))
	return data
}

func UpdateMangahere(site *Site, doc *Document) []map[string]string {
	series := doc.CssSelect("div.list_manga li a")
	data := make([]map[string]string, len(series))

	for i, anchor := range series {
		data[i] = map[string]string{
			"site": site.Name,
			"name": strings.Trim(anchor.Text(), " \t"),
			"url":  strings.Trim(anchor.Attr("href"), " \t"),
		}
		if !strings.HasPrefix(data[i]["url"], "http") {
			data[i]["url"] = UrlJoin(site.Url, data[i]["url"])
		}
		url := strings.TrimRight(data[i]["url"], "/")
		spl := strings.Split(url, "/")
		data[i]["key"] = spl[len(spl)-1]
	}
	fmt.Printf("Found %d series for mangahere\n", len(data))
	return data
}

func UpdateMangareader(site *Site, doc *Document) []map[string]string {
	fmt.Printf("Update mangareader\n")
	results := make([]map[string]string, 0)
	return results
}

func UpdateMangafox(site *Site, doc *Document) []map[string]string {
	fmt.Printf("Update mangafox\n")
	results := make([]map[string]string, 0)
	return results
}

var SiteUpdateFunctions = map[string]func(*Site, *Document) []map[string]string{
	"manga-access": UpdateMangaaccess,
	"mangahere":    UpdateMangahere,
	"mangareader":  UpdateMangareader,
	"mangafox":     UpdateMangafox,
}

func UpdateSite(site Site) []map[string]string {
	path, ok := UpdateUrls[site.Name]
	updater := SiteUpdateFunctions[site.Name]
	none := make([]map[string]string, 0)

	if !ok {
		fmt.Printf("Unknown site-name %s, skipping update.\n", site.Name)
		return none
	}
	url := UrlJoin(site.Url, path)
	vPrintf("Updating %s via %s\n", site.Name, url)

	cachefile := "./cache/" + site.Name + ".html"
	document, err := HttpGetDocument(url, cachefile)
	if err != nil {
		fmt.Printf("Error fetching site %s\n", site.Name)
		return none
	}
	defer document.Free()
	return updater(&site, document)
}

// update chapters for a series.  searches the db for all sites that have
// the series, and updates any which are too old for the chapters threshold
func UpdateChapters(name string, force ...bool) []*Chapter {
	Force := DefaultFalse(force...)

	now := time.Now().Unix()
	after := now
	if !Force {
		after -= CHAPTER_UPDATE_FREQUENCY
	}

	series := QuerySeries(config.db, "select * from series where name = ? AND updated < ?", name, after)

	if len(series) > 0 {
		if !Force {
			vPrintf("Updating %d sites for %s last updated over 1 week ago:\n", len(series), name)
		} else {
			vPrintf("Force-updating %d sites for %s:\n", len(series), name)
		}
		for _, s := range series {
			vPrintf("Updating %s (@%s, %s)\n", s.Name, s.Site, s.Url)
		}

		sem := make(chan bool, MAX_CONCURRENT_WORKERS)
		results := make([]map[string]string, 0)

		for _, s := range series {
			sem <- true
			go func(s *Series) {
				defer func() { <-sem }()
				updater := ChapterUpdateFunctions[s.Site]
				ret := updater(s)
				results = dictcat(results, ret)
			}(s)
		}
		for i := 0; i < cap(sem); i++ {
			sem <- true
		}

		tx := Begin(config.db)

		vPrintf("Received %d total results\n", len(results))

		for _, s := range series {
			Exec(tx, "delete from chapters where name=? and site=?", name, s.Site)
		}

		q := `insert or replace into chapters 
		(name, number, url, series, site) values 
		(?, ?, ?, ?, ?)`

		for _, r := range results {
			Exec(tx, q, r["name"], r["number"], r["url"], r["series"], r["site"])
		}
		for _, s := range series {
			Exec(tx, "update series set updated = ? where name = ? and site= ?", now, name, s.Site)
		}
		tx.Commit()
	}

	chapters, _ := FindChapters(true, name)
	return chapters
}

func UpdateChaptersMangaaccess(series *Series) []map[string]string {
	fmt.Printf("Updating manga-access for series %s\n", series.Name)
	none := make([]map[string]string, 0)

	cachefile := fmt.Sprintf("./cache/%s-%s.html", series.Name, series.Site)
	document, err := HttpGetDocument(series.Url, cachefile)
	if err != nil {
		fmt.Printf("Error getting %s\n", series.Name)
		return none
	}
	defer document.Free()
	base := BaseUrl(series.Url)

	anchors := document.CssSelect("a.download-link")
	data := make([]map[string]string, len(anchors))
	for i, anchor := range anchors {
		data[i] = map[string]string{
			"site":   series.Site,
			"series": series.Name,
			"name":   strings.Trim(anchor.Text(), " \t\r\n"),
			"url":    strings.Trim(anchor.Attr("href"), " \t\r\n"),
			"number": "",
		}
		if !strings.HasPrefix(data[i]["url"], "http") {
			data[i]["url"] = UrlJoin(base, data[i]["url"])
		}
		numelem := anchor.CssSelect("strong")
		if len(numelem) > 0 {
			data[i]["number"] = numelem[0].Text()
		}
	}
	vPrintf("Found %d chapters on manga-access\n", len(data))
	return data
}

func UpdateChaptersMangahere(series *Series) []map[string]string {
	fmt.Printf("Updating mangahere for series %s\n", series.Name)
	none := make([]map[string]string, 0)

	cachefile := fmt.Sprintf("./cache/%s-%s.html", series.Name, series.Site)
	document, err := HttpGetDocument(series.Url, cachefile)
	if err != nil {
		fmt.Printf("Error getting %s\n", series.Name)
		return none
	}
	defer document.Free()
	base := BaseUrl(series.Url)

	anchors := document.CssSelect(".detail_list li a")
	data := make([]map[string]string, len(anchors))
	for i, anchor := range anchors {
		data[i] = map[string]string{
			"site":   series.Site,
			"series": series.Name,
			"name":   strings.Trim(anchor.Text(), " \t\n\r"),
			"url":    strings.Trim(anchor.Attr("href"), " \t\n\r"),
			"number": "",
		}
		spl := strings.Split(strings.TrimRight(data[i]["url"], "/"), "/")
		data[i]["number"] = FindNumber(spl[len(spl)-1])
		if len(data[i]["number"]) == 0 {
			data[i]["number"] = FindNumber(data[i]["name"])
		} else {
			// remove leading junk
			data[i]["number"] = strings.TrimLeft(data[i]["number"], " \t0")
		}
		if !strings.HasPrefix(data[i]["url"], "http") {
			data[i]["url"] = UrlJoin(base, data[i]["url"])
		}
	}
	vPrintf("Found %d chapters on mangahere\n", len(data))
	return data

}
func UpdateChaptersMangareader(series *Series) []map[string]string {
	fmt.Printf("Updating mangareader for series %s\n", series.Name)
	return []map[string]string{}
}
func UpdateChaptersMangafox(series *Series) []map[string]string {
	fmt.Printf("Updating mangafox for series %s\n", series.Name)
	return []map[string]string{}
}

var ChapterUpdateFunctions = map[string]func(*Series) []map[string]string{
	"manga-access": UpdateChaptersMangaaccess,
	"mangahere":    UpdateChaptersMangahere,
	"mangareader":  UpdateChaptersMangareader,
	"mangafox":     UpdateChaptersMangafox,
}

func SelectUrl(chapter *Chapter) (string, string) {
	spl := strings.Split(chapter.Site, ",")
	m := make(map[string]int, len(spl))
	for i, s := range spl {
		m[s] = i
	}
	for _, s := range config.SiteOrder {
		_, ok := m[s]
		if ok {
			spl = strings.Split(chapter.Url, ",")
			return s, spl[m[s]]
		}
	}
	return "", ""
}

// TODO: do everything through this, as it's superior to what i've been doing

type Downloader interface {
	// get page urls via a document and the url string of that document
	GetPageUrls(string, *Document) []string
	GetImageUrl(*Document) string
}

type MangaAccess struct{}

func (m *MangaAccess) GetPageUrls(url string, doc *Document) []string {
	options := doc.CssSelect("select#page_switch option")
	if len(options) < 1 {
		return []string{}
	}
	urls := make([]string, len(options)-1)
	base := BaseUrl(url)

	for i, o := range options[1:] {
		urls[i] = UrlJoin(base, o.Attr("value"))
	}
	return urls
}

func (m *MangaAccess) GetImageUrl(doc *Document) string {
	img := doc.CssSelect("div#pic img")
	if len(img) == 0 {
		return ""
	}
	return img[0].Attr("src")
}

type MangaHere struct{}

func (m *MangaHere) GetPageUrls(url string, doc *Document) []string {
	options := doc.CssSelect(".readpage_top .go_page option")
	if len(options) < 1 {
		return []string{}
	}
	urls := make([]string, len(options)-1)
	base := BaseUrl(url)

	for i, o := range options[1:] {
		fragment := o.Attr("value")
		if strings.HasPrefix(fragment, "http") {
			urls[i] = fragment
		} else {
			urls[i] = UrlJoin(base, fragment)
		}
	}
	return urls
}

func (m *MangaHere) GetImageUrl(doc *Document) string {
	img := doc.CssSelect("#image")
	if len(img) == 0 {
		return ""
	}
	return img[0].Attr("src")
}

var Downloaders = map[string]Downloader{
	"manga-access": new(MangaAccess),
	"mangahere":    new(MangaHere),
}

func DownloadChapter(chapter *Chapter) error {
	site, url := SelectUrl(chapter)
	// fmt.Printf(" %s %s (%s, %s)\n", chapter.Series, chapter.Number, site, url)
	downloader := Downloaders[site]

	doc, err := HttpGetDocument(url)
	if err != nil {
		return err
	}
	var destzip string
	series := chapter.Series
	if config.UseUnderscores {
		series = strings.Replace(series, " ", "_", -1)
	}
	destpath := filepath.Join(config.DownloadPath, series, chapter.Number)
	if chapter.Numberf != 0 {
		destzip = filepath.Join(config.DownloadPath, series,
			fmt.Sprintf("%s-c%03d.zip", series, int(chapter.Numberf)))
	} else {
		destzip = filepath.Join(config.DownloadPath, series,
			fmt.Sprintf("%s-c%s.zip", series, chapter.Number))
	}

	page_urls := downloader.GetPageUrls(url, doc)
	numwidth := len(fmt.Sprintf("%d", len(page_urls)))
	numfmt := fmt.Sprintf("%%0%dd", numwidth)
	// fmt.Printf("Making destination dir: %s", destpath)
	os.MkdirAll(destpath, 0755)
	// fmt.Printf("Number format: %s\n", numfmt)

	vPrintf("Page Urls: %v\n", page_urls)
	update := fmt.Sprintf("Downloading %s %s (from %s): %%d of %%d", chapter.Series, chapter.Number, site)

	type Img struct {
		num int
		url string
	}

	sem := make(chan bool, MAX_CONCURRENT_WORKERS)
	images := make(chan Img, len(page_urls))
	completed := make(chan int)
	// send the first image on the images channel
	images <- Img{1, downloader.GetImageUrl(doc)}

	// print a little updater in place about pages we're loading
	go func(max int) {
		c := 0
		fmt.Printf(update+"\r", c, max)
		os.Stdout.Sync()
		for _ = range completed {
			c++
			fmt.Printf(update+"\r", c, max)
			os.Stdout.Sync()
			if c == max {
				fmt.Printf(update+"\n", c, max)
				return
			}
		}
	}(len(page_urls))

	for i, s := range page_urls {
		sem <- true
		go func(num int, url string) {
			defer func() { <-sem }()
			doc, err := HttpGetDocument(url)
			if err != nil {
				fmt.Printf("Error fetching page %03d (%s)\n", num, url)
				return
			}
			images <- Img{num, downloader.GetImageUrl(doc)}
		}(i+2, s)
	}

	for i := 0; i < len(page_urls); i++ {
		sem <- true
		go func() {
			defer func() { <-sem }()
			img := <-images
			if len(img.url) == 0 {
				fmt.Printf("Error fetching page %03d (null url)\n", img.num)
				return
			}
			ext := FileExtension(img.url)
			name := fmt.Sprintf(numfmt+".%s", img.num, ext)
			destfile := filepath.Join(destpath, name)
			// fmt.Printf("#%d (%s) to %s\n", img.num, img.url, destfile)
			HttpDownloadTo(img.url, destfile)
			completed <- 1
		}()
	}
	// wait for everything to finish...
	for i := 0; i < cap(sem); i++ {
		sem <- true
	}

	ZipDir(destpath, destzip)
	os.RemoveAll(destpath)

	return nil
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.