downloadmgr

package module
v0.0.0-...-2c74f99 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2022 License: Apache-2.0 Imports: 19 Imported by: 1

README

downloadmgr

Download manager is package for downloading files from the given url.

Channel

DownloadMgr has 1 Prehandlee channel and 4 Download channel to handle the download

  • Prehandle channel: This channel will classify tasks and assign tasks to different channels according to whether the download can be resumed
  • QuickDownload channel: For quick task download, do download task by FIFO
  • RandomDownload channel: For normal task, task will be assigned to this channel if resumable. do download task randomly
  • UnpauseDownload channel: For normal task, unresumable task will be assigned to this channel, do download task by FIFO
  • UnpauseSlowDownload channel: For normal task, if task is unresumable and download speed is low, it will be pushed into this channel do download task by FIFO

There are two different download task: QuickTask and NormalTask

QuickTask: It needs to be downloaded as soon as possible within a certain period of time. This task goes directly into QuickDownload channel.

NormalTask: General download tasks without timelimit. It will first enter the prehandle channel and be classified according to whether it can resume or not.

Each channel has a idle list. Tasks are queued based on the start time.Channel will start several goroutines, cyclically check whether there are tasks in the idlelist, and do download tasks.

Callback
  • onDownloadSuccess: run when download success
  • onDownloadFailed: run when download failed(after retried several times)
  • onDownloading: run every 2 seconds when downloading
  • onDownloadCanceled: run when task canceled
  • onDownloadSlowSpeed: run when the download speed low
Download process

The download status of the task will be detected every 2 seconds when downloading. OnDownloading callback will trigger here.

The download task will be interrupted if the download task is abnormal. The failed task will get a chance to retry unless no sapce or task canceled

Example

func main() {
	//logger
	logger, _ := LogrusULog.New("./logs", 2, 20, 30)
	logger.SetLevel(ULog.DebugLevel)

	dm := downloadmgr.NewDownloadMgr()
	dm.SetLogger(logger)

	//set some ignore header
	dm.SetIgnoreHeader([]string{})

    //example url
	targetUrl := [4]string{}
	targetUrl[0] = "https://golang.org/dl/go1.17.2.darwin-amd64.pkg"
	targetUrl[1] = "https://assets.meson.network:10443/static/js/core.min.js"
	targetUrl[2] = "https://coldcdn.com/api/cdn/wr1cs5/video/spacex2.mp4"

	//start 10 download task
	for i := 0; i < 10; i++ {
		saveFile := [3]string{}
		saveFile[0] = fmt.Sprintf("./downloadFile/1/go1.17.2.darwin-amd64-%d.pkg", i)
		saveFile[1] = fmt.Sprintf("./downloadFile/2/core.min-%d.js", i)
		saveFile[2] = fmt.Sprintf("./downloadFile/4/spacex2-%d.mp4", i)

		needEncrypt := false
		if rand.Intn(2) == 1 {
			needEncrypt = true
		}

		index := rand.Intn(4)

		task, err := dm.AddNormalDownloadTask(
			fmt.Sprintf("nameHash-%d", i),
			12345,
			saveFile[index],
			targetUrl[index],
			needEncrypt,
			0,
			func(task *downloadmgr.Task) {
				info, _ := os.Stat(task.SavePath)
				logger.Infoln("success", task.Id, "targetUrl", targetUrl[index], "filePath", task.SavePath, "size", info.Size())
			},
			func(task *downloadmgr.Task) {
				logger.Infoln("fail", task.Id, "fail reason:", task.FailReason)
			},
			func(task *downloadmgr.Task) {
				logger.Infoln("cancel", task.Id)
			},
			func(task *downloadmgr.Task) {
				logger.Debugln("downloading", task.Id, task.Response.Progress(), task.Response.BytesPerSecond())
			},
			func(task *downloadmgr.Task) {
				logger.Debugln("speedSlow", task.Id, task.Response.Progress(), task.Response.BytesPerSecond())
			})

		if err != nil {
			logger.Errorln("task error", err)
		}

		logger.Debugln(task)
	}

	time.Sleep(600 * time.Second)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrOriginUrlProtocol = errors.New("origin url is not http protocol")

Functions

This section is empty.

Types

type BrokenType

type BrokenType int

type DownloadMgr

type DownloadMgr struct {
	// contains filtered or unexported fields
}

func NewDownloadMgr

func NewDownloadMgr() *DownloadMgr

NewDownloadMgr new instance of Download manager. Background jobs will start to classify and download

func (*DownloadMgr) AddNormalDownloadTask

func (dm *DownloadMgr) AddNormalDownloadTask(nameHash string, folderId uint32, savePath string, targetUrl string, needEncrypt bool, sizeLimit int64,
	onSuccess func(task *Task),
	onFail func(task *Task),
	onCancel func(task *Task),
	onDownloading func(task *Task),
	slowSpeedCallback func(task *Task)) (*Task, error)

AddNormalDownloadTask start a normal download task. Task will be push to different download channel depends on it is resumable or not

func (*DownloadMgr) AddQuickDownloadTask

func (dm *DownloadMgr) AddQuickDownloadTask(nameHash string, folderId uint32, savePath string, targetUrl string, expireTime int64, needEncrypt bool, sizeLimit int64,
	onSuccess func(task *Task),
	onFail func(task *Task),
	onCancel func(task *Task),
	onDownloading func(task *Task)) (*Task, error)

AddQuickDownloadTask start a quick download task. Quick tasks start the download as soon as possible and have an expiration time. The task will fail when it expires.

func (*DownloadMgr) GetIdleTaskSize

func (dm *DownloadMgr) GetIdleTaskSize() (map[string]int, int)

func (*DownloadMgr) GetLogger

func (dm *DownloadMgr) GetLogger() ULog.Logger

func (*DownloadMgr) GetTaskInfo

func (dm *DownloadMgr) GetTaskInfo(id uint64) *Task

func (*DownloadMgr) GetTaskMap

func (dm *DownloadMgr) GetTaskMap() *sync.Map

func (*DownloadMgr) SetIgnoreHeader

func (dm *DownloadMgr) SetIgnoreHeader(ignores []string)

func (*DownloadMgr) SetLogger

func (dm *DownloadMgr) SetLogger(logger ULog.Logger)

type FailReasonType

type FailReasonType int
const (
	NoFail FailReasonType = iota
	Fail_NoSpace
	Fail_Expire
	Fail_SizeLimit
	Fail_RequestError
	Fail_Other
)

type Task

type Task struct {
	//init with input param
	Id         uint64
	NameHash   string
	FolderId   uint32
	TargetUrl  string
	SavePath   string
	TaskType   TaskType
	ExpireTime int64 //for quick download, cancel task if expiry,if set 0 never expire
	Encrypt    bool
	SizeLimit  int64 //if >0 means file has size limit, if download data > size limit, task fail

	//modify when downloading
	Response   *grab.Response
	Status     TaskStatus
	FailReason FailReasonType
	// contains filtered or unexported fields
}

func (*Task) CancelDownload

func (t *Task) CancelDownload()

CancelDownload cancel download task by manual

func (*Task) ToString

func (t *Task) ToString() string

ToString for debug

type TaskStatus

type TaskStatus int
const (
	New TaskStatus = iota
	Pause
	Downloading
	Success
	Fail
)

type TaskType

type TaskType int
const (
	QuickTask TaskType = iota
	NormalTask
)

Directories

Path Synopsis
bps
Package bps provides gauges for calculating the Bytes Per Second transfer rate of data streams.
Package bps provides gauges for calculating the Bytes Per Second transfer rate of data streams.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL