Exemplo n.º 1
0
func (c *Controller) UpdatingBlockchain() (string, error) {

	var blockTime, blockId, blockMeter int64
	var waitText, startDaemons, checkTime string
	var restartDb bool

	if c.dbInit {
		ConfirmedBlockId, err := c.DCDB.GetConfirmedBlockId()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if ConfirmedBlockId == 0 {
			firstLoadBlockchain, err := c.DCDB.Single("SELECT first_load_blockchain FROM config").String()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if firstLoadBlockchain == "file" {
				waitText = c.Lang["loading_blockchain_please_wait"]
			} else {
				waitText = c.Lang["is_synchronized_with_the_dc_network"]
			}
		} else {
			LastBlockData, err := c.DCDB.GetLastBlockData()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			blockTime = LastBlockData["lastBlockTime"]
			blockId = LastBlockData["blockId"]
		}

		// для сингл-мода, кнопка включения и выключения демонов
		if !c.Community {
			lockName, err := c.DCDB.GetMainLockName()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if lockName == "main_lock" {
				startDaemons = `<a href="#" id="start_daemons" style="color:#C90600">Start daemons</a>`
			}
			// инфа о синхронизации часов
			switch runtime.GOOS {
			case "linux":
				checkTime = c.Lang["check_time_nix"]
			case "windows":
				checkTime = c.Lang["check_time_win"]
			case "darwin":
				checkTime = c.Lang["check_time_mac"]
			default:
				checkTime = c.Lang["check_time_nix"]
			}
			checkTime = c.Lang["check_time"] + checkTime
			mainLock, err := c.Single(`SELECT lock_time from main_lock`).Int64()
			if mainLock > 0 && utils.Time()-300 > mainLock {
				restartDb = true
			}
		}

		nodeConfig, err := c.GetNodeConfig()
		blockchain_url := nodeConfig["first_load_blockchain_url"]
		if len(blockchain_url) == 0 {
			blockchain_url = consts.BLOCKCHAIN_URL
		}
		resp, err := http.Get(blockchain_url)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		blockChainSize := resp.ContentLength
		if blockChainSize == 0 {
			blockChainSize = consts.BLOCKCHAIN_SIZE
		}
		defer resp.Body.Close()

		blockMeter = int64(utils.Round(float64((blockId/consts.LAST_BLOCK)*100), 0)) - 1

	} else {
		waitText = c.Lang["loading_blockchain_please_wait"]
	}

	var mobile bool
	if utils.Mobile() {
		mobile = true
	}

	networkTime, err := utils.GetNetworkTime()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	diff := int64(math.Abs(float64(utils.Time() - networkTime.Unix())))
	var alertTime string
	if c.dbInit && diff > c.Variables.Int64["alert_error_time"] {
		alertTime = strings.Replace(c.Lang["alert_time"], "[sec]", utils.Int64ToStr(diff), -1)
	}

	funcMap := template.FuncMap{
		"noescape": func(s string) template.HTML {
			return template.HTML(s)
		},
	}
	data, err := static.Asset("static/templates/updating_blockchain.html")
	t := template.New("template").Funcs(funcMap)
	t, err = t.Parse(string(data))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	b := new(bytes.Buffer)
	t.Execute(b, &updatingBlockchainStruct{RestartDb: restartDb, Lang: c.Lang, WaitText: waitText, BlockId: blockId, BlockTime: blockTime, StartDaemons: startDaemons, BlockMeter: blockMeter, CheckTime: checkTime, LastBlock: consts.LAST_BLOCK, BlockChainSize: consts.BLOCKCHAIN_SIZE, Mobile: mobile, AlertTime: alertTime})
	return b.String(), nil
}
Exemplo n.º 2
0
func Notifications(chBreaker chan bool, chAnswer chan string) {
	defer func() {
		if r := recover(); r != nil {
			log.Error("daemon Recovered", r)
			panic(r)
		}
	}()

	const GoroutineName = "Notifications"
	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 = 300
	} else {
		d.sleepTime = 60
	}
	if !d.CheckInstall(chBreaker, chAnswer, GoroutineName) {
		return
	}
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}

