示例#1
0
文件: main.go 项目: Supme/gonder
func checkPid(name string) error {
	file, err := os.Open(models.FromRootDir("pid/" + name + ".pid"))
	if err != nil {
		return err
	}
	reader := bufio.NewReader(file)
	pid, _, err := reader.ReadLine()
	if err != nil {
		return err
	}

	p, _ := strconv.Atoi(string(pid))
	process, err := os.FindProcess(p)
	if err != nil {
		os.Remove(models.FromRootDir("pid/" + name + ".pid"))
		return errors.New("Failed to find process")
	} else {
		err := process.Signal(syscall.Signal(0))
		if err != nil {
			os.Remove(models.FromRootDir("pid/" + name + ".pid"))
			return errors.New("Process not response to signal.")
		}
	}

	return nil
}
示例#2
0
文件: main.go 项目: Supme/gonder
func stopProcess(name string) error {
	err := checkPid(name)
	if err != nil {
		fmt.Println("Process " + name + " not found:")
		return err
	} else {
		file, err := os.Open(models.FromRootDir("pid/" + name + ".pid"))
		if err != nil {
			return err
		}
		reader := bufio.NewReader(file)
		pid, _, err := reader.ReadLine()
		if err != nil {
			return err
		}
		p, _ := strconv.Atoi(string(pid))
		process, _ := os.FindProcess(p)
		err = process.Kill()
		if err != nil {
			return err
		}
		os.Remove(models.FromRootDir("pid/" + name + ".pid"))
	}
	fmt.Println("Process " + name + " stoped")
	return nil
}
示例#3
0
func filemanagerDelete(path string) info {

	if err := os.RemoveAll(models.FromRootDir(filemanagerRootPath + path)); err != nil {
		return info{Error: "Error delete", Code: 1}
	}
	return info{Error: "Ok", Code: 0}
}
示例#4
0
文件: main.go 项目: Supme/gonder
func setPid(name string, pid int) error {
	p := strconv.Itoa(pid)
	file, err := os.Create(models.FromRootDir("pid/" + name + ".pid"))
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = io.WriteString(file, p)
	if err != nil {
		return err
	}
	return nil
}
示例#5
0
文件: preview.go 项目: Supme/gonder
func getUnsubscribePreview(w http.ResponseWriter, r *http.Request) {
	if auth.Right("get-recipients") && auth.CampaignRight(r.FormValue("campaignId")) {

		var tmpl string
		var content []byte
		var err error
		models.Db.QueryRow("SELECT `group`.`template` FROM `campaign` INNER JOIN `group` ON `campaign`.`group_id`=`group`.`id` WHERE `group`.`template` IS NOT NULL AND `campaign`.`id`=?", r.FormValue("id")).Scan(&tmpl)
		if tmpl == "" {
			tmpl = "default"
		} else {
			if _, err = os.Stat(models.FromRootDir("statistic/templates/" + tmpl + "/accept.html")); err != nil {
				tmpl = "default"
			}
			if _, err = os.Stat(models.FromRootDir("statistic/templates/" + tmpl + "/success.html")); err != nil {
				tmpl = "default"
			}
		}

		if r.Method == "GET" {
			content, _ = ioutil.ReadFile(models.FromRootDir("statistic/templates/" + tmpl + "/accept.html"))
		} else {
			content, _ = ioutil.ReadFile(models.FromRootDir("statistic/templates/" + tmpl + "/success.html"))
		}

		t := template.New("unsubscribe")
		t, err = t.Parse(string(content))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		err = t.Execute(w, map[string]string{"campaignId": r.FormValue("campaignId")})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}

	} else {
		http.Error(w, "Forbidden get from this campaign", http.StatusForbidden)
	}

}
示例#6
0
func filemanagerAdd(path string, name string, file multipart.File) info {
	out, err := os.Create(models.FromRootDir(filemanagerRootPath + path + name))
	if err != nil {
		return info{Error: "Can not create file", Code: 1}
	}
	defer out.Close()

	_, err = io.Copy(out, file)
	if err != nil {
		return info{Error: "Can not write file", Code: 1}
	}

	return info{Path: path, Name: name, Error: "No error", Code: 0}
}
示例#7
0
func filemanagerResize(path string, width string, height string) []byte {

	resized := models.FromRootDir("cache/preview/" + width + "_" + height + strings.Replace(path, "/", "_", -1))

	if stat, err := os.Stat(resized); err != nil || time.Since(stat.ModTime()) > time.Minute*10 {
		w, _ := strconv.ParseInt(width, 10, 0)
		h, _ := strconv.ParseInt(height, 10, 0)

		f, err := os.Open(models.FromRootDir(filemanagerRootPath + path))
		if err != nil {
			apilog.Println(err)
		}

		img, _, err := image.Decode(f)
		if err != nil {
			apilog.Println(err)
		}

		m := resize.Resize(uint(w), uint(h), img, resize.Lanczos3)

		out, err := os.Create(resized)
		if err != nil {
			apilog.Println(err)
		}
		defer out.Close()

		png.Encode(out, m)
	}

	d, err := ioutil.ReadFile(resized)
	if err != nil {
		apilog.Println(err)
	}

	return d
}
示例#8
0
func filemanagerGetFolder(path string) interface{} {
	r := []info{}
	files, err := ioutil.ReadDir(models.FromRootDir(filemanagerRootPath + path))
	if err != nil {
		return info{
			Error: "Error reading directory",
			Code:  1,
		}
	}

	for _, f := range files {
		t := info{}
		t.Filename = f.Name()
		if f.IsDir() {
			t.Path = path + f.Name() + "/"
			t.FileType = "dir"
			t.Preview = "images/fileicons/_Open.png"
		} else {
			t.Path = path + f.Name()
			ext := filepath.Ext(f.Name())
			if ext != "" {
				ext = ext[1:]
				t.FileType = filepath.Ext(f.Name())[1:]
				if ext == "jpg" || ext == "png" || ext == "gif" {
					t.Preview = "../../filemanager?mode=download&path=" + path + f.Name() + "&width=150&height=0"
				} else {
					ico := "images/fileicons/" + filepath.Ext(f.Name())[1:] + ".png"
					if _, err := os.Stat(ico); err != nil {
						t.Preview = "images/fileicons/default.png"
					} else {
						t.Preview = ico
					}
				}
			}

		}
		r = append(r, t)
	}

	return r

}
示例#9
0
func filemanagerGetInfo(path string) info {

	f, err := os.Lstat(models.FromRootDir(filemanagerRootPath + path))
	if err != nil {
		return info{Error: "Error reading file", Code: 1}
	}

	r := info{
		Path:      path,
		Filename:  f.Name(),
		Protected: 0,
		Properties: properties{
			DateCreated:  "",
			DateModified: string(f.ModTime().String()),
			Height:       "0",
			Width:        "0",
			Size:         strconv.FormatInt(f.Size(), 10),
		},
		Error: "",
		Code:  0,
	}

	ext := filepath.Ext(f.Name())
	if ext != "" {
		ext = ext[1:]
		r.FileType = filepath.Ext(f.Name())[1:]
		if ext == "jpg" || ext == "png" || ext == "gif" {
			r.Preview = "../../filemanager?mode=download&path=" + path + "&width=150&height=0"
		} else {
			ico := "images/fileicons/" + filepath.Ext(f.Name())[1:] + ".png"
			if _, err := os.Stat(ico); err != nil {
				r.Preview = "images/fileicons/default.png"
			} else {
				r.Preview = ico
			}

		}
	}

	return r
}
示例#10
0
文件: utm.go 项目: Supme/gonder
func Run() {
	l, err := os.OpenFile(models.FromRootDir("log/utm.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Println("error opening utm log file: %v", err)
	}
	defer l.Close()

	multi := io.MultiWriter(l, os.Stdout)

	utmlog = log.New(multi, "", log.Ldate|log.Ltime)

	utm := http.NewServeMux()

	utm.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		mem := new(runtime.MemStats)
		runtime.ReadMemStats(mem)
		w.Write([]byte("Welcome to San Tropez! (Conn: " + strconv.Itoa(models.Db.Stats().OpenConnections) + " Allocate: " + strconv.FormatUint(mem.Alloc, 10) + ")"))
	})

	utm.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Write([]byte("# " + models.Config.Version + "\nUser-agent: *\nDisallow: /data/\nDisallow: /files/\nDisallow: /unsubscribe/\nDisallow: /unsubscribe\nDisallow: /redirect/\nDisallow: /web/\nDisallow: /open/\n"))
	})

	utm.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/x-icon")
		ico, _ := base64.StdEncoding.DecodeString("AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAByGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/8q2uP9yGSL/yra4/3IZIv/Ktrj/yra4/3IZIv9yGSL/yra4/8q2uP9yGSL/yra4/3IZIv/Ktrj/chki/3IZIv/Ktrj/chki/+je3/9yGSL/yra4/3IZIv/Ktrj/chki/8q2uP9yGSL/chki/8q2uP9yGSL/yra4/3IZIv9yGSL/yra4/+je3//Ktrj/chki/8q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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")
		w.Write(ico)
	})

	utm.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(models.FromRootDir("files/")))))

	utm.HandleFunc("/unsubscribe/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			message, data, err := models.DecodeData(strings.Split(r.URL.Path, "/")[2])
			if err != nil {
				utmlog.Println(err)
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			if data == "mail" {
				if err := message.Unsubscribe(map[string]string{"Unsubscribed": "from header link"}); err != nil {
					utmlog.Println(err)
					http.Error(w, "", http.StatusInternalServerError)
					return
				} else {
					if t, err := template.ParseFiles(message.UnsubscribeTemplateDir() + "/success.html"); err != nil {
						utmlog.Println(err)
						http.Error(w, "", http.StatusInternalServerError)
						return
					} else {
						t.Execute(w, map[string]string{
							"campaignId":  message.CampaignId,
							"recipientId": message.RecipientId,
						})
					}
				}
			}
			if data == "web" {
				if t, err := template.ParseFiles(message.UnsubscribeTemplateDir() + "/accept.html"); err != nil {
					utmlog.Println(err)
					http.Error(w, "", http.StatusInternalServerError)
					return
				} else {
					t.Execute(w, map[string]string{
						"campaignId":  message.CampaignId,
						"recipientId": message.RecipientId,
					})
				}
			}
		}
	})

	utm.HandleFunc("/unsubscribe", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if r.Method == "POST" {
			var message models.Message
			err := message.New(r.PostFormValue("recipientId"))
			if err != nil {
				utmlog.Println(err)
				http.Error(w, "", http.StatusInternalServerError)
				return
			}
			if message.CampaignId != r.PostFormValue("campaignId") {
				utmlog.Println(err)
				http.Error(w, "Not valid request", http.StatusInternalServerError)
				return
			}
			if t, err := template.ParseFiles(message.UnsubscribeTemplateDir() + "/success.html"); err != nil {
				utmlog.Println(err)
				http.Error(w, "", http.StatusInternalServerError)
				return
			} else {
				var extra = map[string]string{}
				for name, value := range r.PostForm {
					if name != "campaignId" && name != "recipientId" && name != "unsubscribe" {
						extra[name] = strings.Join(value, "|")
					}
				}
				if err := message.Unsubscribe(extra); err != nil {
					utmlog.Println(err)
					http.Error(w, "", http.StatusInternalServerError)
					return
				}
				t.Execute(w, map[string]string{
					"campaignId":  message.CampaignId,
					"recipientId": message.RecipientId,
				})
			}
		}
	})

	utm.HandleFunc("/redirect/", func(w http.ResponseWriter, r *http.Request) {
		message, data, err := models.DecodeData(strings.Split(r.URL.Path, "/")[2])
		if err != nil {
			utmlog.Println(err)
			http.Error(w, "", http.StatusInternalServerError)
			return
		}
		models.Db.Exec("INSERT INTO jumping (campaign_id, recipient_id, url) VALUES (?, ?, ?)", message.CampaignId, message.RecipientId, data)
		models.Db.Exec("UPDATE `recipient` SET `web_agent`= ? WHERE `id`=? AND `web_agent` IS NULL", models.GetIP(r)+" "+r.UserAgent(), message.RecipientId)
		url := regexp.MustCompile(`\s*?(\[.*?\])\s*?`).Split(data, 2)
		http.Redirect(w, r, strings.TrimSpace(url[len(url)-1]), http.StatusFound)
	})

	utm.HandleFunc("/web/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		message, _, err := models.DecodeData(strings.Split(r.URL.Path, "/")[2])
		if err != nil {
			utmlog.Println(err)
			http.Error(w, "", http.StatusInternalServerError)
			return
		}
		models.Db.Exec("INSERT INTO jumping (campaign_id, recipient_id, url) VALUES (?, ?, 'web_version')", message.CampaignId, message.RecipientId)
		models.Db.Exec("UPDATE `recipient` SET `web_agent`= ? WHERE `id`=? AND `web_agent` IS NULL", models.GetIP(r)+" "+r.UserAgent(), message.RecipientId)
		data, err := message.RenderMessage()
		if err != nil {
			utmlog.Println(err)
			http.Error(w, "", http.StatusInternalServerError)
			return
		}
		w.Write([]byte(data))
	})

	utm.HandleFunc("/open/", func(w http.ResponseWriter, r *http.Request) {
		message, _, err := models.DecodeData(strings.Split(r.URL.Path, "/")[2])
		if err != nil {
			utmlog.Println(err)
			http.Error(w, "", http.StatusInternalServerError)
			return
		}
		models.Db.Exec("INSERT INTO jumping (campaign_id, recipient_id, url) VALUES (?, ?, 'open_trace')", message.CampaignId, message.RecipientId)
		models.Db.Exec("UPDATE `recipient` SET `client_agent`= ? WHERE `id`=? AND `client_agent` IS NULL", models.GetIP(r)+" "+r.UserAgent(), message.RecipientId)
		//w.Header().Set("Content-Type", "image/png")
		//png, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAADUExURUxpcU3H2DoAAAABdFJOUwBA5thmAAAADUlEQVQY02NgGAXIAAABEAAB7JfjegAAAABJRU5ErkJggg==iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAADUExURUxpcU3H2DoAAAABdFJOUwBA5thmAAAAEklEQVQ4y2NgGAWjYBSMAuwAAAQgAAFWu83mAAAAAElFTkSuQmCC")
		//w.Write(png)
		w.Header().Set("Content-Type", "image/gif")
		gif, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
		w.Write(gif)
	})

	// Old statistic todo delete later
	utm.HandleFunc("/data/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			var param *oldJson

			data, err := base64.URLEncoding.DecodeString(strings.Split(strings.Split(r.URL.Path, "/")[2], ".")[0])
			if err != nil {
				utmlog.Println(err)
				http.Error(w, "", http.StatusInternalServerError)
				return
			}

			err = json.Unmarshal([]byte(data), &param)
			if err != nil {
				utmlog.Println(err)
				http.Error(w, "", http.StatusInternalServerError)
				return
			}

			userAgent := models.GetIP(r) + " " + r.UserAgent()

			if param.Opened != "" {
				models.Db.Exec("INSERT INTO jumping (campaign_id, recipient_id, url) VALUES (?, ?, ?)", param.Campaign, param.Recipient, "open_trace")
				models.Db.Exec("UPDATE `recipient` SET `client_agent`= ? WHERE `id`=? AND `client_agent` IS NULL", userAgent, param.Recipient)
				w.Header().Set("Content-Type", "image/gif")
				gif, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
				w.Write(gif)
			} else if param.Url != "" {
				models.Db.Exec("INSERT INTO jumping (campaign_id, recipient_id, url) VALUES (?, ?, ?)", param.Campaign, param.Recipient, param.Url)
				models.Db.Exec("UPDATE `recipient` SET `web_agent`= ? WHERE `id`=? AND `web_agent` IS NULL", userAgent, param.Recipient)
				http.Redirect(w, r, param.Url, http.StatusFound)
			} else if param.Webver != "" {
				w.Header().Set("Content-Type", "text/html; charset=utf-8")
				models.Db.Exec("INSERT INTO jumping (campaign_id, recipient_id, url) VALUES (?, ?, ?)", param.Campaign, param.Recipient, "web_version")
				models.Db.Exec("UPDATE `recipient` SET `web_agent`= ? WHERE `id`=? AND `web_agent` IS NULL", userAgent, param.Recipient)
				var m models.Message
				m.New(param.Recipient)
				message, err := m.RenderMessage()
				if err != nil {
					utmlog.Println(err)
					http.Error(w, "", http.StatusInternalServerError)
					return
				}
				w.Write([]byte(message))
			} else if param.Unsubscribe != "" {
				w.Header().Set("Content-Type", "text/html; charset=utf-8")
				var name string
				models.Db.QueryRow("SELECT `group`.`template` FROM `campaign` INNER JOIN `group` ON `campaign`.`group_id`=`group`.`id` WHERE `group`.`template` IS NOT NULL AND `campaign`.`id`=?", param.Campaign).Scan(&name)
				if name == "" {
					name = "default"
				} else {
					if _, err := os.Stat(models.FromRootDir("templates/" + name + "/accept.html")); err != nil {
						name = "default"
					}
					if _, err := os.Stat(models.FromRootDir("templates/" + name + "/success.html")); err != nil {
						name = "default"
					}
				}
				if t, err := template.ParseFiles(models.FromRootDir("templates/" + name + "/accept.html")); err != nil {
					utmlog.Println(err)
					http.Error(w, "", http.StatusInternalServerError)
					return
				} else {
					t.Execute(w, map[string]string{
						"campaignId":  param.Campaign,
						"recipientId": param.Recipient,
					})
				}
			}
		}
	})
	// /Old statistic todo delete later

	utmlog.Println("UTM listening on port " + models.Config.StatPort + "...")
	utmlog.Fatal(http.ListenAndServe(":"+models.Config.StatPort, muxLog(utm)))
}
示例#11
0
文件: api.go 项目: Supme/gonder
func Run() {
	l, err := os.OpenFile(models.FromRootDir("log/api.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Println("error opening api log file: %v", err)
	}
	defer l.Close()

	multi := io.MultiWriter(l, os.Stdout)

	apilog = log.New(multi, "", log.Ldate|log.Ltime)

	api := http.NewServeMux()

	api.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		mem := new(runtime.MemStats)
		runtime.ReadMemStats(mem)
		w.Write([]byte("Welcome to San Tropez! (Conn: " + strconv.Itoa(models.Db.Stats().OpenConnections) + " Allocate: " + strconv.FormatUint(mem.Alloc, 10) + ")"))
	})

	// Groups
	// Example:
	// Get groups: http://host/api/groups?cmd=get-records&limit=100&offset=0
	// Rename groups: http://host/api/groups?cmd=save-records&selected[]=20&limit=100&offset=0&changes[0][recid]=1&changes[0][name]=Test+1&changes[1][recid]=2&changes[1][name]=Test+2
	// ...
	api.HandleFunc("/api/groups", auth.Check(groups))

	// Campaigns from group
	// Example:
	// Get campaigns: http://host/api/campaigns?group=2&cmd=get-records&limit=100&offset=0
	// Rename campaign: http://host/api/campaigns?cmd=save-records&selected[]=6&limit=100&offset=0&changes[0][recid]=6&changes[0][name]=Test+campaign
	// ...
	api.HandleFunc("/api/campaigns", auth.Check(campaigns))

	// Campaign data
	// Example:
	// Get data: http://host/api/campaign?cmd=get-data&recid=4
	// ...
	api.HandleFunc("/api/campaign", auth.Check(campaign))

	api.HandleFunc("/api/profilelist", auth.Check(profilesList))

	// Profiles
	// Example:
	// Get list http://host/api/profiles?cmd=get-list
	// ...
	api.HandleFunc("/api/profiles", auth.Check(profiles))

	// Get recipients from campaign
	// Example:
	// Get list recipients: http://host/api/recipients?content=recipients&campaign=4&cmd=get-records&limit=100&offset=0
	// Get recipient parameters: http://host/api/recipients?content=parameters&recipient=149358&cmd=get-records&limit=100&offset=0
	// ...
	api.HandleFunc("/api/recipients", auth.Check(recipients))

	api.HandleFunc("/api/sender", auth.Check(sender))
	api.HandleFunc("/api/senderlist", auth.Check(senderList))

	// Reports
	// Example:
	//   Get reports: http://host/api/report?campaign=4
	// /api/report?campaign=xxx
	// /api/report/jump?campaign=xxx
	// /api/report/unsubscribed?group=xxx
	// /api/report/unsubscribed?campaign=xxx
	api.HandleFunc("/api/report", auth.Check(report))
	api.HandleFunc("/api/report/jump", auth.Check(reportJumpDetailedCount))
	api.HandleFunc("/api/report/unsubscribed", auth.Check(reportUnsubscribed))

	api.HandleFunc("/preview", auth.Check(getMailPreview))
	api.HandleFunc("/unsubscribe", auth.Check(getUnsubscribePreview))

	api.HandleFunc("/filemanager", auth.Check(filemanager))

	// Static dirs
	api.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(models.FromRootDir("api/http/assets/")))))
	api.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(models.FromRootDir("files/")))))

	api.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/x-icon")
		ico, _ := base64.StdEncoding.DecodeString("AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAByGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/3IZIv9yGSL/chki/8q2uP9yGSL/yra4/3IZIv/Ktrj/yra4/3IZIv9yGSL/yra4/8q2uP9yGSL/yra4/3IZIv/Ktrj/chki/3IZIv/Ktrj/chki/+je3/9yGSL/yra4/3IZIv/Ktrj/chki/8q2uP9yGSL/chki/8q2uP9yGSL/yra4/3IZIv9yGSL/yra4/+je3//Ktrj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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")
		w.Write(ico)
	})

	api.HandleFunc("/{{.StatPng}}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/gif")
		blank, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
		w.Write(blank)
	})

	api.HandleFunc("/panel", auth.Check(func(w http.ResponseWriter, r *http.Request) {
		if f, err := ioutil.ReadFile(models.FromRootDir("api/http/index.html")); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		} else {
			w.Write(f)
		}
	}))

	api.HandleFunc("/logout", auth.Logout)

	api.HandleFunc("/status/ws/campaign.log", auth.Check(campaignLog))
	api.HandleFunc("/status/ws/api.log", auth.Check(apiLog))
	api.HandleFunc("/status/ws/utm.log", auth.Check(utmLog))
	api.HandleFunc("/status/ws/main.log", auth.Check(mainLog))

	apilog.Println("API listening on port " + models.Config.ApiPort + "...")
	apilog.Fatal(http.ListenAndServeTLS(":"+models.Config.ApiPort, "./cert/server.pem", "./cert/server.key", api))
}
示例#12
0
func recipients(w http.ResponseWriter, r *http.Request) {
	var err error
	var js []byte

	if err = r.ParseForm(); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if r.Form["content"][0] == "recipients" {
		switch r.Form["cmd"][0] {
		case "get-records":
			if auth.Right("get-recipients") && auth.CampaignRight(r.Form["campaign"][0]) {
				rs, err := getRecipients(r.Form["campaign"][0], r.Form["offset"][0], r.Form["limit"][0])
				js, err = json.Marshal(rs)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
			} else {
				js = []byte(`{"status": "error", "message": "Forbidden get recipients"}`)
			}

		case "upload":
			if auth.Right("upload-recipients") && auth.CampaignRight(r.Form["campaign"][0]) {
				content, err := base64.StdEncoding.DecodeString(r.FormValue("base64"))
				if err != nil {
					js = []byte(`{"status": "error", "message": "Base64 decode"}`)
				}
				file := models.FromRootDir("tmp/" + time.Now().String())
				err = ioutil.WriteFile(file, content, 0644)
				if err != nil {
					js = []byte(`{"status": "error", "message": "Write file"}`)
				}

				if path.Ext(r.Form["name"][0]) == ".csv" {
					err = recipientCsv(r.FormValue("campaign"), file)
					if err != nil {
						js = []byte(`{"status": "error", "message": "Add recipients csv"}`)
					}
				} else if path.Ext(r.Form["name"][0]) == ".xlsx" {
					err = recipientXlsx(r.FormValue("campaign"), file)
					if err != nil {
						js = []byte(`{"status": "error", "message": "Add recipients xlsx"}`)
					}
				} else {
					fmt.Println("this other file")
					js = []byte(`{"status": "error", "message": "This not csv or xlsx file"}`)
				}

			} else {
				js = []byte(`{"status": "error", "message": "Forbidden upload recipients"}`)
			}

		case "deleteAll":
			if auth.Right("delete-recipients") && auth.CampaignRight(r.Form["campaign"][0]) {
				err = delRecipients(r.Form["campaign"][0])
				if err != nil {
					js = []byte(`{"status": "error", "message": "Can't delete all recipients"}`)
				}
			} else {
				js = []byte(`{"status": "error", "message": "Forbidden delete recipients"}`)
			}

		case "resend4x1":
			if auth.Right("accept-campaign") && auth.CampaignRight(r.Form["campaign"][0]) {
				err = resendCampaign(r.Form["campaign"][0])
				if err != nil {
					js = []byte(`{"status": "error", "message": "Can't resend"}`)
				}
			} else {
				js = []byte(`{"status": "error", "message": "Forbidden resend campaign"}`)
			}
		}
	}

	if r.Form["content"][0] == "parameters" {
		switch r.Form["cmd"][0] {
		case "get-records":
			rId, err := getRecipientCampaign(r.Form["recipient"][0])
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			if auth.Right("get-recipient-parameters") && auth.CampaignRight(rId) {
				ps, err := getRecipientParams(r.Form["recipient"][0], r.Form["offset"][0], r.Form["limit"][0])
				js, err = json.Marshal(ps)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
			} else {
				js = []byte(`{"status": "error", "message": "Forbidden get recipient parameters"}`)
			}
		}
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
}
示例#13
0
func filemanagerRename(old, new string) info {
	if err := os.Rename(models.FromRootDir(filemanagerRootPath+old), models.FromRootDir(filemanagerRootPath+filepath.Dir(old)+"/"+new)); err != nil {
		return info{Error: "Error rename", Code: 1}
	}
	return info{Error: "Ok", Code: 0}
}
示例#14
0
func filemanagerMkDir(path, name string) info {
	if err := os.MkdirAll(models.FromRootDir(filemanagerRootPath+path+name), 0755); err != nil {
		return info{Error: "Error make directory", Code: 1}
	}
	return info{Error: "Ok", Code: 0}
}
示例#15
0
文件: main.go 项目: Supme/gonder
func main() {

	l, err := os.OpenFile(models.FromRootDir("log/main.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Println("error opening log file: %v", err)
	}
	defer l.Close()

	ml := io.MultiWriter(l, os.Stdout)

	log.SetFlags(3)
	log.SetOutput(ml)

	runtime.GOMAXPROCS(runtime.NumCPU())

	//	models.Config.Get()
	defer models.Config.Close()

	// Start
	if len(os.Args) == 2 {
		var err error
		if os.Args[1] == "status" {
			err = checkPid("api")
			if err == nil {
				fmt.Println("Process api running")
			} else {
				fmt.Println("Process api stoping")
			}
			err = checkPid("sender")
			if err == nil {
				fmt.Println("Process sender running")
			} else {
				fmt.Println("Process sender stoping")
			}
			err = checkPid("utm")
			if err == nil {
				fmt.Println("Process utm running")
			} else {
				fmt.Println("Process utm stoping")
			}
		}
		if os.Args[1] == "start" {
			err = startProcess("api")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = startProcess("sender")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = startProcess("utm")
			if err != nil {
				fmt.Println(err.Error())
			}
			os.Exit(0)
		}
		if os.Args[1] == "stop" {
			err = stopProcess("api")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = stopProcess("sender")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = stopProcess("utm")
			if err != nil {
				fmt.Println(err.Error())
			}
			os.Exit(0)
		}
		if os.Args[1] == "restart" {
			err = stopProcess("api")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = startProcess("api")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = stopProcess("utm")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = startProcess("utm")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = stopProcess("sender")
			if err != nil {
				fmt.Println(err.Error())
			}
			err = startProcess("sender")
			if err != nil {
				fmt.Println(err.Error())
			}
			os.Exit(0)
		}
	}

	if len(os.Args) == 3 {
		if os.Args[1] == "start" {
			if os.Args[2] == "api" {
				err = startProcess("api")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			if os.Args[2] == "sender" {
				err = startProcess("sender")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			if os.Args[2] == "utm" {
				err = startProcess("utm")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			os.Exit(0)
		}

		if os.Args[1] == "stop" {
			if os.Args[2] == "api" {
				err = stopProcess("api")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			if os.Args[2] == "sender" {
				err = stopProcess("sender")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			if os.Args[2] == "utm" {
				err = stopProcess("utm")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			os.Exit(0)
		}

		if os.Args[1] == "restart" {
			if os.Args[2] == "api" {
				err = stopProcess("api")
				if err != nil {
					fmt.Println(err.Error())
				}
				err = startProcess("api")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			if os.Args[2] == "sender" {
				err = stopProcess("sender")
				if err != nil {
					fmt.Println(err.Error())
				}
				err = startProcess("sender")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			if os.Args[2] == "utm" {
				err = stopProcess("utm")
				if err != nil {
					fmt.Println(err.Error())
				}
				err = startProcess("utm")
				if err != nil {
					fmt.Println(err.Error())
				}
			}
			os.Exit(0)
		}

		if os.Args[1] == "daemonize" {

			if os.Args[2] == "api" {

				fmt.Println("Start api http server")
				api.Run()

				for {
				}
			}

			if os.Args[2] == "sender" {

				fmt.Println("Start database mailer")
				campaign.Run()

				for {
				}
			}

			if os.Args[2] == "utm" {

				fmt.Println("Start utm http server")
				utm.Run()

				for {
				}
			}

		}

	}

	if len(os.Args) == 1 {
		fmt.Println("Start api http server")
		go api.Run()

		fmt.Println("Start database mailer")
		go campaign.Run()

		fmt.Println("Start utm http server")
		go utm.Run()

		fmt.Println("Press Enter for stop")
		var input string
		fmt.Scanln(&input)
	}

}