Пример #1
0
func GetMapAclients(db autorc.Conn, sqlstr string, makeFlag string, golog syslog.Writer) []d.Aclient {

	var aclientsmap []d.Aclient

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {

		if rows, res, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		} else {

			aclientsmap = make([]d.Aclient, len(rows))

			for i, row := range rows {

				aclientsmap[i].Id = row.Int(res.Map("id"))
				aclientsmap[i].Phone = row.Str(res.Map("phone"))
				aclientsmap[i].Opcode = row.Str(res.Map("opcode"))
				aclientsmap[i].Nmake = makeFlag
				aclientsmap[i].Nupdatemake = row.Localtime(res.Map("nupdate_make"))

			}

		}
	}

	return aclientsmap

}
Пример #2
0
func apiGet(s *mgo.Session, label string, todo string, mlog *syslog.Writer) string {
	if len(label) == 0 {
		return ""
	}

	list, err := dbQuery(s, label)
	if err != nil {
		mlog.Err("Error: db query went bad: " + err.Error())
		return "Error"
	}

	todos := make([]TodoItem, len(list))
	count := 0
	for i, todo := range list {
		todos[i].Text = todo.Text
		todos[i].Id = todo.Id.Hex()
		count += 1
	}
	jsonOut := struct {
		Label string
		Count int
		Todos []TodoItem
	}{label, count, todos}

	out, err := json.MarshalIndent(jsonOut, "", "  ")
	if err != nil {
		mlog.Err("Error: could not properly construct json")
		return "Error"
	}
	return string(out)
}
Пример #3
0
func GetSqlMainosTel(golog syslog.Writer, db sql.DB, sqlstr string) []domains.MainosTel {
	var result []domains.MainosTel

	rows, err := db.Query(sqlstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer rows.Close()

	for rows.Next() {

		var phone string
		var smstext string
		err := rows.Scan(&phone, &smstext)
		if err != nil {
			golog.Err(err.Error())
		}

		var mainostel domains.MainosTel

		if !strings.HasPrefix(phone, "09") && !strings.Contains(phone, "070057") {

			mainostel.Phone = phone
			mainostel.Text = smstext
			result = append(result, mainostel)

		}

	}
	return result
}
Пример #4
0
func apiCount(s *mgo.Session, mlog *syslog.Writer) string {
	itemCount, listCount, err := dbCountLists(s)
	var countOut struct {
		ItemCount int
		List      []struct {
			Label string
			Count int
		}
	}

	countOut.ItemCount = listCount
	countOut.List = make([]struct {
		Label string
		Count int
	}, len(itemCount))
	i := 0
	for k, v := range itemCount {
		countOut.List[i].Label = k
		countOut.List[i].Count = v
		i += 1
	}

	out, err := json.MarshalIndent(countOut, "", "  ")
	if err != nil {
		mlog.Err("Error: could not properly construct json")
		return "Error"
	}
	return string(out)
}
Пример #5
0
func xmlcheck(golog syslog.Writer, provider string, phone string, data []byte) {

	//	log.Println("GetUrl:xmlcheck check provider ", provider, "phone", phone)
	//
	//	<SmsResponse>
	//        <version>1</version>
	//        <result>1</result>
	//        <resultstring>success</resultstring>
	//        <description></description>
	//        <partcount>1</partcount>
	//        <endcause></endcause>
	//</SmsResponse>

	v := Dataxml{}
	err := xml.Unmarshal(data, &v)
	if err != nil {
		//		fmt.Printf("error: %v", err)
		golog.Err(err.Error())

		blockphone(phone)

	} else {

		//		fmt.Printf("Result: %q\n", v.Result)
		golog.Info(v.Result)

	}
}
Пример #6
0
func apiRemove(s *mgo.Session, label string, id string, mlog *syslog.Writer) string {
	if len(label) == 0 {
		return ""
	}

	err := dbRemove(s, label, MongoTodo{Id: bson.ObjectIdHex(id), Text: ""})
	if err != nil {
		mlog.Err("Error: db remove went bad: " + err.Error())
		return "Error"
	}
	return "Removing: " + id + " from: " + label
}
Пример #7
0
func apiAdd(s *mgo.Session, label string, todo string, mlog *syslog.Writer) string {
	if len(label) == 0 {
		return ""
	}

	newTodo := MongoTodo{Id: bson.NewObjectId(), Text: todo}
	err := dbInsert(s, label, newTodo)
	if err != nil {
		mlog.Err("Error: db insert went bad: " + err.Error())
		return "Error"
	}
	return newTodo.Id.Hex()
}
Пример #8
0
func GetLastMainos() {

	var golog syslog.Writer
	var config domains.Config

	confstr := config.Database.User + ":" + config.Database.Passwd + "@/" + config.Database.Database + "?parseTime=true"

	db, err := sql.Open("mysql", confstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer db.Close()

	sql2.GetSqlMainosTel(golog, *db, "select count(*) from calls where cdate>=curdate()")

}
Пример #9
0
func InsertSmsRecord(db autorc.Conn, sqlstr string, golog syslog.Writer) {

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {
		if _, _, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		}

	}

}
Пример #10
0
func UpdateAclient(golog syslog.Writer, db sql.DB, sqlstr string) {

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {

		if _, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		} else {

			golog.Info("Aclient updated")

		}

	}

}
Пример #11
0
func InsertMobileClient(golog syslog.Writer, db sql.DB, sqlstr string) {

	if stmt, err := db.Prepare(sqlstr); err != nil {

		golog.Err(err.Error())

	} else {

		if _, err := stmt.Exec(); err != nil {

			golog.Err(err.Error())

		} else {

			golog.Info("New Client arrived!!!")

		}

	}

}
Пример #12
0
func newSyslogAdapter(w *syslog.Writer) *LoggingAdapter {
	return &LoggingAdapter{
		Debugf: func(format string, v ...interface{}) { w.Debug(fmt.Sprintf(format, v...)) },
		Infof:  func(format string, v ...interface{}) { w.Info(fmt.Sprintf(format, v...)) },
		Warnf:  func(format string, v ...interface{}) { w.Warning(fmt.Sprintf(format, v...)) },
		Errorf: func(format string, v ...interface{}) { w.Err(fmt.Sprintf(format, v...)) },
		Fatalf: func(format string, v ...interface{}) {
			s := fmt.Sprintf(format, v...)

			w.Crit(s)

			os.Exit(1)
		},
		Panicf: func(format string, v ...interface{}) {
			s := fmt.Sprintf(format, v...)

			w.Emerg(s)

			panic(s)
		},
	}
}
Пример #13
0
func GetMobileClientId(golog syslog.Writer, db sql.DB, sqlstr string) int {

	var cliID int

	rows, err := db.Query(sqlstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer rows.Close()

	for rows.Next() {

		err := rows.Scan(&cliID)
		if err != nil {
			golog.Err(err.Error())
		}

	}

	return cliID

}
Пример #14
0
func GetSqlInt(golog syslog.Writer, db sql.DB, sqlstr string) int {

	var result int

	rows, err := db.Query(sqlstr)
	if err != nil {
		golog.Err(err.Error())
	}
	defer rows.Close()

	for rows.Next() {

		err := rows.Scan(&result)
		if err != nil {
			golog.Err(err.Error())
		}

	}

	return result

}
Пример #15
0
func GetUrl(golog syslog.Writer, provider string, phone string, urlstr string) {

	if res, err := http.Get(urlstr); err != nil {
		log.Fatalf("Get: %v", err)
		golog.Err(err.Error())
	} else {

		if data, err := ioutil.ReadAll(res.Body); err != nil {

			log.Fatalf("Get: %v", err)
			golog.Err(err.Error())

		} else {
			//			fmt.Printf("out %s", string(data))

			if provider == "voicetr" {

				xmlcheck(golog, provider, phone, data)

			}

		}
	}
}
Пример #16
0
func Gettasks(makeFlag string, quant int, golog syslog.Writer) {

	golog.Info("Start Gettasks")

	quantstr := strconv.Itoa(quant)

	if res, err := http.Get("http://latest.kannelgo.sinelgamysql.appspot.com/gettasks?makeflag=" + makeFlag + "&tasksquant=" + quantstr); err != nil {

		golog.Err(err.Error())

	} else {

		if data, err := ioutil.ReadAll(res.Body); err != nil {

			golog.Err(err.Error())

		} else {

			sliceforjson := make([]d.Smsout, 2)

			json.Unmarshal(data, &sliceforjson)

			var sendok bool
			for _, smsout := range sliceforjson {

				sendok = false
				golog.Info(smsout.Phoneto)
				golog.Info(smsout.Opcode)
				golog.Info(smsout.Nmake)

				sendok = checkaclient.CheckByPhone(smsout.Phoneto)

				if sendok {

					golog.Info("sendok OK makeFlag " + makeFlag)

					if makeFlag == "sms179019" {

						//					pr.SendSMSKannel(smsout)
						// for now elisa
						pr.SmsSendBy("elisa", smsout, golog)
						//					pr.SendSMSCgwSonera(smsout)
						//					pr.SendSMSSonera(smsout)

					} else if makeFlag == "gsm179019" {
						//					pr.SendSMSSonera(smsout)
						pr.SmsSendBy("sonera", smsout, golog)
						//					pr.SendSMSCgwSonera(smsout) //problems öä

					} else if makeFlag == "voicetr" {

						golog.Info("send by vocetr")
						pr.SmsSendBy("voicetr", smsout, golog)

					} else if makeFlag == "sms179029" {

						golog.Info("send by pullpull now DNA only")
						pr.SmsSendBy("pullpull", smsout, golog)

					}

					insertsmsins.InsertSmsRecord(smsout.Phoneto, smsout.Text, makeFlag, golog)

				} else {

					//					fmt.Println("Dont't send sms for "+smsout.Phoneto)
					golog.Warning("Dont't send sms for " + smsout.Phoneto)
				}
			}

		}
	}
}
Пример #17
0
func enqueue(syslogLog *syslog.Writer, mongoHref string, mongoDatabaseName string, mongoCollectionName string, amqpHref string, amqpExchange string, amqpExchangeType string, amqpQueue string) {

	//DEBUG
	syslogLog.Notice("[enqueue] BEGIN")
	syslogLog.Notice(fmt.Sprintf("    [enqueue]           mongoHref = [%v]", mongoHref))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]   mongoDatabaseName = [%v]", mongoDatabaseName))
	syslogLog.Notice(fmt.Sprintf("    [enqueue] mongoCollectionName = [%v]", mongoCollectionName))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]            amqpHref = [%v]", amqpHref))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]        amqpExchange = [%v]", amqpExchange))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]    amqpExchangeType = [%v]", amqpExchangeType))
	syslogLog.Notice(fmt.Sprintf("    [enqueue]           amqpQueue = [%v]", amqpQueue))

	// Deal with parameters.
	if "" == mongoHref {
		errMsg := fmt.Sprintf("    [enqueue] Bad mongoHref. Received: [%v].", mongoHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoDatabaseName {
		errMsg := fmt.Sprintf("    [enqueue] Bad mongoHref. Received: [%v].", mongoDatabaseName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoCollectionName {
		errMsg := fmt.Sprintf("    [enqueue] Bad mongoHref. Received: [%v].", mongoCollectionName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpHref {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpHref. Received: [%v].", amqpHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpExchange {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpExchange. Received: [%v].", amqpExchange)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpExchangeType {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpExchangeType. Received: [%v].", amqpExchangeType)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpQueue {
		errMsg := fmt.Sprintf("    [enqueue] Bad amqpQueue. Received: [%v].", amqpQueue)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	// Connect to AMQP.
	amqpConnection, err := amqp.Dial(amqpHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT connect to AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer amqpConnection.Close()

	amqpChannel, err := amqpConnection.Channel()
	if err != nil {
		syslogLog.Err("    [enqueue] Could NOT get AMQP channel")
		panic(err)
		/////////////////////// RETURN
		return
	}

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [enqueue] amqpChannel = [%v]", amqpChannel))

	// Connect to MongoDB
	mongoSession, err := mgo.Dial(mongoHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT connect to MongoDB at [%v], received err = [%v]", mongoHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer mongoSession.Close()

	// Optional. Switch the session to a monotonic behavior.
	mongoSession.SetMode(mgo.Monotonic, true)

	mongoCollection := mongoSession.DB(mongoDatabaseName).C(mongoCollectionName)

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [enqueue] Connected to MongoDB with %v.%v", mongoDatabaseName, mongoCollectionName))

	// AMQP queue bind.
	amqpKey := amqpQueue

	if err = amqpChannel.QueueBind(
		amqpQueue,    // name of the queue
		amqpKey,      // bindingKey
		amqpExchange, // sourceExchange
		false,        // noWait
		nil,          // arguments
	); err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT bind to queue [%v] on AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpQueue, amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}

	//DEBUG
	syslogLog.Notice("    [enqueue] Queue bound.")

	// Set up AMQP consumer.
	amqpDeliveries, err := amqpChannel.Consume(
		amqpQueue,  // name
		"turtledq", // consumerTag
		false,      // noAck
		false,      // exclusive
		false,      // noLocal
		false,      // noWait
		nil,        // arguments
	)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [enqueue] Could NOT get deliverables from queue [%v] on AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpQueue, amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}

	// Forever
	for d := range amqpDeliveries {

		//DEBUG
		syslogLog.Notice("        [enqueue] =-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-= LOOP")
		syslogLog.Notice(fmt.Sprintf("        [enqueue] got %dB message: [%v]", len(d.Body), d.DeliveryTag))
		syslogLog.Notice(fmt.Sprintf("        [enqueue] THING: [%v]", d))

		sjson, err := simplejson.NewJson(d.Body)
		if nil != err {
			//DEBUG
			syslogLog.Err(fmt.Sprintf("        [enqueue] Could NOT parse raw JSON: [%v]", d.Body))
			//@TODO ##################################################################################################################
		}

		//DEBUG
		syslogLog.Notice(fmt.Sprintf("        [enqueue] json = [%#v]", sjson))

		haveTarget := true
		messageTarget, err := sjson.Get("target").String()
		if nil != err {
			haveTarget = false
		}

		//DEBUG
		if haveTarget {
			syslogLog.Notice(fmt.Sprintf("        [enqueue] target = [%v]", messageTarget))
		} else {
			syslogLog.Notice("        [enqueue] either do NOT have messageTarget (or did not receive a \"good\" one)")
		}

		haveWhen := true
		messageWhen, err := sjson.Get("when").Int64()
		if nil != err {
			haveWhen = false
		}

		//DEBUG
		if haveWhen {
			syslogLog.Notice(fmt.Sprintf("        [enqueue] when = [%v]", messageWhen))
		} else {
			syslogLog.Notice("        [enqueue] either do NOT have messageTarget (or did not receive a \"good\" one)")
		}

		haveMessage := true
		messageMessage, err := sjson.Get("message").Map()
		if nil != err {
			haveMessage = false
		}

		//DEBUG
		if haveMessage {
			syslogLog.Notice(fmt.Sprintf("        [enqueue] message = [%v]", messageMessage))
		} else {
			syslogLog.Notice("        [enqueue] either do NOT have messageMessage (or did not receive a \"good\" one)")
		}

		// Deal with corrupted items.
		if !haveTarget || !haveWhen || !haveMessage {

			//DEBUG
			syslogLog.Notice("        [enqueue] Empty item from AMQP queue. Will ACK early and continue.")

			// Ack.
			err = d.Ack(false)
			if nil != err {
				syslogLog.Err(fmt.Sprintf("        [enqueue] ERROR EARLY ACKing: [%v]", err))
			}

			//DEBUG
			syslogLog.Notice("        [enqueue] EARLY ACKed")

			/////////////////////// CONTINUE
			continue
		}

		// Enqueue the item
		mongoDoc := bson.M{
			"target":  messageTarget,
			"when":    time.Unix(messageWhen, 0),
			"message": messageMessage}

		err = mongoCollection.Insert(mongoDoc)
		if nil != err {
			syslogLog.Err(fmt.Sprintf("        [enqueue] ERROR Inserting into Mongo: [%v]", err))
			//@TODO ###############################################################################################
		}

		syslogLog.Notice(fmt.Sprintf("        [enqueue] Inserted into Mongo: [%v]", mongoDoc))

		// Ack.
		err = d.Ack(false)
		if nil != err {
			syslogLog.Err(fmt.Sprintf("        [enqueue] ERROR ACKing: [%v]", err))
		}

		//DEBUG
		syslogLog.Notice("        [enqueue] ACKed")

		//			sleepTime := time.Duration(5 + rand.Intn(7)) * time.Second
		//
		//			//DEBUG
		//			syslogLog.Notice( fmt.Sprintf("    [enqueue] sleep for %v", sleepTime) )
		//
		//			time.Sleep(sleepTime)
	} // for

	//DEBUG
	syslogLog.Notice("[enqueue] END")

}
Пример #18
0
func dequeue(syslogLog *syslog.Writer, mongoHref string, mongoDatabaseName string, mongoCollectionName string, amqpHref string, amqpExchange string, amqpExchangeType string) {

	//DEBUG
	syslogLog.Notice("[dequeue] BEGIN")
	syslogLog.Notice(fmt.Sprintf("    [dequeue]           mongoHref = [%v]", mongoHref))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]   mongoDatabaseName = [%v]", mongoDatabaseName))
	syslogLog.Notice(fmt.Sprintf("    [dequeue] mongoCollectionName = [%v]", mongoCollectionName))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]            amqpHref = [%v]", amqpHref))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]        amqpExchange = [%v]", amqpExchange))
	syslogLog.Notice(fmt.Sprintf("    [dequeue]    amqpExchangeType = [%v]", amqpExchangeType))

	// Deal with parameters.
	if "" == mongoHref {
		errMsg := fmt.Sprintf("    [dequeue] Bad mongoHref. Received: [%v].", mongoHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoDatabaseName {
		errMsg := fmt.Sprintf("    [dequeue] Bad mongoDatabaseName. Received: [%v].", mongoDatabaseName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == mongoCollectionName {
		errMsg := fmt.Sprintf("    [dequeue] Bad mongoCollectionName. Received: [%v].", mongoCollectionName)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	if "" == amqpHref {
		errMsg := fmt.Sprintf("    [dequeue] Bad amqpHref. Received: [%v].", amqpHref)
		syslogLog.Err(errMsg)
		panic(errMsg)
		/////////////////////// RETURN
		return
	}

	// Connect to MongoDB
	mongoSession, err := mgo.Dial(mongoHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [dequeue] Could NOT connect to MongoDB at [%v], received err = [%v]", mongoHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer mongoSession.Close()

	// Optional. Switch the session to a monotonic behavior.
	mongoSession.SetMode(mgo.Monotonic, true)

	mongoCollection := mongoSession.DB(mongoDatabaseName).C(mongoCollectionName)

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [dequeue] Connected to MongoDB with %v.%v", mongoDatabaseName, mongoCollectionName))

	// Connect to AMQP.
	amqpConnection, err := amqp.Dial(amqpHref)
	if err != nil {
		syslogLog.Err(fmt.Sprintf("    [dequeue] Could NOT connect to AMQP server (RabbitMQ?) at [%v], received err = [%v]", amqpHref, err))
		panic(err)
		/////////////////////// RETURN
		return
	}
	defer amqpConnection.Close()

	amqpChannel, err := amqpConnection.Channel()
	if err != nil {
		syslogLog.Err("    [dequeue] Could NOT get AMQP channel")
		panic(err)
		/////////////////////// RETURN
		return
	}

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [dequeue] amqpChannel = [%v]", amqpChannel))

	//DEBUG
	syslogLog.Notice(fmt.Sprintf("    [dequeue] Connected to AMQP server (RabbitMQ?)", mongoDatabaseName, mongoCollectionName))

	// Forever
	for {

		//DEBUG
		syslogLog.Notice("    [dequeue] =-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-=-<>-= LOOP")

		// Check MongoDB for items that are ready.
		mongoCriteria := bson.M{"when": bson.M{"$lte": bson.Now()}}

		mongoQuery := mongoCollection.Find(mongoCriteria)

		//DEBUG
		syslogLog.Notice(fmt.Sprintf("    [dequeue] mongoQuery = [%v]", mongoQuery))

		if nil != err {
			syslogLog.Err(fmt.Sprintf("    [dequeue] Error querying MongoDB with mongoCriteria = [%v] received err = [%v]", mongoCriteria, err))
		} else {

			syslogLog.Notice(fmt.Sprintf("    [dequeue] Success querying MongoDB with mongoCriteria = [%v]", mongoCriteria, err))

			//					var x struct{
			//						_Id    bson.ObjectId
			//						When   time.Time
			//						Target string
			//						Message map[string]interface{}
			//					}

			x := map[string]interface{}{}

			items := mongoQuery.Iter()
			for items.Next(&x) {

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Received row: [%v]", x))

				//						routingKey := x.Target
				routingKey := x["target"].(string)

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Routing Key : [%v]", routingKey))

				//						body, err := json.Marshal(x.Message)
				body, err := json.Marshal(x["message"])
				if nil != err {
					//DEBUG
					syslogLog.Err(fmt.Sprintf("        [dequeue] Error serializing body into JSON, received err = [%v]", err))
					//@TODO #############################################################################

				}

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Body : [%v]", body))

				//DEBUG
				syslogLog.Notice(fmt.Sprintf("        [dequeue] Routing key: [%v]", routingKey))
				syslogLog.Notice(fmt.Sprintf("        [dequeue] declared Exchange, publishing %dB body (%s)", len(body), body))

				if err = amqpChannel.Publish(
					amqpExchange, // publish to an exchange
					routingKey,   // routing to 0 or more queues
					false,        // mandatory
					false,        // immediate
					amqp.Publishing{
						Headers:         amqp.Table{},
						ContentType:     "text/plain",
						ContentEncoding: "",
						Body:            body,
						DeliveryMode:    amqp.Transient, // 1=non-persistent, 2=persistent
						Priority:        0,              // 0-9
						// a bunch of application/implementation-specific fields
					},
				); err != nil {

					//DEBUG
					syslogLog.Err(fmt.Sprintf("        [dequeue] Error: Exchange Publish: [%v]", err))
				} else {

					//DEBUG
					syslogLog.Err("        [dequeue] Published")
				}

				// Delete from MongoDB.
				//							err = mongoCollection.RemoveId(x._Id)
				err = mongoCollection.RemoveId(x["_id"])
				if nil != err {
					//DEBUG
					//								syslogLog.Err(  fmt.Sprintf("        [dequeue] Could NOT remove item from Mongo with _id [%v], received err = [%v]", x._Id, err)  )
					syslogLog.Err(fmt.Sprintf("        [dequeue] Could NOT remove item from Mongo with _id [%v], received err = [%v]", x["_id"], err))
				} else {
					//DEBUG
					//								syslogLog.Notice(  fmt.Sprintf("        [dequeue] Removed item from Mongo with _id [%v]", x._Id)  )
					syslogLog.Notice(fmt.Sprintf("        [dequeue] Removed item from Mongo with _id [%v]", x["_id"]))
				}

			} // for

			syslogLog.Notice("    [dequeue] Done iterating through result of query.")
		}

		// Sleep for a while before checking again.
		sleepTime := time.Duration(5+rand.Intn(7)) * time.Second

		//DEBUG
		syslogLog.Notice(fmt.Sprintf("    [dequeue] sleep for %v", sleepTime))

		time.Sleep(sleepTime)
	} // for

	//DEBUG
	syslogLog.Notice("[dequeue] END")

}
Пример #19
0
func Settasks(makeFlag string, days int, quant int, golog syslog.Writer) {

	quantstr := strconv.Itoa(quant)
	daysstr := strconv.Itoa(days)

	var sqlselectstr string

	if makeFlag == "gsm179019" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (50,54,56,49,79,'na') and nupdate_make <=adddate(now(), -" + daysstr + ") and rating>5) or (nmake IS NULL and block = 0 and opcode in (50,54,56,49,79,'na')) order by id desc limit " + quantstr
	}
	if makeFlag == "voicetr" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (50,54,56,49,79,'na') and nupdate_make <=adddate(now(), -" + daysstr + ")) or (nmake IS NULL and block = 0 and opcode in (50,54,56,49,79,'na')) order by id desc limit " + quantstr
	}
	if makeFlag == "sms179019" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (50,54,56,49,79,'na') and nupdate_make <=adddate(now(), -" + daysstr + ") and smsquant>1) or (nmake IS NULL and block = 0 and opcode in (50,54,56,49,79,'na')) order by id desc limit " + quantstr
	}

	if makeFlag == "sms179029" {
		sqlselectstr = "select * from aclients where (block = 0 and sulje = 0 and ennu = 0 and nmake <> '" + makeFlag + "' and opcode in (54) and nupdate_make <=adddate(now(), -" + daysstr + ") ) or (nmake IS NULL and block = 0 and opcode in (54)) order by id desc limit " + quantstr
	}

	db.Raw.Register("SET NAMES utf8")
	var aclienmap = sql.GetMapAclients(*db, sqlselectstr, makeFlag, golog)

	golog.Info("Ready Settask for " + strconv.Itoa(len(aclienmap)))

	if aclientupdate_stmt, err := db.Prepare("update aclients set nmake = ?,nupdate_make = now() where id = ?"); err != nil {

		golog.Err(err.Error())

	} else {

		for _, Aclient := range aclienmap {

			fmt.Println(Aclient.Phone)
			fmt.Println(Aclient.Opcode)
			fmt.Println(Aclient.Nmake)
			fmt.Println("---------")

			if _, _, err := aclientupdate_stmt.Exec(makeFlag, Aclient.Id); err != nil {
				golog.Err(err.Error())
			}

		}

		jsbyte, _ := json.Marshal(aclienmap)

		buff := bytes.NewBuffer(jsbyte)

		client := &http.Client{}

		if req, err := http.NewRequest("POST", "http://latest.kannelgo.sinelgamysql.appspot.com/settasks", buff); err != nil {

			fmt.Printf("Error: %v\n", err)

		} else {

			req.Header.Add("makeFlag", makeFlag)

			if resp, err1 := client.Do(req); err1 != nil {
				fmt.Printf("Error: %v\n", err1)
			} else {
				defer resp.Body.Close()
				body, _ := ioutil.ReadAll(resp.Body)
				fmt.Println("Body: %s\n", body)
			}

		}

	}

}