예제 #1
0
func GetM3U8andRewrite(w http.ResponseWriter, r *http.Request) {
	// Dirty CORS workaround, does not work too well right now
	// because CORS is also being applied to the .ts files
	// found in the .m3u8

	vars := mux.Vars(r)

	lowercasedchannelname := strings.ToLower(vars["channelname"])
	statuscode, url := retrieveaudio.Get(lowercasedchannelname)
	if statuscode == 0 {
		w.WriteHeader(404)
		w.Write([]byte("Stream not found."))
	} else if statuscode == 1 {
		cli := http.DefaultClient
		req, err := http.NewRequest("GET", url, nil)
		if err != nil {
			w.WriteHeader(400)
			w.Write([]byte("Something went wrong, contact developer at @equoia"))
			log.Println(err)
		}
		req.Header.Set("User-Agent", "letr.it/twitchaudio 1.0")

		resp, err := cli.Do(req)
		if err != nil {
			log.Println("Looks like something went wrong with the request:\n", err)
		}
		defer resp.Body.Close()
		tmpbody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println(err)
		}
		lines := strings.Split(string(tmpbody), "\n")
		r := regexp.MustCompile(`(.*ttvnw.net\/.*\/audio_only\/)`)

		vodfileEndpoint := r.FindStringSubmatch(url)[1]

		for i, line := range lines {
			if strings.Contains(line, "index") {
				lines[i] = vodfileEndpoint + line
			}
		}

		output := strings.Join(lines, "\n")

		w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
		w.WriteHeader(200)
		w.Write([]byte(output))

	}
}
예제 #2
0
func saveBlocks(params martini.Params, w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	keyIDStr := params["key"]
	if keyIDStr == "" {
		handleError(c, w, errors.New("the pageID not found."), http.StatusInternalServerError)
		return
	}

	var b map[string]interface{}
	if err := getRequestJson(w, r, &b); err != nil {
		handleError(c, w, err, http.StatusBadRequest)
		return
	}

	intID, err := strconv.ParseInt(keyIDStr, 10, 64)
	if err != nil {
		handleError(c, w, err, http.StatusBadRequest)
		return
	}
	pageKey := model.NewPageKey(c, intID)

	var p model.Page
	if err := ds.Get(c, pageKey, &p); err != nil {
		handleError(c, w, err, http.StatusBadRequest)
		return
	}

	err = datastore.RunInTransaction(c, func(c context.Context) error {
		// TODO make async
		for id, value := range b {
			log.Infof(c, "saving block. id:%s, value:%s", id, value)
			r := regexp.MustCompile(`^ctpl_block:(true|false):(\w+):(\d+)$`)
			gr := r.FindStringSubmatch(id)
			if gr == nil {
				return errors.New("illegal block id:" + id)
			}

			global, err := strconv.ParseBool(gr[1])
			if err != nil {
				return err
			}

			areaID := gr[2]
			strBlockID := gr[3]
			blockID, err := strconv.ParseInt(strBlockID, 10, 64)
			if err != nil {
				return err
			}

			var pkey *datastore.Key
			if global {
				pkey = model.NewGlobalPageKey(c)
			} else {
				pkey = pageKey
			}
			akey := model.NewAreaKey(c, areaID, pkey)
			bkey := model.NewHTMLBlockKey(c, blockID, akey)

			var block model.HTMLBlock
			if err := ds.Get(c, bkey, &block); err != nil {
				return errors.WrapOr(err)
			}

			var ok bool
			block.Value, ok = value.(string)
			if !ok {
				return errors.New(
					fmt.Sprintf("illegal block value type :%T", value))
			}

			if err = ds.Put(c, &block); err != nil {
				return errors.WrapOr(err)
			}

			// save backup entity when HTMLBlock saved.
			blocks := []*model.HTMLBlock{&block}
			backupHTMLBlockFunc.Call(c, uuid.New(), blocks)
		}
		return nil
	}, &datastore.TransactionOptions{XG: true})
	if err != nil {
		handleError(c, w, err, http.StatusInternalServerError)
		return
	}
}
예제 #3
0
파일: upload.go 프로젝트: haste/tiers
func UploadHandler(w http.ResponseWriter, r *http.Request) {
	session, _ := session.Get(r, "tiers")
	userid, ok := session.Values["user"]

	if !ok {
		return
	}

	reader, err := r.MultipartReader()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// XXX: Handle errors.
	var db, _ = sql.Open("mysql", conf.Config.Database)
	defer db.Close()

	for {
		part, err := reader.NextPart()
		if err != nil {
			break
		}

		// if part.FileName() is empty, skip this iteration.
		if part.FileName() == "" {
			continue
		}

		var fileName string
		var t time.Time
		// profile_20140815_135412_0.png
		r := regexp.MustCompile("^(ingress|profile)_(\\d+)_(\\d+)_\\d+\\.png$")
		if r.MatchString(part.FileName()) {
			m := r.FindStringSubmatch(part.FileName())
			t, _ = time.ParseInLocation("20060102150405", m[2]+m[3], time.Local)

			fileName = fmt.Sprintf("%d_%s", userid, part.FileName())
		} else {
			t = time.Now()
			fileName = fmt.Sprintf("%d_%s.png", userid, t.Format("20060102_150405"))
		}

		dst, err := os.Create(conf.Config.Cache + fileName)
		defer dst.Close()

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		if _, err := io.Copy(dst, part); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		reader, err := os.Open(conf.Config.Cache + fileName)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer reader.Close()

		m, _, err := image.Decode(reader)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		width := m.Bounds().Dx()

		// XXX: Handle errors...
		db.Exec(`
			INSERT INTO tiers_queues(user_id, timestamp, file, ocr_profile)
			VALUES(?, ?, ?, ?)
		`, userid, t.Unix(), fileName, width)
	}

	var numQueue float32
	db.QueryRow(`SELECT count(id) FROM tiers_queues WHERE processed = 0`).Scan(&numQueue)

	var processTime float32
	db.QueryRow(`
		SELECT avg(processtime) AS processtime
		FROM (
			SELECT processtime
			FROM tiers_queues
			WHERE processed = 1
			ORDER BY id DESC
			LIMIT 10
		) T
	`).Scan(&processTime)

	queueText := fmt.Sprintf(
		"Your file has been added to the queue and should be processed within %.1f seconds.",
		numQueue*processTime/1000,
	)

	if r.Header.Get("X-Requested-With") == "XMLHttpRequest" {
		data, _ := json.Marshal(map[string]interface{}{
			"success": true,
			"message": queueText,
		})
		fmt.Fprintf(w, "%s", data)
	} else {
		http.Redirect(w, r, "/", 302)
	}

	queue.Queue <- true
}