Пример #1
0
func ProcessRequest(request DownloadRequest) {
	var tempFile string = MakeTempFileName(request.url, ".flv")
	var tempFileSansExtension string
	{
		pathDotIndex := strings.LastIndex(tempFile, ".")
		tempFileSansExtension = tempFile[0:pathDotIndex]
	}

	var cmd *exec.Cmd = MakeCommand(&request, tempFile)

	if cmd == nil {
		request.WriteError("forming the download command", nil)
		return
	}

	var proc *StdoutProcessor
	if pipe, e := cmd.StdoutPipe(); e != nil {
		request.WriteError("setting youtube-dl pipe", e)
		return
	} else {
		proc = NewStdoutProcessor(&pipe)
	}

	if e := cmd.Start(); e != nil {
		request.WriteError("running youtube-dl", e)
		return
	}

	var state DownloadState = kStarting
	var data map[string]interface{}
	var e os.Error

	for {
		status, e := proc.ParseOneStatusMessage()
		if e != nil {
			if state < kExtractingAudio {
				request.WriteError("downloading the video", e)
				return
			} else {
				break
			}
		} else if status == nil {
			continue
		}

		if status.state != kDownloadingVideo && (status.state == 0 || status.state == state) {
			continue
		}

		fmt.Printf("Proc SM: %v\n", status)
		if status.state >= kDownloadingVideo && state != status.state {
			if data, e = ReadJson(tempFile + ".info.json"); e != nil {
				request.WriteError("reading video JSON", e)
				return
			}
			status.title = data["title"].(string)
		}
		state = status.state

		status.requestId = request.id
		request.statusChannel <- *status
	}

	var finalFileBaseName = data["title"].(string) + "." + *outputFormat
	var finalFile = request.basePath + "/" + finalFileBaseName
	if _, e := CopyFile(finalFile,
		tempFileSansExtension+"."+*outputFormat); e != nil {
		request.WriteError("tagging", e)
		return
	}

	request.statusChannel <- StatusMessage{request.id, kTagging, "", "", 0, 0, 0, nil, ""}
	var c = exec.Command("lltag", "--yes", "-G", "--rename=%a/%t", finalFileBaseName)
	c.Dir = request.basePath
	out, ioError := c.StdoutPipe()
	if ioError != nil {
		request.WriteError("starting the tagger", ioError)
		return
	}

	var in io.WriteCloser
	in, ioError = c.StdinPipe()
	if ioError != nil {
		request.WriteError("starting the tagger", ioError)
		return
	}

	var link string
	if e = c.Start(); e != nil {
		request.WriteError("tagging", e)
		return
	} else {
		in.Write([]byte(strings.Repeat("y\n", 20)))
		outData, e := ioutil.ReadAll(out)
		if e != nil {
			request.WriteError("reading the tagger output", e)
			return
		}
		match := regexp.MustCompile("New filename is '([^\n]*)'\n").FindStringSubmatch(string(outData))
		fmt.Printf("out data: %s\n\nmatch: %v\n", string(outData), match)
		if match == nil {
			request.WriteError("finding the output file", os.NewError("fail"))
			return
		}

		link = "/files/" + match[1]
	}

	fmt.Printf("Link: %s\n", link)
	request.statusChannel <- StatusMessage{request.id, kComplete, link, "", 0, 0, 0, nil, ""}
}