Beispiel #1
0
func setupThread(qualifier string) {
	tokenChan := make(chan string, 1)
	go fetchToken(tokenChan)

	mbid, err := setupMailbox(qualifier)
	if err != nil {
		return
	}

	session := auth.Session{
		Duration: 6 * time.Hour,
	}
	latestNonceToken = <-tokenChan
	session.Token = latestNonceToken
	session.Signature, chatInitErr = session.SignatureFor(hearstMailboxKey)
	if chatInitErr != nil {
		return
	}

	postPayload := map[string]string{
		"Subject": "guide public chat",
	}
	postBytes, err := json.Marshal(postPayload)
	if err != nil {
		chatInitErr = err
		return
	}
	postBody := bytes.NewBuffer(postBytes)

	threadUrl := fmt.Sprintf("%s/thread/", hearstServer)
	req, err := http.NewRequest("POST", threadUrl, postBody)
	req.Header.Add("X-Hearst-Mailbox", mbid)
	req.Header.Add("X-Hearst-Session", session.String())

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		chatInitErr = err
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		chatInitErr = err
		return
	}

	var responseJson map[string]string
	if chatInitErr = json.Unmarshal(body, &responseJson); chatInitErr != nil {
		return
	}
	threadId := responseJson["Id"]
	datastore.Blob{"guide-chat-thread-id-" + qualifier}.Set(threadId)
	hearstThreads[qualifier] = HearstThreadInfo{
		ThreadId:  threadId,
		MailboxId: mbid,
	}
}
Beispiel #2
0
func (cc AuthController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if chatInitErr != nil {
		http.Error(w, "Error initializing chat:"+chatInitErr.Error(), 500)
		return
	}

	qualifier := "chat"
	comps := strings.Split(r.URL.Path, "/")
	if len(comps) > 0 && comps[0] != "" {
		qualifier = comps[0]
	}

	if _, ok := hearstThreads[qualifier]; !ok {
		if e := loadThread(qualifier); e != nil {
			setupThread(qualifier)
		}
	}

	threadInfo, ok := hearstThreads[qualifier]
	if !ok {
		errorMessage := "Error initializing chat"
		if chatInitErr != nil {
			errorMessage = errorMessage + ": " + chatInitErr.Error()
		}
		http.Error(w, "Error initializing chat", 500)
		return
	}

	session := auth.Session{
		Duration: 6 * time.Hour,
	}
	session.Token = latestNonceToken
	session.Signature, chatInitErr = session.SignatureFor(hearstMailboxKey)

	responsePayload := map[string]string{
		"mailbox_id":    threadInfo.MailboxId,
		"thread_id":     threadInfo.ThreadId,
		"session_token": session.String(),
	}
	w.Header().Add("Content-Type", "application/json")
	encoder := json.NewEncoder(w)
	if err := encoder.Encode(responsePayload); err != nil {
		http.Error(w, "error marshaling json response", 500)
		return
	}
}