示例#1
0
func (c *Controller) AutoPayments() (string, error) {

	txType := "AutoPayments"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	var autoPayments []*autoPayment

	rows, err := c.Query(c.FormatQuery("SELECT id, amount, commission, currency_id, last_payment_time, period, sender, recipient FROM auto_payments WHERE sender = ? AND del_block_id = 0"), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var amount, commission float64
		var id, currency_id, last_payment_time, period, sender, recipient int64
		err = rows.Scan(&id, &amount, &commission, &currency_id, &last_payment_time, &period, &sender, &recipient)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		auto_ := &autoPayment{Id: id, Amount: amount, Commission: commission, Currency_id: currency_id, Last_payment_time: last_payment_time, Period: period, Sender: sender, Recipient: recipient}
		autoPayments = append(autoPayments, auto_)
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"AutoPayments", "DelAutoPayment", "NewAutoPayment"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("auto_payments", "AutoPayments", &AutoPaymentsPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		CurrencyList:    c.CurrencyListCf,
		AutoPayments:    autoPayments,
		LastTxFormatted: lastTxFormatted})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#2
0
func (c *Controller) ArbitrationBuyer() (string, error) {

	log.Debug("ArbitrationBuyer")

	txType := "money_back_request"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	myOrders, err := c.GetAll(`
			SELECT *
			FROM orders
			WHERE buyer = ?
			ORDER BY time DESC
			LIMIT 20
			`, 20, c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeSellerHoldBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("arbitration_buyer", "arbitrationBuyer", &arbitrationBuyerPage{
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		CurrencyList:    c.CurrencyList,
		MyOrders:        myOrders})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#3
0
func (c *Controller) PromisedAmountList() (string, error) {

	txType := "PromisedAmount"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewPromisedAmount", "ChangePromisedAmount", "DelPromisedAmount", "ForRepaidFix", "ActualizationPromisedAmounts", "Mining"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	limitsText := strings.Replace(c.Lang["change_commission_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_promised_amount"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_promised_amount_period"]], -1)

	actualizationPromisedAmounts, promisedAmountListAccepted, _, err := c.GetPromisedAmounts(c.SessUserId, c.Variables.Int64["cash_request_time"])
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	TemplateStr, err := makeTemplate("promised_amount_list", "promisedAmountList", &promisedAmountListPage{
		Alert:                        c.Alert,
		Lang:                         c.Lang,
		CountSignArr:                 c.CountSignArr,
		ShowSignData:                 c.ShowSignData,
		UserId:                       c.SessUserId,
		TimeNow:                      timeNow,
		TxType:                       txType,
		TxTypeId:                     txTypeId,
		SignData:                     "",
		LastTxFormatted:              lastTxFormatted,
		CurrencyList:                 c.CurrencyList,
		PromisedAmountListAccepted:   promisedAmountListAccepted,
		ActualizationPromisedAmounts: actualizationPromisedAmounts,
		LimitsText:                   limitsText})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#4
0
func (c *Controller) ChangeAvatar() (string, error) {

	txType := "UserAvatar"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"UserAvatar"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	data, err := c.OneRow("SELECT name, avatar FROM users WHERE user_id =  ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	avatar := data["avatar"]
	name := data["name"]

	TemplateStr, err := makeTemplate("change_avatar", "changeAvatar", &ChangeAvatarPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		Avatar:          avatar,
		Name:            name})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#5
0
func (c *Controller) HolidaysList() (string, error) {

	var err error

	var myHolidaysPending []map[string]string
	if c.SessRestricted == 0 {
		// те, что еще не попали в Dc-сеть
		myHolidaysPending, err = c.GetAll(`SELECT * FROM `+c.MyPrefix+`my_holidays ORDER BY id DESC`, -1)
	}

	myHolidaysAccepted, err := c.GetAll(`SELECT * FROM holidays WHERE user_id = ?`, -1, c.SessUserId)

	limitsText := strings.Replace(c.Lang["limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_holidays"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_holidays_period"]], -1)

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewHolidays"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("holidays_list", "holidaysList", &holidaysListPage{
		Alert:              c.Alert,
		Lang:               c.Lang,
		CountSignArr:       c.CountSignArr,
		ShowSignData:       c.ShowSignData,
		SignData:           "",
		LastTxFormatted:    lastTxFormatted,
		LimitsText:         limitsText,
		MyHolidaysPending:  myHolidaysPending,
		MyHolidaysAccepted: myHolidaysAccepted})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
func (c *Controller) ChangeArbitratorConditions() (string, error) {

	txType := "ChangeArbitratorConditions"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	myCommission := make(map[int64][]float64)
	if c.SessRestricted == 0 {
		rows, err := c.Query(c.FormatQuery("SELECT currency_id, pct, min, max FROM " + c.MyPrefix + "my_commission"))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var pct, min, max float64
			var currency_id int64
			err = rows.Scan(&currency_id, &pct, &min, &max)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			myCommission[currency_id] = []float64{pct, min, max}
		}
	}

	currencyList := c.CurrencyList
	commission := make(map[int64][]float64)
	for currency_id, _ := range currencyList {
		if len(myCommission[currency_id]) > 0 {
			commission[currency_id] = myCommission[currency_id]
		} else {
			commission[currency_id] = []float64{0.1, 0.01, 0}
		}
	}

	// для CF-проектов
	currencyList[1000] = "Crowdfunding"
	if len(myCommission[1000]) > 0 {
		commission[1000] = myCommission[1000]
	} else {
		commission[1000] = []float64{0.1, 0.01, 0}
	}
	arbitratorConditionsJson, err := c.Single("SELECT conditions FROM arbitrator_conditions WHERE user_id  =  ?", c.SessUserId).Bytes()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	arbitratorConditionsMap_ := make(map[string][5]string)
	if len(arbitratorConditionsJson) > 0 {
		err = json.Unmarshal(arbitratorConditionsJson, &arbitratorConditionsMap_)
		// арбитр к этому моменту мог передумать и убрать свои условия, уйдя из арбитров для новых сделок поставив [0] что вызовет тут ошибку
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}
	arbitratorConditionsMap := make(map[int64][5]string)
	for k, v := range arbitratorConditionsMap_ {
		arbitratorConditionsMap[utils.StrToInt64(k)] = v
	}
	if len(arbitratorConditionsMap) == 0 {
		arbitratorConditionsMap[72] = [5]string{"0.01", "0", "0.01", "0", "0.1"}
		arbitratorConditionsMap[23] = [5]string{"0.01", "0", "0.01", "0", "0.1"}
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorConditions"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	var pendingTx_ map[int64]int64
	if len(last_tx) > 0 {
		lastTxFormatted, pendingTx_ = utils.MakeLastTx(last_tx, c.Lang)
	}
	pendingTx := pendingTx_[txTypeId]

	TemplateStr, err := makeTemplate("change_arbitrator_conditions", "changeArbitratorConditions", &changeArbitratorConditionsPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		CurrencyList:    c.CurrencyList,
		PendingTx:       pendingTx,
		LastTxFormatted: lastTxFormatted,
		Conditions:      arbitratorConditionsMap,
		Commission:      commission})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#7
0
func (c *Controller) ChangePrimaryKey() (string, error) {

	var err error

	txType := "ChangePrimaryKey"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	var myKeys []map[string]string
	if c.SessRestricted == 0 {
		myKeys, err = c.GetAll(`SELECT * FROM `+c.MyPrefix+`my_keys ORDER BY id DESC`, -1)
	}

	statusArray := map[string]string{"my_pending": c.Lang["local_pending"], "approved": c.Lang["status_approved"]}

	// узнаем, когда последний раз была смена ключа, чтобы не показывать юзеру страницу смены
	lastChangeKeyTime, err := c.Single("SELECT time FROM log_time_primary_key WHERE user_id  =  ? ORDER BY time DESC", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	limitsText := strings.Replace(c.Lang["change_primary_key_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_primary_key"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_primary_key_period"]], -1)

	var lastTxQueueTx, lastTxTx bool
	lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangePrimaryKey"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(lastTx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(lastTx, c.Lang)
		if len(lastTx[0]["queue_tx"]) > 0 {
			lastTxQueueTx = true
		}
		if len(lastTx[0]["tx"]) > 0 {
			lastTxTx = true
		}
	}

	TemplateStr, err := makeTemplate("change_primary_key", "changePrimaryKey", &changePrimaryKeyPage{
		Alert:             c.Alert,
		Lang:              c.Lang,
		ShowSignData:      c.ShowSignData,
		SignData:          "",
		UserId:            c.SessUserId,
		CountSignArr:      c.CountSignArr,
		LimitsText:        limitsText,
		LastTxQueueTx:     lastTxQueueTx,
		LastTxTx:          lastTxTx,
		LastTxFormatted:   lastTxFormatted,
		LastChangeKeyTime: lastChangeKeyTime,
		LastTx:            lastTx,
		MyKeys:            myKeys,
		StatusArray:       statusArray,
		TimeNow:           timeNow,
		TxType:            txType,
		IOS:               utils.IOS(),
		Android:           utils.Android(),
		Mobile:            utils.Mobile(),
		TxTypeId:          txTypeId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#8
0
func (c *Controller) CashRequestIn() (string, error) {

	txType := "CashRequestIn"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	cashRequestsStatus := map[string]string{"my_pending": c.Lang["local_pending"], "pending": c.Lang["pending"], "approved": c.Lang["approved"], "rejected": c.Lang["rejected"]}

	// Узнаем свой user_id
	userId, err := c.GetMyUserId(c.MyPrefix)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// актуальный запрос к нам на получение налички. Может быть только 1.
	actualData, err := c.OneRow(`
		SELECT `+c.MyPrefix+`my_cash_requests.cash_request_id,
					 `+c.MyPrefix+`my_cash_requests.id,
					 `+c.MyPrefix+`my_cash_requests.comment_status,
					 `+c.MyPrefix+`my_cash_requests.comment,
					 cash_requests.amount,
					 cash_requests.currency_id,
					 cash_requests.from_user_id,
					 hex(cash_requests.hash_code) as hash_code
		FROM `+c.MyPrefix+`my_cash_requests
		LEFT JOIN cash_requests ON cash_requests.id = `+c.MyPrefix+`my_cash_requests.cash_request_id
		WHERE cash_requests.to_user_id = ? AND
					 cash_requests.status = 'pending' AND
					 cash_requests.time > ? AND
					 cash_requests.del_block_id = 0 AND
					 cash_requests.for_repaid_del_block_id = 0
		ORDER BY cash_request_id DESC
		LIMIT 1`, userId, utils.Time()-c.Variables.Int64["cash_request_time"]).String()
	fmt.Println(`
		SELECT ` + c.MyPrefix + `my_cash_requests.cash_request_id,
					 ` + c.MyPrefix + `my_cash_requests.id,
					 ` + c.MyPrefix + `my_cash_requests.comment_status,
					 ` + c.MyPrefix + `my_cash_requests.comment,
					 cash_requests.amount,
					 cash_requests.currency_id,
					 cash_requests.from_user_id,
					 hex(cash_requests.hash_code) as hash_code
		FROM ` + c.MyPrefix + `my_cash_requests
		LEFT JOIN cash_requests ON cash_requests.id = ` + c.MyPrefix + `my_cash_requests.cash_request_id
		WHERE cash_requests.to_user_id = ` + utils.Int64ToStr(userId) + ` AND
					 cash_requests.status = 'pending' AND
					 cash_requests.time > ` + utils.Int64ToStr(utils.Time()-c.Variables.Int64["cash_request_time"]) + ` AND
					 cash_requests.del_block_id = 0 AND
					 cash_requests.for_repaid_del_block_id = 0
		ORDER BY cash_request_id DESC
		LIMIT 1`)
	if len(actualData) > 0 {
		actualData["hash_code"] = strings.ToLower(actualData["hash_code"])
	}
	// список ранее отправленных ответов на запросы.
	myCashRequests, err := c.GetAll("SELECT * FROM "+c.MyPrefix+"my_cash_requests WHERE to_user_id = ?", -1, userId)

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"CashRequestIn"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("cash_request_in", "cashRequestIn", &CashRequestInPage{
		Alert:              c.Alert,
		Lang:               c.Lang,
		CountSignArr:       c.CountSignArr,
		ShowSignData:       c.ShowSignData,
		UserId:             userId,
		TimeNow:            timeNow,
		TxType:             txType,
		TxTypeId:           txTypeId,
		SignData:           "",
		CurrencyList:       c.CurrencyList,
		CashRequestsStatus: cashRequestsStatus,
		MyCashRequests:     myCashRequests,
		LastTxFormatted:    lastTxFormatted,
		ActualData:         actualData})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#9
0
func (c *Controller) ArbitrationSeller() (string, error) {

	log.Debug("ArbitrationSeller")

	txType := "ChangeSellerHoldBack"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	holdBack, err := c.OneRow("SELECT arbitration_days_refund, seller_hold_back_pct FROM users WHERE user_id  =  ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	myOrders, err := c.GetAll("SELECT id, time, amount, seller, status, comment_status, comment	FROM orders	WHERE seller = ? ORDER BY time DESC LIMIT 20", 20, c.SessUserId)
	for k, data := range myOrders {
		if data["status"] == "refund" {
			if c.SessRestricted == 0 {
				data_, err := c.OneRow("SELECT comment, comment_status FROM "+c.MyPrefix+"my_comments WHERE id  =  ? AND type  =  'seller'", data["id"]).String()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
				data["status"] = data_["comment"]
				data["comment_status"] = data_["comment_status"]
			}
		}
		myOrders[k] = data
	}

	var shopData map[string]string
	if c.SessRestricted == 0 {
		shopData, err = c.OneRow("SELECT shop_secret_key, shop_callback_url FROM " + c.MyPrefix + "my_table").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeSellerHoldBack", "MoneyBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	var pendingTx_ map[int64]int64
	if len(last_tx) > 0 {
		lastTxFormatted, pendingTx_ = utils.MakeLastTx(last_tx, c.Lang)
	}
	pendingTx := pendingTx_[txTypeId]

	TemplateStr, err := makeTemplate("arbitration_seller", "arbitrationSeller", &arbitrationSellerPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		CurrencyList:    c.CurrencyList,
		MinerId:         c.MinerId,
		PendingTx:       pendingTx,
		MyOrders:        myOrders,
		SessRestricted:  c.SessRestricted,
		ShopData:        shopData,
		HoldBack:        holdBack})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#10
0
文件: new_user.go 项目: dzyk/dcoin-go
func (c *Controller) NewUser() (string, error) {

	txType := "NewUser"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	param := utils.ParamType{X: 176, Y: 100, Width: 100, Bg_path: "static/img/k_bg.png"}

	refPhotos := make(map[int64][]string)
	myRefsKeys := make(map[int64]map[string]string)
	if c.SessRestricted == 0 {
		join := c.MyPrefix + `my_new_users.user_id`
		if c.ConfigIni["db_type"] == "sqlite" || c.ConfigIni["db_type"] == "postgresql" {
			join = `"` + c.MyPrefix + `my_new_users".user_id`
		}
		rows, err := c.Query(c.FormatQuery(`
				SELECT users.user_id,	private_key,  log_id
				FROM ` + c.MyPrefix + `my_new_users
				LEFT JOIN users ON users.user_id = ` + join + `
				WHERE status = 'approved'
				`))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var user_id, log_id int64
			var private_key string
			err = rows.Scan(&user_id, &private_key, &log_id)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			// проверим, не сменил ли уже юзер свой ключ
			StrUserId := utils.Int64ToStr(user_id)
			if log_id != 0 {
				myRefsKeys[user_id] = map[string]string{"user_id": StrUserId}
			} else {
				myRefsKeys[user_id] = map[string]string{"user_id": StrUserId, "private_key": private_key}
				md5 := string(utils.Md5(private_key))
				kPath := *utils.Dir + "/public/" + md5[0:16]
				kPathPng := kPath + ".png"
				kPathTxt := kPath + ".txt"
				if _, err := os.Stat(kPathPng); os.IsNotExist(err) {
					privKey := strings.Replace(private_key, "-----BEGIN RSA PRIVATE KEY-----", "", -1)
					privKey = strings.Replace(privKey, "-----END RSA PRIVATE KEY-----", "", -1)
					_, err = utils.KeyToImg(privKey, kPathPng, user_id, c.TimeFormat, param)
					if err != nil {
						return "", utils.ErrInfo(err)
					}
					err := ioutil.WriteFile(kPathTxt, []byte(privKey), 0644)
					if err != nil {
						return "", utils.ErrInfo(err)
					}
					/*$gd = key_to_img($private_key, $param, $row['user_id']);
					imagepng($gd, $k_path_png);
					file_put_contents($k_path_txt, trim($private_key));*/
				}
			}
		}
	}

	refs := make(map[int64]map[int64]float64)
	// инфа по рефам юзера
	rows, err := c.Query(c.FormatQuery(`
			SELECT referral, sum(amount) as amount, currency_id
			FROM referral_stats
			WHERE user_id = ?
			GROUP BY currency_id,  referral
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var referral, currency_id int64
		var amount float64
		err = rows.Scan(&referral, &amount, &currency_id)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		refs[referral] = map[int64]float64{currency_id: amount}
	}

	myRefsAmounts := make(map[int64]myRefsType)
	for refUserId, refData := range refs {
		data, err := c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", refUserId).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// получим ID майнеров, у которых лежат фото нужного нам юзера
		if len(data) == 0 {
			continue
		}
		minersIds := utils.GetMinersKeepers(data["photo_block_id"], data["photo_max_miner_id"], data["miners_keepers"], true)
		if len(minersIds) > 0 {
			hosts, err := c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			myRefsAmounts[refUserId] = myRefsType{Amounts: refData, Hosts: hosts}
			refPhotos[refUserId] = hosts
		}
	}
	myRefs := make(map[int64]myRefsType)
	for refUserId, refData := range myRefsAmounts {
		myRefs[refUserId] = refData
	}
	for refUserId, refData := range myRefsKeys {
		md5 := string(utils.Md5(refData["private_key"]))
		myRefs[refUserId] = myRefsType{Key: refData["private_key"], KeyUrl: c.NodeConfig["pool_url"] + "public/" + md5[0:16]}
	}

	/*
	 * Общая стата по рефам
	 */
	globalRefs := make(map[int64]globalRefsType)
	// берем лидеров по USD
	rows, err = c.Query(c.FormatQuery(`
			SELECT user_id, sum(amount) as amount
			FROM referral_stats
			WHERE currency_id = 72
			GROUP BY user_id
			ORDER BY amount DESC
			`))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		var user_id int64
		var amount float64
		err = rows.Scan(&user_id, &amount)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// вся прибыль с рефов у данного юзера
		refAmounts, err := c.GetAll(`
				SELECT ROUND(sum(amount)) as amount,  currency_id
				FROM referral_stats
				WHERE user_id = ?
				GROUP BY currency_id
				`, -1, user_id)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		data, err := c.OneRow("SELECT * FROM miners_data WHERE user_id  =  ?", user_id).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// получим ID майнеров, у которых лежат фото нужного нам юзера
		minersIds := utils.GetMinersKeepers(data["photo_block_id"], data["photo_max_miner_id"], data["miners_keepers"], true)
		hosts, err := c.GetList("SELECT http_host FROM miners_data WHERE miner_id  IN (" + utils.JoinInts(minersIds, ",") + ")").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		globalRefs[user_id] = globalRefsType{Amounts: refAmounts, Hosts: hosts}
		refPhotos[user_id] = hosts
	}

	lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewUser"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(lastTx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(lastTx, c.Lang)
	}

	TemplateStr, err := makeTemplate("new_user", "newUser", &newUserPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		MyRefs:          myRefs,
		GlobalRefs:      globalRefs,
		CurrencyList:    c.CurrencyList,
		RefPhotos:       refPhotos,
		PoolUrl:         c.NodeConfig["pool_url"]})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#11
0
func (c *Controller) ArbitrationArbitrator() (string, error) {

	log.Debug("ArbitrationArbitrator")

	txType := "MoneyBackRequest"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	myOrders, err := c.GetAll(`
			SELECT *
			FROM orders
			WHERE (arbitrator0 = ? OR arbitrator1 = ? OR arbitrator2 = ? OR arbitrator3 = ? OR arbitrator4 = ?) AND
						 status = 'refund'
			ORDER BY time DESC
			LIMIT 20
	`, 20, c.SessUserId, c.SessUserId, c.SessUserId, c.SessUserId, c.SessUserId)
	for k, data := range myOrders {
		if c.SessRestricted == 0 {
			data_, err := c.OneRow(`
						SELECT comment,
									 comment_status
						FROM `+c.MyPrefix+`my_comments
						WHERE id = ? AND
									 type = 'arbitrator'
						LIMIT 1
				`, data["id"]).String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			data["comment"] = data_["comment"]
			data["comment_status"] = data_["comment_status"]
		} else {
			data["comment"] = ""
			data["comment_status"] = "decrypted"
		}
		myOrders[k] = data
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorConditions", "MoneyBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("arbitration_arbitrator", "arbitrationArbitrator", &arbitrationArbitratorPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		CountSignArr:    c.CountSignArr,
		ShowSignData:    c.ShowSignData,
		UserId:          c.SessUserId,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		SignData:        "",
		LastTxFormatted: lastTxFormatted,
		CurrencyList:    c.CurrencyList,
		MinerId:         c.MinerId,
		MyOrders:        myOrders})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#12
0
func (c *Controller) ProgressBar() (string, error) {

	if !c.dbInit {
		return "", nil
	}

	progressBarPct := make(map[string]int64)
	progressBarPct["begin"] = 10
	progressBarPct["change_key"] = 10
	progressBarPct["my_table"] = 5
	progressBarPct["upgrade_country"] = 3
	progressBarPct["upgrade_face_hash"] = 3
	progressBarPct["upgrade_profile_hash"] = 3
	progressBarPct["upgrade_face_coords"] = 3
	progressBarPct["upgrade_profile_coords"] = 3
	progressBarPct["upgrade_video"] = 3
	progressBarPct["upgrade_host"] = 3
	progressBarPct["upgrade_geolocation"] = 3
	progressBarPct["promised_amount"] = 5
	progressBarPct["commission"] = 3
	progressBarPct["tasks"] = 8
	progressBarPct["vote"] = 5
	progressBarPct["referral"] = 1

	progressBar := make(map[string]int64)

	// сменил ли юзер ключ
	changeKey, err := c.Single("SELECT log_id FROM users WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangePrimaryKey"}), 1, c.TimeFormat)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if (len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0)) || changeKey > 0 {
		progressBar["change_key"] = 1
	}

	// есть ли в БД личная юзерсая таблица
	if c.Community {
		tables, err := c.GetAllTables()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if utils.InSliceString(utils.Int64ToStr(c.SessUserId)+"_my_table", tables) {
			progressBar["my_table"] = 1
		}
	} else {
		progressBar["my_table"] = 1
	}

	// апгрейд аккаунта
	myMinersId, err := c.GetMinerId(c.SessUserId)
	if myMinersId > 0 {
		progressBar["upgrade_country"] = 1
		progressBar["upgrade_face_hash"] = 1
		progressBar["upgrade_profile_hash"] = 1
		progressBar["upgrade_face_coords"] = 1
		progressBar["upgrade_profile_coords"] = 1
		progressBar["upgrade_video"] = 1
		progressBar["upgrade_host"] = 1
		progressBar["upgrade_geolocation"] = 1
	} else if c.SessRestricted == 0 {
		upgradeData, err := c.OneRow("SELECT user_id, race, country, geolocation, http_host as host, face_coords, profile_coords, video_url_id, video_type FROM " + c.MyPrefix + "my_table").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(upgradeData["race"]) > 0 && len(upgradeData["country"]) > 0 {
			progressBar["upgrade_country"] = 1
		}
		if len(upgradeData["face_hash"]) > 0 {
			progressBar["upgrade_face_hash"] = 1
		}
		if len(upgradeData["profile_hash"]) > 0 {
			progressBar["upgrade_profile_hash"] = 1
		}
		if len(upgradeData["face_coords"]) > 0 {
			progressBar["upgrade_face_coords"] = 1
		}
		if len(upgradeData["profile_coords"]) > 0 {
			progressBar["upgrade_profile_coords"] = 1
		}
		if _, err := os.Stat(*utils.Dir + "public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.mp4"); os.IsExist(err) {
			if len(upgradeData["video_url_id"]) > 0 {
				progressBar["upgrade_video"] = 1
			}
		}
		if len(upgradeData["host"]) > 0 {
			progressBar["upgrade_host"] = 1
		}
		if len(upgradeData["latitude"]) > 0 && len(upgradeData["longitude"]) > 0 {
			progressBar["upgrade_geolocation"] = 1
		}
	}

	// добавлена ли обещанная сумма
	promisedAmount, err := c.Single("SELECT id FROM promised_amount WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	// возможно юзер уже отправил запрос на добавление обещенной суммы
	last_tx, err = c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewPromisedAmount"}), 1, c.TimeFormat)
	if (len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0)) || promisedAmount > 0 {
		progressBar["promised_amount"] = 1
	}

	// установлена ли комиссия
	commission, err := c.Single("SELECT commission FROM commission WHERE user_id  =  ?", c.UserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	// возможно юзер уже отправил запрос на добавление комиссии
	last_tx, err = c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeCommission"}), 1, c.TimeFormat)
	if (len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0)) || len(commission) > 0 {
		progressBar["commission"] = 1
	}

	// голосование за параметры валют. для простоты смотрим в голоса за реф %
	vote, err := c.Single("SELECT user_id FROM votes_referral WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	last_tx, err = c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"VotesComplex"}), 1, c.TimeFormat)
	if (len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0)) || vote > 0 {
		progressBar["vote"] = 1
	}
	if c.SessRestricted == 0 {
		// выполнялись ли задания
		myTasks, err := c.Single("SELECT id FROM " + c.MyPrefix + "my_tasks").Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if myTasks > 0 {
			progressBar["tasks"] = 1
		}
	}

	// сколько майнеров зарегались по ключам данного юзера
	progressBar["referral"], err = c.Single(`
		SELECT count(miner_id)
		FROM users
		LEFT JOIN miners_data on miners_data.user_id = users.user_id
		WHERE referral = ? AND
					 miner_id > 0
	`, c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	// итог
	progressPct := progressBarPct["begin"]
	for name, result := range progressBar {
		if name == "referral" {
			progressPct += progressBarPct[name] * result
		} else {
			progressPct += progressBarPct[name]
		}
	}
	progressBar["begin"] = 1

	log.Debug("ProgressBar end")
	if !c.ContentInc {
		data, err := static.Asset("static/templates/progress_bar.html")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		t := template.Must(template.New("template").Parse(string(data)))
		b := new(bytes.Buffer)
		t.ExecuteTemplate(b, "progressBar", &progressBarPage{Lang: c.Lang, ProgressPct: progressPct})
		return b.String(), nil
	} else {
		TemplateStr, err := makeTemplate("progress", "progress", &progressBarPage{
			Lang:           c.Lang,
			ProgressBar:    progressBar,
			ProgressBarPct: progressBarPct,
			ProgressPct:    progressPct})
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		return TemplateStr, nil
	}
}
示例#13
0
func (c *Controller) AlertMessage() (string, error) {

	if c.SessRestricted != 0 {
		return "", nil
	}

	c.r.ParseForm()
	if ok, _ := regexp.MatchString(`install`, c.r.FormValue("tpl_name")); ok {
		return "", nil
	}

	show := false
	// проверим, есть ли сообщения от админа
	data, err := c.OneRow("SELECT * FROM alert_messages WHERE close  =  0 ORDER BY id DESC").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	var message map[string]string
	var adminMessage string
	if len(data["message"]) > 0 {
		err = json.Unmarshal([]byte(data["message"]), &message)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(message[utils.Int64ToStr(c.LangInt)]) > 0 {
			adminMessage = message[utils.Int64ToStr(c.LangInt)]
		} else {
			adminMessage = message["gen"]
		}
		if data["currency_list"] != "ALL" {
			// проверим, есть ли у нас обещанные суммы с такой валютой
			promisedAmount, err := c.Single("SELECT id FROM promised_amount WHERE currency_id IN (" + data["currency_list"] + ")").Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if promisedAmount > 0 {
				show = true
			}
		} else {
			show = true
		}
	}
	result := ""
	if show {
		result += `<script>
			$('#close_alert').bind('click', function () {
				$.post( 'ajax?controllerName=closeAlert', {
					'id' : '` + data["id"] + `'
				} );
			});
			</script>
			 <div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
			 <h4>Warning!</h4>
			    ` + adminMessage + `
			  </div>`
	}

	// сообщение о новой версии движка
	myVer, err := c.Single("SELECT current_version FROM info_block").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// возможны 2 сценария:
	// 1. информация о новой версии есть в блоках
	newVer, err := c.GetList("SELECT version FROM new_version WHERE alert  =  1").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	newMaxVer := "0"
	for i := 0; i < len(newVer); i++ {
		if utils.VersionOrdinal(newVer[i]) > utils.VersionOrdinal(myVer) && newMaxVer == "0" {
			newMaxVer = newVer[i]
		}
		if utils.VersionOrdinal(newVer[i]) > utils.VersionOrdinal(newMaxVer) && newMaxVer != "0" {
			newMaxVer = newVer[i]
		}
	}
	var newVersion string
	if newMaxVer != "0" {
		newVersion = strings.Replace(c.Lang["new_version"], "[ver]", newMaxVer, -1)
	}

	// для пулов и ограниченных юзеров выводим сообщение без кнопок
	if (c.Community || c.SessRestricted != 0) && newMaxVer != "0" {
		newVersion = strings.Replace(c.Lang["new_version_pulls"], "[ver]", newMaxVer, -1)
	}

	if newMaxVer != "0" && len(myVer) > 0 {
		result += `<script>
				$('#btn_install').bind('click', function () {
					$('#new_version_text').text('Please wait');
					$.post( 'ajax?controllerName=installNewVersion', {}, function(data) {
						$('#new_version_text').text(data);
					});
				});
				$('#btn_upgrade').bind('click', function () {
					$('#new_version_text').text('Please wait');
					$.post( 'ajax?controllerName=upgradeToNewVersion', {}, function(data) {
						$('#new_version_text').text(data);
					});
				});
			</script>

			<div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
			    <h4>Warning!</h4>
			   <div id='new_version_text'>` + newVersion + `</div>
			 </div>`
	}

	if c.SessRestricted == 0 && (!c.Community || c.PoolAdmin) {
		myMinerId, err := c.GetMinerId(c.SessUserId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// если юзер уже майнер, то у него должно быть настроено точное время
		if myMinerId > 0 {
			networkTime, err := utils.GetNetworkTime()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			diff := int64(math.Abs(float64(utils.Time() - networkTime.Unix())))
			if diff > c.Variables.Int64["alert_error_time"] {
				alertTime := strings.Replace(c.Lang["alert_time"], "[sec]", utils.Int64ToStr(diff), -1)
				result += `<div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				     <h4>Warning!</h4>
				     <div>` + alertTime + `</div>
				     </div>`
			}
		}
	}

	if c.SessRestricted == 0 {
		// после обнуления таблиц my_node_key будет пуст
		// получим время из последнего блока
		myNodePrivateKey, err := c.GetNodePrivateKey(c.MyPrefix)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		minerId, err := c.GetMinerId(c.SessUserId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// возможно юзер новенький на пуле и у него разные нод-ключи
		nodePublicKey, err := c.GetNodePublicKey(c.SessUserId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		myNodePublicKey, err := c.GetMyNodePublicKey(c.MyPrefix)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if (len(myNodePrivateKey) == 0 && minerId > 0) || (string(nodePublicKey) != myNodePublicKey && len(nodePublicKey) > 0) {
			result += `<div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				     <h4>Warning!</h4>
				     <div>` + c.Lang["alert_change_node_key"] + `</div>
				     </div>`
		}

	}

	// просто информируем, что в данном разделе у юзера нет прав
	skipCommunity := []string{"nodeConfig", "nulling", "startStop"}
	skipRestrictedUsers := []string{"nodeConfig", "changeNodeKey", "nulling", "startStop", "cashRequestIn", "cashRequestOut", "upgrade", "notifications", "interface"}
	if (!c.NodeAdmin && utils.InSliceString(c.TplName, skipCommunity)) || (c.SessRestricted != 0 && utils.InSliceString(c.TplName, skipRestrictedUsers)) {
		result += `<div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
			  <h4>Warning!</h4>
			  <div>` + c.Lang["permission_denied"] + `</div>
			  </div>`
	}

	// информируем, что у юзера нет прав и нужно стать майнером
	minersOnly := []string{"myCfProjects", "newCfProject", "cashRequestIn", "cashRequestOut", "changeNodeKey", "voting", "geolocation", "promisedAmountList", "promisedAmountAdd", "holidaysList", "newHolidays", "points", "tasks", "changeHost", "newUser", "changeCommission"}
	if utils.InSliceString(c.TplName, minersOnly) {
		minerId, err := c.Single("SELECT miner_id FROM users LEFT JOIN miners_data ON users.user_id  =  miners_data.user_id WHERE users.user_id  =  ?", c.SessUserId).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if minerId == 0 {
			result += `<div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				 <h4>Warning!</h4>
				 <div>` + c.Lang["only_for_miners"] + `</div>
				 </div>`
		}
	}

	// информируем, что необходимо вначале сменить праймари-ключ
	logId, err := c.Single("SELECT log_id FROM users WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if logId == 0 {
		text := ""
		// проверим, есть ли запросы на смену в тр-ях
		lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangePrimaryKey"}), 1, c.TimeFormat)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(lastTx) == 0 { // юзер еще не начинал смену ключа
			text = c.Lang["alert_change_primary_key"]
		} else if len(lastTx[0]["error"]) > 0 || len(lastTx[0]["queue_tx"]) > 0 || len(lastTx[0]["tx"]) > 0 || utils.Time()-utils.StrToInt64(lastTx[0]["time_int"]) > 3600 {
			text = c.Lang["please_try_again_change_key"]
		} else {
			text = c.Lang["please_wait_changing_key"]
		}
		result += `<div class="alert alert-danger alert-dismissable" style='margin-top: 30px'><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
				  <h4>` + c.Lang["warning"] + `</h4>
				  <div>` + text + `</div>
				  </div>`
	}

	return result, nil
}
示例#14
0
func FirstChangePkey(chBreaker chan bool, chAnswer chan string) {
	defer func() {
		if r := recover(); r != nil {
			log.Error("daemon Recovered", r)
			panic(r)
		}
	}()

	const GoroutineName = "FirstChangePkey"
	d := new(daemon)
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}
	d.goRoutineName = GoroutineName
	d.chAnswer = chAnswer
	d.chBreaker = chBreaker
	if utils.Mobile() {
		d.sleepTime = 360
	} else {
		d.sleepTime = 60
	}
	if !d.CheckInstall(chBreaker, chAnswer, GoroutineName) {
		return
	}
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}

BEGIN:
	for {
		log.Info(GoroutineName)
		MonitorDaemonCh <- []string{GoroutineName, utils.Int64ToStr(utils.Time())}

		// проверим, не нужно ли нам выйти из цикла
		if CheckDaemonsRestart(chBreaker, chAnswer, GoroutineName) {
			break BEGIN
		}

		community, err := d.GetCommunityUsers()
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		var uids []int64
		if len(community) > 0 {
			uids = community
		} else {
			myuid, err := d.GetMyUserId("")
			if err != nil {
				if d.dPrintSleep(err, d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}
			uids = append(uids, myuid)
		}
		log.Debug("uids %v", uids)
		var status, myPrefix string
		for _, uid := range uids {
			if len(community) > 0 {
				myPrefix = utils.Int64ToStr(uid) + "_"
			}
			status, err = d.Single(`SELECT status FROM ` + myPrefix + `my_table`).String()
			if err != nil {
				if d.dPrintSleep(err, d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}
			log.Debug("status: %v / myPrefix: %v", status, myPrefix)
			if status == "waiting_accept_new_key" {

				// если ключ кто-то сменил
				userPublicKey, err := d.GetUserPublicKey(uid)
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				myUserPublicKey, err := d.GetMyPublicKey(myPrefix)
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				if !bytes.Equal(myUserPublicKey, []byte(userPublicKey)) {
					log.Debug("myUserPublicKey:%s != userPublicKey:%s", utils.BinToHex(myUserPublicKey), utils.BinToHex(userPublicKey))
					// удаляем старый ключ
					err = d.ExecSql(`DELETE FROM ` + myPrefix + `my_keys`)
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					// и user_id
					q := `UPDATE ` + myPrefix + `my_table SET status="my_pending", user_id=0`
					if len(community) > 0 {
						q = `DELETE FROM ` + myPrefix + `my_table`
					}
					err = d.ExecSql(q)
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if len(community) > 0 {
						err = d.ExecSql(`DELETE FROM community WHERE user_id = ?`, uid)
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
					// и пробуем взять новый
					availablekey := &availablekey.AvailablekeyStruct{}
					availablekey.DCDB = d.DCDB
					userId, _, err := availablekey.GetAvailableKey()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if userId > 0 {
						if len(community) > 0 {
							err = d.ExecSql(`INSERT INTO community (user_id) VALUES (?)`, userId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						// генерим и шлем новую тр-ию
						err = d.SendTxChangePkey(userId)
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					} else {
						// если userId == 0, значит ключей в паблике больше нет и юзеру придется искать ключ самому
						continue
					}
				}

				// проверим, не прошла ли тр-ия и не сменился ли уже ключ
				userPubKeyCount, err := d.Single(`SELECT count(*) FROM ` + myPrefix + `my_keys WHERE status='approved'`).Int64()
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				log.Debug("userPubKey: %v", userPubKeyCount)
				if userPubKeyCount > 1 {
					err = d.ExecSql(`UPDATE ` + myPrefix + `my_table SET status='user'`)
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					// также, если это пул, то надо удалить приватный ключ из базы данных, т.к. взлом пула будет означать угон всех акков
					// хранение ключа на мобильном - безопасно, хранение ключа на ПК, пока Dcoin не стал популярен, тоже допустимо
					if len(community) > 0 {
						err = d.ExecSql(`DELETE private_key FROM ` + myPrefix + `my_keys`)
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}

					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}

				lastTx, err := d.GetLastTx(uid, utils.TypesToIds([]string{"ChangePrimaryKey"}), 1, "2006-02-01 15:04:05")
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				log.Debug("lastTx: %v", lastTx)
				if len(lastTx) > 0 {
					if len(lastTx[0]["error"]) > 0 || utils.Time()-utils.StrToInt64(lastTx[0]["time_int"]) > 1800 {
						// генерим и шлем новую тр-ию
						err = d.SendTxChangePkey(uid)
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			}
		}

		if d.dSleep(d.sleepTime) {
			break BEGIN
		}
	}
	log.Debug("break BEGIN %v", GoroutineName)
}
示例#15
0
文件: voting.go 项目: dzyk/dcoin-go
func (c *Controller) Voting() (string, error) {

	txType := "VotesComplex"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	waitVoting := make(map[int64]string)
	promisedAmountCurrencyList := make(map[int64]map[string]string)

	// голосовать майнер может только после того, как пройдет  miner_newbie_time сек
	regTime, err := c.Single("SELECT reg_time FROM miners_data WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	minerNewbie := ""
	if regTime > utils.Time()-c.Variables.Int64["miner_newbie_time"] && c.SessUserId != 1 {
		minerNewbie = strings.Replace(c.Lang["hold_time_wait2"], "[sec]", utils.TimeLeft(c.Variables.Int64["miner_newbie_time"]-(utils.Time()-regTime), c.Lang), -1)
	} else {
		// валюты
		rows, err := c.Query(c.FormatQuery(`
				SELECT currency_id,
							  name,
							  full_name,
							  start_time
				FROM promised_amount
					LEFT JOIN currency ON currency.id = promised_amount.currency_id
				WHERE user_id = ? AND
							 status IN ('mining', 'repaid') AND
							 start_time > 0 AND
							 del_block_id = 0
				GROUP BY currency_id
				`), c.SessUserId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var currency_id, start_time int64
			var name, full_name string
			err = rows.Scan(&currency_id, &name, &full_name, &start_time)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			// после добавления обещанной суммы должно пройти не менее min_hold_time_promise_amount сек, чтобы за неё можно было голосовать
			if start_time > utils.Time()-c.Variables.Int64["min_hold_time_promise_amount"] {
				waitVoting[currency_id] = strings.Replace(c.Lang["hold_time_wait"], "[sec]", utils.TimeLeft(c.Variables.Int64["min_hold_time_promise_amount"]-(utils.Time()-start_time), c.Lang), -1)
				continue
			}
			// если по данной валюте еще не набралось >1000 майнеров, то за неё голосовать нельзя.
			countMiners, err := c.Single(`
					SELECT count(user_id)
					FROM promised_amount
					WHERE start_time < ? AND
								 del_block_id = 0 AND
								 status IN ('mining', 'repaid') AND
								 currency_id = ? AND
								 del_block_id = 0
					GROUP BY  user_id
					`, utils.Time()-c.Variables.Int64["min_hold_time_promise_amount"], currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if countMiners < c.Variables.Int64["min_miners_of_voting"] {
				waitVoting[currency_id] = strings.Replace(c.Lang["min_miners_count"], "[miners_count]", utils.Int64ToStr(c.Variables.Int64["min_miners_of_voting"]), -1)
				waitVoting[currency_id] = strings.Replace(waitVoting[currency_id], "[remaining]", utils.Int64ToStr(c.Variables.Int64["min_miners_of_voting"]-countMiners), -1)
				continue
			}
			// голосовать можно не чаще 1 раза в 2 недели
			voteTime, err := c.Single("SELECT time FROM log_time_votes_complex WHERE user_id  =  ? AND time > ?", c.SessUserId, utils.Time()-c.Variables.Int64["limit_votes_complex_period"]).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if voteTime > 0 {
				waitVoting[currency_id] = strings.Replace(c.Lang["wait_voting"], "[sec]", utils.TimeLeft(c.Variables.Int64["limit_votes_complex_period"]-(utils.Time()-voteTime), c.Lang), -1)
				continue
			}

			// получим наши предыдущие голоса
			votesUserPct, err := c.Single("SELECT pct FROM votes_user_pct WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}

			votesMinerPct, err := c.Single("SELECT pct FROM votes_miner_pct WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}

			votesMaxOtherCurrencies, err := c.Single("SELECT count FROM votes_max_other_currencies WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}

			votesMaxPromisedAmount, err := c.Single("SELECT amount FROM votes_max_promised_amount WHERE user_id  =  ? AND currency_id  =  ?", c.SessUserId, currency_id).Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			promisedAmountCurrencyList[currency_id] = make(map[string]string)
			promisedAmountCurrencyList[currency_id]["votes_user_pct"] = utils.Int64ToStr(votesUserPct)
			promisedAmountCurrencyList[currency_id]["votes_miner_pct"] = utils.Int64ToStr(votesMinerPct)
			promisedAmountCurrencyList[currency_id]["votes_max_other_currencies"] = utils.Int64ToStr(votesMaxOtherCurrencies)
			promisedAmountCurrencyList[currency_id]["votes_max_promised_amount"] = utils.Int64ToStr(votesMaxPromisedAmount)
			promisedAmountCurrencyList[currency_id]["name"] = name
		}
	}

	referral, err := c.OneRow("SELECT first, second, third FROM votes_referral WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(referral) == 0 {
		referral["first"] = int64(utils.RandInt(0, 30))
		referral["second"] = int64(utils.RandInt(0, 30))
		referral["third"] = int64(utils.RandInt(0, 30))
	}

	maxCurrencyId, err := c.Single("SELECT max(id) FROM currency").Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	allMaxPromisedAmount := []int64{1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000, 20000000, 50000000, 100000000, 200000000, 500000000, 1000000000}

	allPct := utils.GetPctArray()
	pctArray := utils.GetPctArray()
	jsPct := "{"
	for year, sec := range pctArray {
		jsPct += fmt.Sprintf(`%v: '%v',`, year, sec)
	}
	jsPct = jsPct[:len(jsPct)-1] + "}"

	lastTx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"VotesComplex"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(lastTx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(lastTx, c.Lang)
	}

	refs := []string{"first", "second", "third"}
	refsNums := []int{0, 5, 10, 15, 20, 25, 30}

	TemplateStr, err := makeTemplate("voting", "voting", &VotingPage{
		Alert:                      c.Alert,
		Lang:                       c.Lang,
		CountSignArr:               c.CountSignArr,
		ShowSignData:               c.ShowSignData,
		UserId:                     c.SessUserId,
		TimeNow:                    timeNow,
		TxType:                     txType,
		TxTypeId:                   txTypeId,
		SignData:                   "",
		PromisedAmountCurrencyList: promisedAmountCurrencyList,
		MaxOtherCurrenciesCount:    []int{0, 1, 2, 3, 4},
		RefsNums:                   refsNums,
		Referral:                   referral,
		MinerNewbie:                minerNewbie,
		MaxCurrencyId:              maxCurrencyId,
		AllMaxPromisedAmount:       allMaxPromisedAmount,
		AllPct:                     allPct,
		LastTxFormatted:            lastTxFormatted,
		WaitVoting:                 waitVoting,
		CurrencyList:               c.CurrencyList,
		JsPct:                      jsPct,
		Refs:                       refs})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#16
0
func (c *Controller) MiningMenu() (string, error) {

	var err error
	log.Debug("first_select: %v", c.Parameters["first_select"])
	if c.Parameters["first_select"] == "1" {
		c.ExecSql(`UPDATE ` + c.MyPrefix + `my_table SET first_select=1`)
	}
	if len(c.Parameters["skip_promised_amount"]) > 0 {
		err = c.ExecSql("UPDATE " + c.MyPrefix + "my_table SET hide_first_promised_amount = 1")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}
	if len(c.Parameters["skip_commission"]) > 0 {
		err = c.ExecSql("UPDATE " + c.MyPrefix + "my_table SET hide_first_commission = 1")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	var result string
	checkCommission := func() error {
		// установлена ли комиссия
		commission, err := c.Single("SELECT commission FROM commission WHERE user_id  =  ?", c.SessUserId).String()
		if err != nil {
			return utils.ErrInfo(err)
		}
		if len(commission) == 0 {
			// возможно юзер уже отправил запрос на добавление комиссии
			last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeCommission"}), 1, c.TimeFormat)
			if err != nil {
				return utils.ErrInfo(err)
			}
			if len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0) {
				// авансом выдаем полное майнерское меню
				result = "full_mining_menu"
			} else {
				// возможно юзер нажал кнопку "пропустить"
				hideFirstCommission, err := c.Single("SELECT hide_first_commission FROM " + c.MyPrefix + "my_table").Int64()
				if err != nil {
					return utils.ErrInfo(err)
				}
				if hideFirstCommission == 0 {
					result = "need_commission"
				} else {
					result = "full_mining_menu"
				}
			}
		} else {
			result = "full_mining_menu"
		}
		return nil
	}

	hostTpl := ""
	// чтобы при добавлении общенных сумм, смены комиссий редиректило сюда
	navigate := "miningMenu"
	if c.SessRestricted != 0 {
		result = "need_email"
	} else {
		myMinerId, err := c.Single("SELECT miner_id FROM miners_data WHERE user_id  =  ?", c.SessUserId).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if myMinerId == 0 {
			// проверим, послали ли мы запрос в DC-сеть
			data, err := c.OneRow("SELECT node_voting_send_request, http_host as host FROM " + c.MyPrefix + "my_table").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			node_voting_send_request := utils.StrToInt64(data["node_voting_send_request"])
			host := data["host"]
			// если прошло менее 1 часа
			if time.Now().Unix()-node_voting_send_request < 3600 {
				result = "pending"
			} else if node_voting_send_request > 0 {
				// голосование нодов
				nodeVotesEnd, err := c.Single("SELECT votes_end FROM votes_miners WHERE user_id  =  ? AND type  =  'node_voting' ORDER BY id DESC", c.SessUserId).String()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
				if nodeVotesEnd == "1" { // голосование нодов завершено
					userVotesEnd, err := c.Single("SELECT votes_end FROM votes_miners WHERE user_id  =  ? AND type  =  'user_voting' ORDER BY id DESC", c.SessUserId).String()
					if err != nil {
						return "", utils.ErrInfo(err)
					}
					if userVotesEnd == "1" { // юзерское голосование закончено
						result = "bad"
					} else if userVotesEnd == "0" { // идет юзерское голосование
						result = "users_pending"
					} else {
						result = "bad_photos_hash"
						hostTpl = host
					}
				} else if nodeVotesEnd == "0" && time.Now().Unix()-node_voting_send_request < 86400 { // голосование нодов началось, ждем.
					result = "nodes_pending"
				} else if nodeVotesEnd == "0" && time.Now().Unix()-node_voting_send_request >= 86400 { // голосование нодов удет более суток и еще не завершилось
					result = "resend"
				} else { // запрос в DC-сеть еще не дошел и голосования не начались
					// если прошло менее 1 часа
					if time.Now().Unix()-node_voting_send_request < 3600 {
						result = "pending"
					} else { // где-то проблема и запрос не ушел.
						result = "resend"
					}
				}
			} else { // запрос на получение статуса "майнер" мы еще не слали
				result = "null"
			}
		} else {

			// установлены ли уведомления
			smtpUserName, err := c.Single("SELECT smtp_username FROM " + c.MyPrefix + "my_table").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if len(smtpUserName) == 0 {
				result = "need_notifications"
			} else {
				// добавлена ли обещанная сумма
				promisedAmount, err := c.Single("SELECT id FROM promised_amount WHERE user_id  =  ?", c.SessUserId).Int64()
				if err != nil {
					return "", utils.ErrInfo(err)
				}
				if promisedAmount == 0 {
					// возможно юзер уже отправил запрос на добавление обещенной суммы
					last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewPromisedAmount"}), 1, c.TimeFormat)
					if len(last_tx) > 0 && (len(last_tx[0]["queue_tx"]) > 0 || len(last_tx[0]["tx"]) > 0) {
						// установлена ли комиссия
						err = checkCommission()
						if err != nil {
							return "", utils.ErrInfo(err)
						}
					} else {
						// возможно юзер нажал кнопку "пропустить"
						hideFirstPromisedAmount, err := c.Single("SELECT hide_first_promised_amount FROM " + c.MyPrefix + "my_table").Int64()
						if err != nil {
							return "", utils.ErrInfo(err)
						}
						if hideFirstPromisedAmount == 0 {
							result = "need_promised_amount"
						} else {
							err = checkCommission()
							if err != nil {
								return "", utils.ErrInfo(err)
							}
						}
					}
				} else {
					// установлена ли комиссия
					err = checkCommission()
					if err != nil {
						return "", utils.ErrInfo(err)
					}
				}
			}
		}
	}

	var minerVotesAttempt int64
	var myComments []map[string]string
	c.Navigate = navigate
	lastTxFormatted := ""
	tplName := ""
	tplTitle := ""
	log.Debug(">result:", result)
	var nodePrivateKey string
	if result == "null" {
		tplName = "upgrade_0"
		tplTitle = "upgrade0"
		return c.Upgrade0()
	} else if result == "need_email" {
		tplName = "sign_up_in_the_pool"
		tplTitle = "signUpInThePool"
		//  сгенерим ключ для нода
		nodePrivateKey, _ = utils.GenKeys()
	} else if result == "need_notifications" {
		tplName = "notifications"
		tplTitle = "notifications"
		return c.Notifications()
	} else if result == "need_promised_amount" {
		tplName = "promised_amount_add"
		tplTitle = "upgrade"
		return c.NewPromisedAmount()
	} else if result == "need_commission" {
		tplName = "change_commission"
		tplTitle = "changeCommission"
		return c.ChangeCommission()
	} else if result == "full_mining_menu" {
		tplName = "mining_menu"
		tplTitle = "miningMenu"
		last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewUser", "NewMiner", "NewPromisedAmount", "ChangePromisedAmount", "VotesMiner", "ChangeGeolocation", "VotesPromisedAmount", "DelPromisedAmount", "CashRequestOut", "CashRequestIn", "VotesComplex", "ForRepaidFix", "NewHolidays", "ActualizationPromisedAmounts", "Mining", "NewMinerUpdate", "ChangeHost", "ChangeCommission"}), 3, c.TimeFormat)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(last_tx) > 0 {
			lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
		}
	} else {
		// сколько у нас осталось попыток стать майнером.
		countAttempt, err := c.CountMinerAttempt(c.SessUserId, "user_voting")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		minerVotesAttempt = c.Variables.Int64["miner_votes_attempt"] - countAttempt

		// комментарии проголосовавших
		myComments, err = c.GetAll(`SELECT * FROM `+c.MyPrefix+`my_comments WHERE comment != 'null' AND type NOT IN ('arbitrator','seller')`, -1)
		tplName = "upgrade"
		tplTitle = "upgrade"
	}

	log.Debug("tplName, tplTitle %v, %v", tplName, tplTitle)
	TemplateStr, err := makeTemplate(tplName, tplTitle, &miningMenuPage{
		Alert:             c.Alert,
		Lang:              c.Lang,
		CountSignArr:      c.CountSignArr,
		ShowSignData:      c.ShowSignData,
		UserId:            c.SessUserId,
		SignData:          "",
		CurrencyList:      c.CurrencyList,
		LastTxFormatted:   lastTxFormatted,
		MyComments:        myComments,
		Result:            result,
		NodePrivateKey:    nodePrivateKey,
		MinerVotesAttempt: minerVotesAttempt,
		Mobile:            utils.Mobile(),
		Host:              hostTpl})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#17
0
func (c *Controller) ChangeCommission() (string, error) {

	txType := "ChangeCommission"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	navigate := "changeCommission"
	if len(c.Navigate) > 0 {
		navigate = c.Navigate
	}

	minCommission := map[string]string{"WOC": "0.01", "AED": "0.04", "AOA": "0.96", "ARS": "0.06", "AUD": "0.01", "AZN": "0.01", "BDT": "0.78", "BGN": "0.01", "BOB": "0.07", "BRL": "0.02", "BYR": "89.25", "CAD": "0.01", "CHF": "0.01", "CLP": "5.13", "CNY": "0.06", "COP": "19.11", "CRC": "4.98", "CZK": "0.19", "DKK": "0.06", "DOP": "0.42", "DZD": "0.81", "EGP": "0.07", "EUR": "0.01", "GBP": "0.01", "GEL": "0.02", "GHS": "0.02", "GTQ": "0.08", "HKD": "0.08", "HRK": "0.06", "HUF": "2.25", "IDR": "103.85", "ILS": "0.04", "INR": "0.62", "IQD": "11.64", "IRR": "999.99", "JOD": "0.01", "JPY": "0.98", "KES": "0.87", "KRW": "11.14", "KWD": "0.01", "KZT": "1.53", "LBP": "15.11", "LKR": "1.32", "MAD": "0.08", "MXN": "0.13", "MYR": "0.03", "NGN": "1.61", "NOK": "0.06", "NPR": "0.98", "NZD": "0.01", "PEN": "0.03", "PHP": "0.44", "PKR": "1.03", "PLN": "0.03", "QAR": "0.04", "RON": "0.03", "RSD": "0.85", "RUB": "0.33", "SAR": "0.04", "SDG": "0.04", "SEK": "0.07", "SGD": "0.01", "SVC": "0.09", "SYP": "1.08", "THB": "0.31", "TND": "0.02", "TRY": "0.02", "TWD": "0.30", "TZS": "16.19", "UAH": "0.08", "UGX": "25.79", "USD": "0.01", "UZS": "21.15", "VEF": "0.06", "VND": "210.95", "YER": "2.15", "ZAR": "0.10", "BTC": "0.01", "LTC": "0.01"}

	currencyMin := make(map[int64]string)
	for id, name := range c.CurrencyList {
		currencyMin[id] = minCommission[name]
	}

	myCommission := make(map[int64][]float64)
	if c.SessRestricted == 0 {
		rows, err := c.Query(c.FormatQuery("SELECT currency_id, pct, min, max FROM " + c.MyPrefix + "my_commission"))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer rows.Close()
		for rows.Next() {
			var pct, min, max float64
			var currency_id int64
			err = rows.Scan(&currency_id, &pct, &min, &max)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			myCommission[currency_id] = []float64{pct, min, max}
		}
	}

	currencyList := c.CurrencyList
	commission := make(map[int64][]float64)
	for currency_id, _ := range currencyList {
		if len(myCommission[currency_id]) > 0 {
			commission[currency_id] = myCommission[currency_id]
		} else {
			commission[currency_id] = []float64{0.1, utils.StrToFloat64(currencyMin[currency_id]), 0}
		}
	}

	// для CF-проектов
	currencyList[1000] = "Crowdfunding"
	if len(myCommission[1000]) > 0 {
		commission[1000] = myCommission[1000]
	} else {
		commission[1000] = []float64{0.1, 0.01, 0}
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorConditions", "MoneyBack"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	//limitsText := strings.Replace(c.Lang["change_commission_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_commission"]), -1)
	//limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_commission_period"]], -1)

	log.Debug("commission:", commission)

	TemplateStr, err := makeTemplate("change_commission", "changeCommission", &changeCommissionPage{
		Alert:            c.Alert,
		Lang:             c.Lang,
		CountSignArr:     c.CountSignArr,
		ShowSignData:     c.ShowSignData,
		UserId:           c.SessUserId,
		TimeNow:          timeNow,
		TxType:           txType,
		TxTypeId:         txTypeId,
		SignData:         "",
		LastTxFormatted:  lastTxFormatted,
		CurrencyList:     c.CurrencyList,
		ConfigCommission: c.ConfigCommission,
		Navigate:         navigate,
		Commission:       commission})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#18
0
func (c *Controller) WalletsList() (string, error) {

	var err error

	// валюты
	currencyList := c.CurrencyListCf

	confirmedBlockId := c.ConfirmedBlockId

	var wallets []utils.DCAmounts
	var myDcTransactions []map[string]string
	if c.SessUserId > 0 {
		wallets, err = c.GetBalances(c.SessUserId)
		if c.SessRestricted == 0 {
			myDcTransactions, err = c.GetAll("SELECT * FROM "+c.MyPrefix+"my_dc_transactions ORDER BY id DESC LIMIT 100", 100)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			for id, data := range myDcTransactions {
				t := time.Unix(utils.StrToInt64(data["time"]), 0)
				timeFormatted := t.Format(c.TimeFormat)
				log.Debug("timeFormatted", utils.StrToInt64(data["time"]), timeFormatted, c.TimeFormat)
				myDcTransactions[id]["timeFormatted"] = timeFormatted
				myDcTransactions[id]["numBlocks"] = "0"
				blockId := utils.StrToInt64(data["block_id"])
				if blockId > 0 {
					myDcTransactions[id]["numBlocks"] = utils.Int64ToStr(confirmedBlockId - blockId)
				}
			}
		}
	}
	userType := "SendDc"
	projectType := "CfSendDc"
	userTypeId := utils.TypeInt(userType)
	projectTypeId := utils.TypeInt(projectType)
	timeNow := time.Now().Unix()
	currentBlockId, err := c.GetBlockId()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	names := make(map[string]string)
	names["cash_request"] = c.Lang["cash"]
	names["from_mining_id"] = c.Lang["from_mining"]
	names["from_repaid"] = c.Lang["from_repaid_mining"]
	names["from_user"] = c.Lang["from_user"]
	names["node_commission"] = c.Lang["node_commission"]
	names["system_commission"] = c.Lang["system_commission"]
	names["referral"] = c.Lang["referral"]
	names["cf_project"] = "Crowd funding"
	names["cf_project_refund"] = "Crowd funding refund"

	minerId, err := c.GetMinerId(c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	c.r.ParseForm()
	// если юзер кликнул по кнопку "профинансировать" со страницы проекта
	//parameters := c.r.FormValue("parameters")
	cfProjectId := int64(utils.StrToFloat64(c.Parameters["projectId"]))

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"SendDc"}), 1, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}
	arbitrationTrustList_, err := c.GetMap(`
			SELECT arbitrator_user_id,
					 	conditions
			FROM arbitration_trust_list
			LEFT JOIN arbitrator_conditions ON arbitrator_conditions.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE arbitration_trust_list.user_id = ?
	`, "arbitrator_user_id", "conditions", c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	arbitrationTrustList := make(map[int64]map[int64][]string)
	var jsonMap map[string][]string
	for arbitrator_user_id, conditions := range arbitrationTrustList_ {
		err = json.Unmarshal([]byte(conditions), &jsonMap)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		uidInt := utils.StrToInt64(arbitrator_user_id)
		arbitrationTrustList[uidInt] = make(map[int64][]string)
		for currenycId, data := range jsonMap {
			arbitrationTrustList[uidInt][utils.StrToInt64(currenycId)] = data
		}
	}
	log.Debug("arbitrationTrustList", arbitrationTrustList)

	TemplateStr, err := makeTemplate("wallets_list", "walletsList", &walletsListPage{
		CountSignArr:         c.CountSignArr,
		CfProjectId:          cfProjectId,
		Names:                names,
		UserIdStr:            utils.Int64ToStr(c.SessUserId),
		Alert:                c.Alert,
		Community:            c.Community,
		ConfigCommission:     c.ConfigCommission,
		ProjectType:          projectType,
		UserType:             userType,
		UserId:               c.SessUserId,
		Lang:                 c.Lang,
		CurrencyList:         currencyList,
		Wallets:              wallets,
		MyDcTransactions:     myDcTransactions,
		UserTypeId:           userTypeId,
		ProjectTypeId:        projectTypeId,
		Time:                 timeNow,
		CurrentBlockId:       currentBlockId,
		ConfirmedBlockId:     confirmedBlockId,
		MinerId:              minerId,
		Config:               c.NodeConfig,
		LastTxFormatted:      lastTxFormatted,
		ArbitrationTrustList: arbitrationTrustList,
		ShowSignData:         c.ShowSignData,
		SignData:             ""})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#19
0
func (c *Controller) CurrencyExchange() (string, error) {

	txType := "NewForexOrder"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	addSql := ""
	if len(c.Parameters["all_currencies"]) == 0 {
		// по умолчанию выдаем только те валюты, которые есть хоть у кого-то на кошельках
		actualCurrencies, err := c.GetList("SELECT currency_id FROM wallets GROUP BY currency_id").String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(actualCurrencies) > 0 {
			addSql = " WHERE id IN (" + strings.Join(actualCurrencies, ",") + ")"
		}
	}
	currencyListName := make(map[int64]string)
	currency, err := c.GetMap("SELECT id, name FROM currency "+addSql+" ORDER BY name", "id", "name")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	for k, v := range currency {
		currencyListName[utils.StrToInt64(k)] = v
	}

	var sellCurrencyId, buyCurrencyId int64
	if len(c.Parameters["buy_currency_id"]) > 0 {
		buyCurrencyId = utils.StrToInt64(c.Parameters["buy_currency_id"])
		c.sess.Set("buy_currency_id", buyCurrencyId)
	}
	if len(c.Parameters["sell_currency_id"]) > 0 {
		sellCurrencyId = utils.StrToInt64(c.Parameters["sell_currency_id"])
		c.sess.Set("sell_currency_id", sellCurrencyId)
	}
	if buyCurrencyId == 0 {
		buyCurrencyId = GetSessInt64("buy_currency_id", c.sess)
	}
	if sellCurrencyId == 0 {
		sellCurrencyId = GetSessInt64("sell_currency_id", c.sess)
	}
	if buyCurrencyId == 0 {
		buyCurrencyId = 1
	}
	if sellCurrencyId == 0 {
		sellCurrencyId = 72
	}

	buyCurrencyName := currencyListName[buyCurrencyId]
	sellCurrencyName := currencyListName[sellCurrencyId]

	// валюты
	currencyListFullName, err := c.GetCurrencyListFullName()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	buyOrders, err := c.GetAll(`
			SELECT *
			FROM forex_orders
			WHERE  buy_currency_id =  ? AND
						 sell_currency_id = ? AND
						 empty_block_id = 0 AND
						 del_block_id = 0
						 `, 100, buyCurrencyId, sellCurrencyId)

	sellOrders, err := c.GetAll(`
			SELECT *
			FROM forex_orders
			WHERE  buy_currency_id =  ? AND
						 sell_currency_id = ? AND
						 empty_block_id = 0 AND
						 del_block_id = 0
						 `, 100, sellCurrencyId, buyCurrencyId)

	myOrders, err := c.GetAll(`
			SELECT *
			FROM forex_orders
			WHERE user_id =  ? AND
						 empty_block_id = 0 AND
						 del_block_id = 0
						 `, 100, c.SessUserId)

	rows, err := c.Query(c.FormatQuery(`
			SELECT amount, currency_id, last_update
			FROM wallets
			WHERE user_id = ? AND
						currency_id IN (?, ?)
			`), c.SessUserId, sellCurrencyId, buyCurrencyId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	walletsAmounts := make(map[int64]float64)
	for rows.Next() {
		var amount float64
		var currency_id, last_update int64
		err = rows.Scan(&amount, &currency_id, &last_update)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		profit, err := c.CalcProfitGen(currency_id, amount, c.SessUserId, last_update, timeNow, "wallets")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		amount += profit
		amount = utils.Round(amount, 2)
		forex_orders_amount, err := c.Single("SELECT sum(amount) FROM forex_orders WHERE user_id = ? AND sell_currency_id = ? AND del_block_id = 0", c.SessUserId, currency_id).Float64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		amount -= forex_orders_amount
		walletsAmounts[currency_id] = amount
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"NewForexOrder", "DelForexOrder"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	if len(last_tx) > 0 {
		lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang)
	}

	TemplateStr, err := makeTemplate("currency_exchange", "currencyExchange", &currencyExchangePage{
		LastTxFormatted:      lastTxFormatted,
		Lang:                 c.Lang,
		CountSignArr:         c.CountSignArr,
		ShowSignData:         c.ShowSignData,
		WalletsAmounts:       walletsAmounts,
		CurrencyListName:     currencyListName,
		BuyCurrencyId:        buyCurrencyId,
		SellCurrencyId:       sellCurrencyId,
		BuyCurrencyName:      buyCurrencyName,
		SellCurrencyName:     sellCurrencyName,
		CurrencyListFullName: currencyListFullName,
		ConfigCommission:     c.ConfigCommission,
		TimeNow:              timeNow,
		SellOrders:           sellOrders,
		BuyOrders:            buyOrders,
		MyOrders:             myOrders,
		UserId:               c.SessUserId,
		TxType:               txType,
		TxTypeId:             txTypeId,
		SignData:             ""})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#20
0
func (c *Controller) Arbitration() (string, error) {

	txType := "ChangeArbitratorList"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	var q string
	if c.ConfigIni["db_type"] == "postgresql" {
		q = `SELECT DISTINCT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE arbitration_trust_list.user_id = ? AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id, url
			ORDER BY count(arbitration_trust_list.user_id)  DESC`
	} else {
		q = `SELECT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE arbitration_trust_list.user_id = ? AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id
			ORDER BY count(arbitration_trust_list.user_id)  DESC`
	}
	myTrustList, err := c.GetAll(q, 100, c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	var arbitrators []*arbitrationType
	// top 10 арбитров
	if c.ConfigIni["db_type"] == "postgresql" {
		q = `SELECT DISTINCT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN miners_data ON miners_data.user_id = arbitration_trust_list.user_id
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE miners_data.status='miner' AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id, url
			ORDER BY count(arbitration_trust_list.user_id)  DESC
			LIMIT 10`
	} else {
		q = `SELECT arbitrator_user_id, url, count(arbitration_trust_list.user_id) as count
			FROM arbitration_trust_list
			LEFT JOIN miners_data ON miners_data.user_id = arbitration_trust_list.user_id
			LEFT JOIN users ON users.user_id = arbitration_trust_list.arbitrator_user_id
			WHERE miners_data.status='miner' AND
						 arbitration_trust_list.arbitrator_user_id > 0
			GROUP BY arbitrator_user_id
			ORDER BY count(arbitration_trust_list.user_id)  DESC
			LIMIT 10`
	}
	rows, err := c.Query(c.FormatQuery(q))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		//var pct, amount float64
		var arbitrator_user_id, count int64
		var url string
		err = rows.Scan(&arbitrator_user_id, &url, &count)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		// кол-во манибеков и сумма за последний месяц
		refund_data, err := c.OneRow(`
			SELECT count(id) as count, sum(refund) as sum
			FROM orders
			LEFT JOIN miners_data ON miners_data.user_id = orders.buyer
			WHERE (arbitrator0 = ? OR arbitrator1 = ? OR arbitrator2 = ? OR arbitrator3 = ? OR arbitrator4 = ?) AND
						 orders.status = 'refund' AND
						 arbitrator_refund_time > ? AND
						 arbitrator_refund_time < ? AND
						 miners_data.status = 'miner'
			GROUP BY user_id
		`, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, timeNow-3600*24*30, timeNow).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// кол-во неудовлетвореных манибеков за последний месяц
		count_rejected_refunds, err := c.Single(`
			SELECT count(id)
			FROM orders
			LEFT JOIN miners_data ON miners_data.user_id = orders.buyer
			WHERE  (arbitrator0 = ? OR arbitrator1 = ? OR arbitrator2 = ? OR arbitrator3 = ? OR arbitrator4 = ?) AND
						 orders.status = 'refund' AND
						 end_time > ? AND
						 end_time < ? AND
						 voluntary_refund = 0 AND
						 refund = 0 AND
						 miners_data.status = 'miner'
			GROUP BY user_id
		`, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, arbitrator_user_id, timeNow-3600*24*30, timeNow).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		log.Debug("utils.StrToInt64(refund_data[count])", utils.StrToInt64(refund_data["count"]))
		log.Debug("utils.StrToInt64(refund_data[sum])", utils.StrToInt64(refund_data["sum"]))

		arbitrators = append(arbitrators, &arbitrationType{Arbitrator_user_id: arbitrator_user_id, Url: url, Count: count, Refund_data_count: utils.StrToInt64(refund_data["count"]), Refund_data_sum: utils.StrToFloat64(refund_data["sum"]), Count_rejected_refunds: count_rejected_refunds})

	}

	// арбитр ли наш юзер
	arbitrator, err := c.Single("SELECT conditions FROM arbitrator_conditions WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// продавец ли
	arbitrationDaysRefund, err := c.Single("SELECT arbitration_days_refund FROM users WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	arbitrationTrustList, err := c.Single("SELECT arbitrator_user_id FROM arbitration_trust_list WHERE user_id  =  ?", c.SessUserId).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"ChangeArbitratorList", "ChangeArbitratorConditions", "ChangeSellerHoldBack", "ChangeSellerHoldBack", "MoneyBackRequest", "MoneyBack", "ChangeMoneyBackTime"}), 3, c.TimeFormat)
	lastTxFormatted := ""
	var pendingTx_ map[int64]int64
	if len(last_tx) > 0 {
		lastTxFormatted, pendingTx_ = utils.MakeLastTx(last_tx, c.Lang)
	}
	pendingTx := pendingTx_[txTypeId]

	TemplateStr, err := makeTemplate("arbitration", "arbitration", &arbitrationPage{
		Alert:                 c.Alert,
		Lang:                  c.Lang,
		CountSignArr:          c.CountSignArr,
		ShowSignData:          c.ShowSignData,
		UserId:                c.SessUserId,
		TimeNow:               timeNow,
		TxType:                txType,
		TxTypeId:              txTypeId,
		SignData:              "",
		Arbitrators:           arbitrators,
		MyTrustList:           myTrustList,
		PendingTx:             pendingTx,
		Arbitrator:            arbitrator,
		ArbitrationDaysRefund: arbitrationDaysRefund,
		LastTxFormatted:       lastTxFormatted,
		ArbitrationTrustList:  arbitrationTrustList})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}