Beispiel #1
0
func getDeviceList(w rest.ResponseWriter, r *rest.Request) {
	stats.QueryOnlineDevices()

	devInfoList := []devInfo{}
	r.ParseForm()
	dev_ids := r.FormValue("dev_ids")
	if dev_ids != "" {
		ids := strings.Split(dev_ids, ",")
		for _, id := range ids {
			if serverName, err := storage.Instance.CheckDevice(id); err == nil && serverName != "" {
				info := devInfo{
					Id: id,
				}
				devInfoList = append(devInfoList, info)
			}
		}
	} else {
		rest.Error(w, "Missing \"dev_ids\"", http.StatusBadRequest)
		return
	}

	resp := cloud.ApiResponse{}
	resp.ErrNo = cloud.ERR_NOERROR
	resp.Data = devInfoList
	w.WriteJson(resp)
}
func get_object__decode_request(res rest.ResponseWriter, req *rest.Request) (string, string, map[string]bool, bool) {
	// get CONTENT-TYPE parameter
	contentType := req.PathParam("content-type")
	if len(contentType) == 0 {
		rest.Error(res, "Invalid content type", 400)
		return "", "", nil, true
	}

	// get ID parameter
	doc_id := req.PathParam("id")
	if len(doc_id) == 0 {
		rest.Error(res, "Invalid content ID", 400)
		return "", "", nil, true
	}

	// get PAYLOAD parameters
	flags := map[string]bool{
		"payload": true,
	}
	for flag_name, _ := range flags {
		if req.Form[flag_name] != nil {
			flag_str := req.FormValue(flag_name)
			flag, err := strconv.ParseBool(flag_str)
			if err != nil {
				rest.Error(res, "Invalid query "+flag_name+". "+err.Error(), 400)
				return "", "", nil, true
			}
			flags[flag_name] = flag
		}
	}

	return contentType, doc_id, flags, false
}
Beispiel #3
0
func getDevice(w rest.ResponseWriter, r *rest.Request) {
	devId := r.PathParam("devid")

	r.ParseForm()
	token := r.FormValue("token")
	if token == "" {
		rest.Error(w, "Missing \"token\"", http.StatusBadRequest)
		return
	}

	if !checkAuthz(token, devId) {
		log.Warnf("Auth failed. token: %s, device_id: %s", token, devId)
		rest.Error(w, "Authorization failed", http.StatusForbidden)
		return
	}

	stats.QueryDeviceInfo()

	if serverName, err := storage.Instance.CheckDevice(devId); err == nil && serverName != "" {
		resp := cloud.ApiResponse{}
		resp.ErrNo = cloud.ERR_NOERROR
		resp.Data = devInfo{
			Id: devId,
		}
		w.WriteJson(resp)
	} else {
		rest.NotFound(w, r)
		return
	}
}
// POST /files/delete
func FileDelete(w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	id, _ := strconv.ParseInt(r.FormValue("Id"), 10, 64)
	file := database.FindFile(id)

	// Delete from DB
	database.DeleteFile(file)
	w.WriteJson("")
}
Beispiel #5
0
// APIDialogIndex is used to get dialogs index
func (i *Impl) APIDialogIndex(w rest.ResponseWriter, r *rest.Request) {
	userID := r.PathParam("user_id")
	page, err := strconv.Atoi(r.FormValue("page"))
	offset := 0
	if err == nil {
		offset = (page - 1) * 10
	}

	dialogs := i.GetDialogs(userID, offset)
	w.WriteJson(&dialogs)
}
Beispiel #6
0
// APIMessageIndex is used to show dialog messages
func (i *Impl) APIMessageIndex(w rest.ResponseWriter, r *rest.Request) {
	userID := r.PathParam("user_id")
	dialogID, _ := strconv.Atoi(r.PathParam("dialog_id"))
	page, err := strconv.Atoi(r.FormValue("page"))
	offset := 0
	if err == nil {
		offset = (page - 1) * 10
	}

	messages := i.IndexMessages(userID, dialogID, offset)

	w.WriteJson(&messages)
}
Beispiel #7
0
func authKeyValue(req *rest.Request) (string, bool) {
	key := req.FormValue("api_key")
	if key != "" {
		return key, true
	}

	key = req.Header.Get("Authorization")
	if key == "" {
		return "", false
	} else {
		return key, true
	}
}
Beispiel #8
0
//获取与id对应的邮件内容
func (email *Email) getEmailContent(w rest.ResponseWriter, r *rest.Request) {
	log.Printf("get email content...")
	addr := r.FormValue("pop3Addr")
	//使用pop3Addr参数区分协议类型
	log.Printf("pop3 addr=%s\n", addr)

	if addr != "" {
		email.getEmailContentUsePop3(w, r)
	} else {
		email.getEmailContentUseIMAP(w, r)
	}

}
// POST /releases/delete
func ReleaseDelete(w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	id, _ := strconv.ParseInt(r.FormValue("Id"), 10, 64)
	release := database.FindRelease(id)
	file := database.FindFile(release.FileId)

	// Delete from DB
	database.DeleteRelease(release)
	database.UnpublishFile(file)
	go database.RefreshBuilds()

	// http.Redirect(w, r, "/admin/releases", http.StatusFound)
	w.WriteJson("")
}
Beispiel #10
0
func eventData(req *rest.Request, out interface{}) error {
	encoded := req.FormValue("data")
	if encoded != "" {
		if err := decodeData(encoded, &out); err != nil {
			return err
		} else {
			return nil
		}
	}

	if err := req.DecodeJsonPayload(&out); err != nil {
		return err
	} else {
		return nil
	}
}
Beispiel #11
0
/*
	GET /email 统一入口,通过参数区分具体的请求
 GET /email?pop3Addr=pop.163.com&pop3Port=22&user=myusername&pwd=mypasswords&afterId=***
 GET /email?pop3Addr=pop.163.com&pop3Port=22&user=myusername&pwd=mypasswords&id=***

 tes url
 http://localhost:8080/email?pop3Addr=pop.126.com&pop3Port=110&[email protected]&pwd=***&afterId=1
*/
func (email *Email) GetEmailListAndContent(w rest.ResponseWriter, r *rest.Request) {
	log.Printf("enter into get email list and content...")
	//检验参数是否完整

	getListArgs := r.FormValue("afterId")
	getContentArgs := r.FormValue("id")

	log.Printf("url query params: afterId=%s, id=%s", getListArgs, getContentArgs)

	if getListArgs != "" {
		email.getEmailList(w, r)
	} else if getContentArgs != "" {
		email.getEmailContent(w, r)
	}

	//回复错误信息

}
Beispiel #12
0
func getRouterList(w rest.ResponseWriter, r *rest.Request) {
	type RouterInfo struct {
		Rid   string `json:"rid"`
		Rname string `json:"rname"`
	}

	type ResponseRouterList struct {
		Status int          `json:"status"`
		Descr  string       `json:"descr"`
		List   []RouterInfo `json:"list"`
	}

	resp := ResponseRouterList{}
	resp.Status = STATUS_OTHER_ERR
	r.ParseForm()

	uid := r.FormValue("uid")
	if uid == "" {
		resp.Status = STATUS_INVALID_PARAM
		resp.Descr = "missing 'uid'"
		w.WriteJson(resp)
		return
	}

	devices, err := devcenter.GetDevices(uid, devcenter.DEV_ROUTER)
	if err != nil {
		log.Errorf("GetDevices failed: %s", err.Error())
		resp.Descr = err.Error()
		w.WriteJson(resp)
		return
	}

	for _, dev := range devices {
		router := RouterInfo{
			Rid:   dev.Id,
			Rname: dev.Title,
		}
		resp.List = append(resp.List, router)
	}

	resp.Status = 0
	resp.Descr = "OK"
	w.WriteJson(resp)
}
Beispiel #13
0
func getSysStats(w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	startDate := r.FormValue("start_date")
	endDate := r.FormValue("end_date")

	var (
		start time.Time
		end   time.Time
		err   error
	)
	if startDate == "" {
		start = time.Now()
	} else {
		if start, err = time.Parse("20060102", startDate); err != nil {
			rest.Error(w, "invalid date format", http.StatusBadRequest)
			return
		}
	}
	if endDate == "" {
		end = time.Now()
	} else {
		if end, err = time.Parse("20060102", endDate); err != nil {
			rest.Error(w, "invalid date format", http.StatusBadRequest)
			return
		}
	}
	if start.After(end) {
		rest.Error(w, "start date greater than end date", http.StatusBadRequest)
		return
	}

	resp := Response{
		ErrNo: 0,
	}
	resp.Data, err = storage.Instance.GetSysStats(start, end)
	if err != nil {
		rest.Error(w, "storage I/O failed", http.StatusInternalServerError)
		log.Warnf("GetSysStats failed: %s", err.Error())
		return
	}
	w.WriteJson(resp)
}
Beispiel #14
0
func (email *Email) getEmailListUsePop3(w rest.ResponseWriter, r *rest.Request) ([]EmailHeader, error) {
	addr := r.FormValue("pop3Addr")
	port := r.FormValue("pop3Port")
	user := r.FormValue("user")
	pwd := r.FormValue("pwd")
	afterId := r.FormValue("afterId")

	address := addr + ":" + port
	log.Printf("pop3 addr=%s\n", address)

	client, err := email.getPop3EmailClient(address, user, pwd)
	if err != nil {
		return nil, err
	}

	defer func() {
		client.Quit()
		client.Close()
	}()

	var count int
	var size uint64

	if count, size, err = client.Stat(); err != nil {
		log.Printf("Error: %v\n", err)
		return nil, err
	}

	log.Printf("Count: %d, Size: %d\n", count, size)

	//获取指定afterid及以后的所有邮件列表
	headers := make([]EmailHeader, 0)
	id, _ := strconv.Atoi(afterId)
	for i := id; i <= count; i++ {
		log.Printf("=============")
		log.Printf("i=%d, count=%d\n", i, count)
		if _, size, err = client.List(i); err != nil {
			log.Printf("Error: %v\n", err)
			return nil, err
		}

		log.Printf("email Number: %d, Size: %d\n", i, size)

		header := EmailHeader{}
		header.Id = strconv.Itoa(i)

		headers = append(headers, header)
	}

	return headers, nil
}
Beispiel #15
0
func (email *Email) getEmailContentUsePop3(w rest.ResponseWriter, r *rest.Request) {
	addr := r.FormValue("pop3Addr")
	port := r.FormValue("pop3Port")
	user := r.FormValue("user")
	pwd := r.FormValue("pwd")
	id := r.FormValue("id")

	address := addr + ":" + port
	client, err := email.getPop3EmailClient(address, user, pwd)
	if err != nil {
		errorInfo := ErrorInfo{Code: 403, Name: ""}
		resp := EmailJsonResponse{Success: false, Error: errorInfo}
		w.WriteJson(&resp)
	}

	defer func() {
		client.Quit()
		client.Close()
	}()

	var body string
	content := EmailContent{}
	i, _ := strconv.Atoi(id)
	if body, err = client.Retr(i); err != nil {
		log.Printf("Error: %v\n", err)
		errorInfo := ErrorInfo{Code: 403, Name: ""}
		resp := EmailJsonResponse{Success: false, Error: errorInfo}
		w.WriteJson(&resp)
		return
	}

	_, subject, senderAddr, err := parseContent(body)
	//skip parse error
	if err != nil {
		log.Printf("parse email body error")
		errorInfo := ErrorInfo{Code: 403, Name: ""}
		resp := EmailJsonResponse{Success: false, Error: errorInfo}
		w.WriteJson(&resp)
		return
	}

	content.SenderAddr = senderAddr
	content.SenderName = ""
	content.Subject = subject
	content.Content = body

	resp := EmailJsonResponse{Success: true, Data: content}
	w.WriteJson(&resp)
}
Beispiel #16
0
//防止与email包冲突
func (*Email) SendEmailContent(w rest.ResponseWriter, r *rest.Request) {
	log.Printf("send email...")

	addr := r.FormValue("smtpAddr")
	port := r.FormValue("smtpPort")
	user := r.FormValue("user")
	pwd := r.FormValue("pwd")

	address := addr + ":" + port
	log.Printf("smtp address %s\n", address)

	//从请求报文body中解析json串,获取发文地址及主题、正文、附件等
	if r.Body == nil {
		log.Printf("request body is null")
		return
	}
	reqJson, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("when read request body error: %s", err)
		return
	}
	defer r.Body.Close()
	log.Printf("request body: %s", string(reqJson))

	var emailReq EmailJsonRequest
	err = json.Unmarshal(reqJson, &emailReq)
	if err != nil {
		log.Printf("unmarshal req json error, %s", err)
		return
	}
	log.Printf("%v", emailReq)

	log.Printf("from addrs: %s", user)
	to := emailReq.Data.RecverAddrList
	log.Printf("send to addrs: %v", to)
	auth := smtp.PlainAuth("", user, pwd, addr)
	str := strings.Replace("From: "+user+"~To: "+to[0]+"~Subject: "+"this is subject"+"~~", "~", "\r\n", -1) + "this is body msg"
	//多个收件人时需要循环发送,一次构造一个收件人[]string
	err = smtp.SendMail(address, auth, user, []string{to[0]}, []byte(str))

	//处理附件,从emailReq.Data.Attachements中取出名称和内容

	//使用net/smtp发送邮件

	resp := EmailJsonResponse{}
	if err == nil {
		log.Printf("send mail ok\n")
		resp.Success = true

	} else {
		log.Printf("send mail error: %s", err)
		resp.Success = false
		resp.Error = ErrorInfo{Code: 404, Name: "send mail error"}
	}

	w.WriteJson(&resp)
}
// POST /releases/update
func ReleaseUpdate(w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()

	// Parse form and append to struct
	id, _ := strconv.ParseInt(r.FormValue("Id"), 10, 64)
	fileId, _ := strconv.ParseInt(r.FormValue("FileId"), 10, 64)
	release := database.FindRelease(id)
	file := database.FindFile(fileId)
	release.FileId = file.Id
	release.FileName = file.Name
	release.Channel = r.FormValue("Channel")
	release.Changelog = r.FormValue("Changelog")

	// Append to db
	database.UpdateRelease(release)

	// Redirect
	w.WriteJson("")
}
// POST /releases/create
func ReleaseCreate(w rest.ResponseWriter, r *rest.Request) {
	r.ParseForm()
	fileId, _ := strconv.ParseInt(r.FormValue("FileId"), 10, 64)
	file := database.FindFile(fileId)

	// Generate release
	release := database.Release{
		Created:   time.Now().UnixNano(),
		Changelog: r.FormValue("Changelog"),
		Channel:   r.FormValue("Channel"),
		FileId:    file.Id,
		FileName:  file.Name,
	}

	database.CreateRelease(release)
	database.PublishFile(file)
	go database.RefreshBuilds()
	w.WriteJson("")
}
Beispiel #19
0
func (r *restServerAPI) UpdateGroup(w grest.ResponseWriter, req *grest.Request) {
	g, err := r.ds.GroupByEmail(req.PathParam("email"))
	if err != nil {
		grest.Error(w, err.Error(), http.StatusNotFound)
		return
	}

	user := req.Env["REMOTE_USER_OBJECT"].(*datasource.User)
	action := req.FormValue("action")

	switch action {
	case "join":
		if g.IsMemeber(user.Email) {
			grest.Error(w, "Already joined", http.StatusNotAcceptable)
			return
		}
		g.Members = append(g.Members, user.Email)
	case "leave":
		if g.Manager == user.Email {
			grest.Error(w, "You can't leave a group you which you manage", http.StatusNotAcceptable)
			return
		}
		leaved := false
		for i, m := range g.Members {
			if m == user.Email {
				leaved = true
				n := len(g.Members)
				g.Members[i] = g.Members[n-1]
				g.Members = g.Members[:n-1]
				break
			}
		}
		if !leaved {
			grest.Error(w, "Not joined anyway", http.StatusNotAcceptable)
			return
		}
	case "update":
		if !user.Admin && g.Manager != user.Email {
			grest.Error(w, "You can't modify this group", http.StatusForbidden)
			return
		}
		var gTemp datasource.Group
		err := req.DecodeJsonPayload(&gTemp)
		if err != nil {
			grest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		g.Name = gTemp.Name
		g.Description = gTemp.Description
		g.Active = gTemp.Active
		g.Public = gTemp.Public
		g.Joinable = gTemp.Joinable
		g.Manager = gTemp.Manager
		g.CCs = gTemp.CCs

	default:
		grest.Error(w, fmt.Sprintf("Unknown action: %s", action), http.StatusNotAcceptable)
		return
	}

	e := r.ds.StoreGroup(g)
	if e != nil {
		grest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	} else {
		w.WriteJson(g)
	}
}
Beispiel #20
0
//use imap to delete a mail
func (email *Email) DeleteEmail(w rest.ResponseWriter, r *rest.Request) {
	log.Printf("delete email...")
	addr := r.FormValue("imapAddr")
	//port := r.FormValue("smtpPort")
	user := r.FormValue("user")
	pwd := r.FormValue("pwd")
	id := r.FormValue("id")

	//check params, return error

	//create imap client
	var (
		c   *imap.Client
		cmd *imap.Command
		rsp *imap.Response
	)

	// Connect to the server
	c, _ = imap.Dial(addr)

	// Remember to log out and close the connection when finished
	defer c.Logout(30 * time.Second)

	// Print server greeting (first response in the unilateral server data queue)
	log.Printf("Server says hello:%s", c.Data[0].Info)
	c.Data = nil

	// Enable encryption, if supported by the server
	if c.Caps["STARTTLS"] {
		c.StartTLS(nil)
	}

	// Authenticate
	if c.State() == imap.Login {
		c.Login(user, pwd)
	}

	// List all top-level mailboxes, wait for the command to finish
	cmd, _ = imap.Wait(c.List("", "%"))

	// Print mailbox information
	log.Printf("\nTop-level mailboxes:")
	for _, rsp = range cmd.Data {
		log.Printf("|--%s", rsp.MailboxInfo())
	}

	// Check for new unilateral server data responses
	for _, rsp = range c.Data {
		log.Printf("Server data:%s", rsp)
	}
	c.Data = nil

	// Open a mailbox (synchronous command - no need for imap.Wait)
	c.Select("INBOX", true)
	log.Printf("\nMailbox status:%s\n", c.Mailbox)
	if c.Mailbox == nil {
		resp := EmailJsonResponse{Success: true}
		w.WriteJson(&resp)
		return
	}

	//use Expunge to delete a mail
	set, _ := imap.NewSeqSet("")
	mid, _ := strconv.Atoi(id)
	set.AddNum(uint32(mid))

	//delete mail
	cmd, err := c.Expunge(set)
	if err != nil {
		log.Printf("%v ", cmd)
	} else {
		log.Printf("delete mail ok")
	}

}
Beispiel #21
0
func postRouterCommand(w rest.ResponseWriter, r *rest.Request) {
	log.Debugf("Request from RemoterAddr: %s", r.RemoteAddr)

	resp := CommandResponse{}
	resp.Status = STATUS_OK

	uid := r.FormValue("uid")
	if uid == "" {
		resp.Status = STATUS_INVALID_PARAM
		resp.Error = "missing 'uid'"
		w.WriteJson(resp)
		return
	}

	rid := r.FormValue("rid")
	if rid == "" {
		resp.Status = STATUS_INVALID_PARAM
		resp.Error = "missing 'rid'"
		w.WriteJson(resp)
		return
	}

	if !checkAuthzUid(uid, rid) {
		log.Warnf("auth failed. uid: %s, rid: %s", uid, rid)
		resp.Status = STATUS_OTHER_ERR
		resp.Error = "authorization failed"
		w.WriteJson(resp)
		return
	}

	if r.Body == nil {
		resp.Status = STATUS_INVALID_PARAM
		resp.Error = "missing POST data"
		w.WriteJson(resp)
		return
	}

	body, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		resp.Status = STATUS_INVALID_PARAM
		resp.Error = "invalid POST body"
		w.WriteJson(resp)
		return
	}

	var cmd string
	var serviceName string

	if len(rid) == len("c80e774a1e78") {
		// To old agent
		serviceName = "gibbon_agent"
		type CommandRequest struct {
			//Uid string `json:"uid"`
			Cmd string `json:"cmd"`
		}
		cmdRequest := CommandRequest{
			//Uid: uid,
			Cmd: string(body),
		}
		bCmd, _ := json.Marshal(cmdRequest)
		cmd = string(bCmd)
	} else {
		// To new android service
		serviceName = "com.letv.letvroutersettingservice"
		type RouterCommand struct {
			Forward string `json:"forward"`
		}
		var rc RouterCommand
		if err := json.Unmarshal([]byte(body), &rc); err != nil {
			resp.Status = -2000
			resp.Error = "Request body is not JSON"
			w.WriteJson(resp)
			return
		}
		cmd = rc.Forward
		if cmd == "" {
			resp.Status = -2001
			resp.Error = "'forward' is empty"
			w.WriteJson(resp)
			return
		}
	}

	stats.Cmd(serviceName)
	result, err := rpcClient.Control(rid, serviceName, cmd)
	if err != nil {
		if _, ok := err.(*mq.NoDeviceError); ok {
			stats.CmdOffline(serviceName)
			resp.Status = STATUS_ROUTER_OFFLINE
			resp.Error = fmt.Sprintf("device (%s) offline", rid)
		} else if _, ok := err.(*mq.TimeoutError); ok {
			stats.CmdTimeout(serviceName)
			resp.Status = STATUS_OTHER_ERR
			resp.Error = fmt.Sprintf("recv response timeout [%s]", rid)
		} else if _, ok := err.(*mq.InvalidServiceError); ok {
			stats.CmdInvalidService(serviceName)
			resp.Status = STATUS_OTHER_ERR
			resp.Error = fmt.Sprintf("Device [%s] has no service [%s]", rid, serviceName)
		} else {
			stats.CmdOtherError(serviceName)
			resp.Status = STATUS_OTHER_ERR
			resp.Error = err.Error()
		}
		w.WriteJson(resp)
		return
	} else {
		stats.CmdSuccess(serviceName)
		if len(rid) == len("c80e774a1e78") {
			// reply from gibbon agent
			w.(http.ResponseWriter).Write([]byte(result))
		} else {
			// reply from android service
			type RouterCommandReply struct {
				Status int    `json:"status"`
				Descr  string `json:"descr"`
				Result string `json:"result"`
			}
			var reply RouterCommandReply
			reply.Status = 0
			reply.Descr = "OK"
			reply.Result = result
			w.WriteJson(reply)
		}
	}
}
Beispiel #22
0
func (emaill *Email) getEmailContentUseIMAP(w rest.ResponseWriter, r *rest.Request) {
	addr := r.FormValue("imapAddr")
	port := r.FormValue("imapPort")
	user := r.FormValue("user")
	pwd := r.FormValue("pwd")
	id := r.FormValue("id")

	address := addr + ":" + port
	log.Printf("get email content use imap %s\n", address)

	var (
		c   *imap.Client
		cmd *imap.Command
		rsp *imap.Response
	)

	// Connect to the server
	c, err := imap.Dial(addr)
	if err != nil {
		log.Printf("dial %s error\n", address)
		return
	}

	// Remember to log out and close the connection when finished
	defer c.Logout(30 * time.Second)

	// Print server greeting (first response in the unilateral server data queue)
	log.Printf("Server says hello:%s", c.Data[0].Info)
	c.Data = nil

	// Enable encryption, if supported by the server
	if c.Caps["STARTTLS"] {
		c.StartTLS(nil)
	}

	// Authenticate
	if c.State() == imap.Login {
		c.Login(user, pwd)
	}

	// List all top-level mailboxes, wait for the command to finish
	cmd, _ = imap.Wait(c.List("", "%"))

	// Print mailbox information
	log.Printf("\nTop-level mailboxes:")
	for _, rsp = range cmd.Data {
		log.Printf("|--%s", rsp.MailboxInfo())
	}

	// Check for new unilateral server data responses
	for _, rsp = range c.Data {
		log.Printf("Server data:%s", rsp)
	}
	c.Data = nil

	// Open a mailbox (synchronous command - no need for imap.Wait)
	c.Select("INBOX", true)
	log.Printf("\nMailbox status:%s\n", c.Mailbox)
	if c.Mailbox == nil {
		resp := EmailJsonResponse{Success: true}
		w.WriteJson(&resp)
		return
	}

	// Fetch the headers of the 10 most recent messages
	set, _ := imap.NewSeqSet("")
	set.Add(id)
	// if c.Mailbox.Messages >= 10 {
	// 	set.AddRange(c.Mailbox.Messages-9, c.Mailbox.Messages) //测试只取最新一封邮件
	// } else {
	// 	set.Add("1:*")
	// }
	cmd, _ = c.Fetch(set, "RFC822.HEADER", "RFC822.TEXT") //指定要获取的内容

	// Process responses while the command is running
	log.Printf("\nget mail [%s] messages:", id)
	for cmd.InProgress() {
		// Wait for the next response (no timeout)
		c.Recv(-1)

		// Process command data
		for _, rsp = range cmd.Data {
			header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"])
			if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil {
				subject := msg.Header.Get("Subject")
				log.Printf("|--%s", subject)

				realSubject := GetRealSubject(subject)
				log.Printf("in rest_email.go: get real subject")
				log.Printf(realSubject)

				senderAddr := msg.Header.Get("From")
				recverAddrList := msg.Header.Get("To")

				realSenderAddr := GetRealSubject(senderAddr)
				realRecverAddrList := GetRealSubject(recverAddrList)

				body := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.TEXT"])
				//log.Printf("email body: %s", body)
				//realBody  := GetRealBody(string(body))
				headerAndBody := make([]byte, len(header)+len(body))
				copy(headerAndBody, header)
				copy(headerAndBody[len(header):], body)

				msg, _ := mail.ReadMessage(bytes.NewReader(headerAndBody))
				mime, _ := enmime.ParseMIMEBody(msg)
				realBody := mime.Text //如果原始内容为html,会去掉html元素标签
				log.Printf("real body: %s", realBody)

				//获取MIMEPart所有节点内容
				// log.Printf("root ======================")
				// root := mime.Root
				// if root != nil {
				// 	log.Printf(string(root.Content()))
				// 	log.Printf("child==========")
				// 	if child := root.FirstChild(); child != nil {
				// 		log.Printf(string(child.Content()))
				// 	}

				// }

				attachments := mime.Attachments
				log.Printf("attachments len=%d", len(attachments))
				count := len(attachments)
				var attachmentList []Attachment = nil
				var data EmailContent
				if count > 0 {
					attachmentList = make([]Attachment, count)
					for i := 0; i < len(attachments); i++ {
						name := attachments[i].FileName()
						content := attachments[i].Content() //todo encode by base64
						log.Printf("name===%s", name)
						attachmentList[i] = Attachment{Name: name, Body: string(content)}
					}

				}
				data = EmailContent{Subject: realSubject, SenderAddr: realSenderAddr,
					RecverAddrList: realRecverAddrList, Content: realBody,
					Attachments: attachmentList}

				resp := EmailJsonResponse{Success: true, Data: data}
				w.WriteJson(resp)
			}
		}
		cmd.Data = nil

		// Process unilateral server data
		for _, rsp = range c.Data {
			log.Printf("Server data:%s", rsp)
		}
		c.Data = nil
	}

	// Check command completion status
	if rsp, err := cmd.Result(imap.OK); err != nil {
		if err == imap.ErrAborted {
			log.Printf("Fetch command aborted\n")
		} else {
			log.Printf("Fetch error:%s\n", rsp.Info)
		}
	}

}
Beispiel #23
0
func (r *restServerAPI) UpdateUser(w grest.ResponseWriter, req *grest.Request) {
	currentUser := req.Env["REMOTE_USER_OBJECT"].(*datasource.User)

	email := req.PathParam("email")
	var user *datasource.User
	var err error
	if email == currentUser.Email {
		user = currentUser
	} else {
		if !currentUser.Admin {
			grest.Error(w, "Access denied", http.StatusForbidden)
			return
		}
		user, err = r.ds.UserByEmail(email)
		if err != nil {
			grest.Error(w, err.Error(), http.StatusNotFound)
			return
		}
	}

	action := req.FormValue("action")

	switch action {
	case "changePassword":
		salt := r.ds.ConfigByteArray("PASSWORD_SALT")
		var cp ChangePassword
		err = req.DecodeJsonPayload(&cp)
		if err != nil {
			grest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if user.HasPassword() && !user.AcceptsPassword(cp.OldPassword, salt) {
			grest.Error(w, "Old password is incorrect", http.StatusForbidden)
			return
		}
		user.SetPassword(cp.NewPassword, salt)
		// TODO notify

	case "update":
		var uTemp datasource.User
		err = req.DecodeJsonPayload(&uTemp)
		if err != nil {
			grest.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		user.UIDStr = uTemp.UIDStr
		user.InboxAddr = uTemp.InboxAddr // TODO notify the previous InboxAddr
		user.Active = uTemp.Active
		user.Admin = uTemp.Admin
		user.EnFirstName = uTemp.EnFirstName
		user.EnLastName = uTemp.EnLastName
		user.FaFirstName = uTemp.FaFirstName
		user.FaLastName = uTemp.FaLastName
		user.MobileNum = uTemp.MobileNum
		user.EmergencyNum = uTemp.EmergencyNum
		user.BirthDate = uTemp.BirthDate
		user.EnrolmentDate = uTemp.EnrolmentDate
		user.LeavingDate = uTemp.LeavingDate
	default:
		grest.Error(w, fmt.Sprintf("Unknown action: %s", action), http.StatusNotAcceptable)
		return
	}

	e := r.ds.StoreUser(user)
	if e != nil {
		grest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	} else {
		w.WriteJson(user)
	}
}