BEGIN:
	for {

		//sendnotif.SendMobileNotification("11111111", "222222222222222222")

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

		// проверим, не нужно ли нам выйти из цикла
		if CheckDaemonsRestart(chBreaker, chAnswer, GoroutineName) {
			break BEGIN
		}
		// валюты
		currencyList, err := d.GetCurrencyList(false)
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		notificationsArray := make(map[string]map[int64]map[string]string)
		userEmailSmsData := make(map[int64]map[string]string)

		myUsersIds, err := d.GetCommunityUsers()
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		var community bool
		if len(myUsersIds) == 0 {
			community = false
			myUserId, err := d.GetMyUserId("")
			if err != nil {
				if d.dPrintSleep(err, d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}
			myUsersIds = append(myUsersIds, myUserId)
		} else {
			community = true
		}
		/*myPrefix, err:= d.GetMyPrefix()
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {	break BEGIN }
			continue BEGIN
		}*/
		myBlockId, err := d.GetMyBlockId()
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		blockId, err := d.GetBlockId()
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		if myBlockId > blockId {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		if len(myUsersIds) > 0 {
			for i := 0; i < len(myUsersIds); i++ {
				myPrefix := ""
				if community {
					myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
				}
				myData, err := d.OneRow("SELECT * FROM " + myPrefix + "my_table").String()
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				// на пуле шлем уведомления только майнерам
				if community && myData["miner_id"] == "0" {
					continue
				}
				myNotifications, err := d.GetAll("SELECT * FROM "+myPrefix+"my_notifications", -1)
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				for _, data := range myNotifications {
					notificationsArray[data["name"]] = make(map[int64]map[string]string)
					notificationsArray[data["name"]][myUsersIds[i]] = map[string]string{"email": data["email"], "sms": data["sms"], "mobile": data["mobile"]}
					userEmailSmsData[myUsersIds[i]] = myData
				}
			}
		}

		poolAdminUserId, err := d.GetPoolAdminUserId()
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		subj := "DCoin notifications"
		for name, notificationInfo := range notificationsArray {
			switch name {
			case "admin_messages":
				data, err := d.OneRow("SELECT id, message FROM alert_messages WHERE notification  =  0").String()
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				if len(data) > 0 {
					err = d.ExecSql("UPDATE alert_messages SET notification = 1 WHERE id = ?", data["id"])
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if myBlockId > blockId {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					for userId, emailSms := range notificationInfo {
						if emailSms["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, userEmailSmsData[userId]["text"])
						}
						if emailSms["email"] == "1" {
							err = d.SendMail("From Admin: "+data["message"], subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if emailSms["sms"] == "1" {
							_, err = utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], userEmailSmsData[userId]["text"])
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
					}
				}
			case "incoming_cash_requests":
				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					data, err := d.OneRow("SELECT id, amount, currency_id FROM "+myPrefix+"my_cash_requests WHERE to_user_id  =  ? AND notification  =  0 AND status  =  'pending'", userId).String()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if len(data) > 0 {
						text := `You"ve got the request for ` + data["amount"] + ` ` + currencyList[utils.StrToInt64(data["currencyId"])] + `. It has to be repaid within the next 48 hours.`

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE "+myPrefix+"my_cash_requests SET notification = 1 WHERE id = ?", data["id"])
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "change_in_status":

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					status, err := d.Single("SELECT status FROM " + myPrefix + "my_table WHERE notification_status = 0").String()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if len(status) > 0 {
						text := `New status: ` + status

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE " + myPrefix + "my_table SET notification_status = 1")
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "dc_came_from":

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					myDcTransactions, err := d.GetAll(`
							SELECT  id,
							               amount,
										 currency_id,
										 comment_status,
										 comment
							FROM `+myPrefix+`my_dc_transactions
							WHERE to_user_id = ? AND
									 	notification = 0 AND
									 	status = 'approved'`, -1, userId)
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					for _, data := range myDcTransactions {
						comment := ""
						if data["comment_status"] == "decrypted" {
							comment = data["comment"]
						}
						text := `You've got ` + data["amount"] + ` D` + currencyList[utils.StrToInt64(data["currency_id"])] + ` ` + comment

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							//err = d.SendMail(`<br><span style="font-size:16px">`+text+`</span>`, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE "+myPrefix+"my_dc_transactions SET notification = 1 WHERE id = ?", data["id"])
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "dc_sent":

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					myDcTransactions, err := d.GetAll(`
							SELECT id,
									    amount,
									    currency_id
							FROM `+myPrefix+`my_dc_transactions
							WHERE to_user_id !=  ? AND
										 notification = 0 AND
										 status = 'approved'`, -1, userId)
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					for _, data := range myDcTransactions {

						text := `Debiting ` + data["amount"] + ` D` + currencyList[utils.StrToInt64(data["currency_id"])]

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE "+myPrefix+"my_dc_transactions SET notification = 1 WHERE id = ?", data["id"])
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "update_primary_key":

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					data, err := d.OneRow("SELECT id FROM " + myPrefix + "my_keys WHERE notification = 0 AND status = 'approved'").String()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if len(data) > 0 {
						text := `Update primary key`

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE "+myPrefix+"my_keys SET notification = 1 WHERE id = ?", data["id"])
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "update_email":

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					myNewEmail, err := d.Single("SELECT status FROM " + myPrefix + "my_table WHERE notification_email  =  0").String()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if len(myNewEmail) > 0 {
						text := `New email: ` + myNewEmail

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE " + myPrefix + "my_table SET notification_email = 1")
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "update_sms_request":

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					smsHttpGetRequest, err := d.Single("SELECT sms_http_get_request FROM " + myPrefix + "my_table WHERE notification_sms_http_get_request  =  0").String()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if len(smsHttpGetRequest) > 0 {
						text := `New sms_http_get_request ` + smsHttpGetRequest

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE " + myPrefix + "my_table SET notification_sms_http_get_request = 1")
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}
			case "voting_results":
				myDcTransactions, err := d.GetAll(`
						SELECT  id,
									 currency_id,
									 miner,
									 user,
									 block_id
						FROM pct
						WHERE notification = 0`, -1)
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				text := ""
				pctUpd := false
				for _, data := range myDcTransactions {
					pctUpd = true
					text += fmt.Sprintf("New pct %v! miner: %v %/block, user: %v %/block", currencyList[utils.StrToInt64(data["currency_id"])], ((math.Pow(1+utils.StrToFloat64(data["miner"]), 120) - 1) * 100), ((math.Pow(1+utils.StrToFloat64(data["user"]), 120) - 1) * 100))
				}
				if pctUpd {
					err = d.ExecSql("UPDATE pct SET notification = 1 WHERE notification = 0")
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
				}
				if myBlockId > blockId {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}

				// шлется что-то не то, потом поправлю, пока отключил
				if community {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}

				if len(text) > 0 {
					for userId, emailSms := range notificationInfo {

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if emailSms["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if emailSms["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
					}
				}
			case "voting_time": // Прошло 2 недели с момента Вашего голосования за %

				for i := 0; i < len(myUsersIds); i++ {
					myPrefix := ""
					if community {
						myPrefix = utils.Int64ToStr(myUsersIds[i]) + "_"
					}
					userId := myUsersIds[i]
					lastVoting, err := d.Single("SELECT last_voting FROM " + myPrefix + "my_complex_votes WHERE notification  =  0").Int64()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if lastVoting > 0 && utils.Time()-lastVoting > 86400*14 {
						text := "It's 2 weeks from the moment you voted."

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if notificationsArray[name][userId]["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if notificationsArray[name][userId]["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
						err = d.ExecSql("UPDATE " + myPrefix + "my_complex_votes SET notification = 1")
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
					}
				}

			case "new_version":

				newVersion, err := d.Single("SELECT version FROM new_version WHERE notification  =  0 AND alert  =  1").String()
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}

				err = d.ExecSql("UPDATE new_version SET notification = 1 WHERE version = ?", newVersion)
				if err != nil {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}

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

				// в пуле это лишняя инфа
				if community {
					if d.dPrintSleep(err, d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
				if len(newVersion) > 0 {
					for userId, emailSms := range notificationInfo {
						text := "New version: " + newVersion

						if notificationsArray[name][userId]["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if emailSms["email"] == "1" {
							err = d.SendMail(text, subj, userEmailSmsData[userId]["email"], userEmailSmsData[userId], community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if emailSms["sms"] == "1" {
							utils.SendSms(userEmailSmsData[userId]["sms_http_get_request"], text)
						}
					}
				}

			case "node_time": // Расхождение времени сервера более чем на 5 сек

				var adminUserId int64
				// если работаем в режиме пула, то нужно слать инфу админу пула
				if community {
					adminUserId = poolAdminUserId
				} else {
					// проверим, нода ли мы
					my_table, err := d.OneRow("SELECT user_id, miner_id FROM my_table").Int64()
					if err != nil {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					}
					if my_table["miner_id"] == 0 {
						if d.dPrintSleep(err, d.sleepTime) {
							break BEGIN
						}
						continue BEGIN
					} else {
						adminUserId = my_table["user_id"]
					}
					emailSms := notificationInfo[adminUserId]
					myData := userEmailSmsData[adminUserId]
					if len(myData) > 0 {
						networkTime, err := utils.GetNetworkTime()
						if err != nil {
							if d.dPrintSleep(err, d.sleepTime) {
								break BEGIN
							}
							continue BEGIN
						}
						diff := int64(math.Abs(float64(utils.Time() - networkTime.Unix())))
						text := ""
						if diff > 5 {
							text = "Divergence time " + utils.Int64ToStr(diff) + " sec"
						}

						if emailSms["mobile"] == "1" {
							sendnotif.SendMobileNotification(subj, text)
						}
						if emailSms["email"] == "1" {
							err = d.SendMail(text, subj, myData["email"], myData, community, poolAdminUserId)
							if err != nil {
								if d.dPrintSleep(err, d.sleepTime) {
									break BEGIN
								}
								continue BEGIN
							}
						}
						if emailSms["sms"] == "1" {
							utils.SendSms(myData["sms_http_get_request"], text)
						}
					}
				}
			}
		}

		if d.dSleep(d.sleepTime) {
			break BEGIN
		}
	}
	log.Debug("break BEGIN %v", GoroutineName)
}
Exemplo n.º 3
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
}