Example #1
0
func CreateCard(notif me.NotifModel, ts int) string {
	db.CardCounter += 1
	cardId := strconv.Itoa(db.CardCounter)
	db.Card[cardId] = me.CardModel{cardId, notif.Id, ts, false}
	if owner, ok := db.User[notif.OwnerId]; ok {
		if client, okk := db.User[notif.ClientId]; okk {
			owner.CardIds = append(owner.CardIds, cardId)
			db.User[notif.OwnerId] = owner

			data := map[string]interface{}{"title": notif.Name, "id": cardId}
			regIDs := []string{client.RegId}
			msg := gcm.NewMessage(data, regIDs...)

			// Create a Sender to send the message.
			sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}

			// Send the message and receive the response after at most two retries.
			_, err := sender.Send(msg, 2)
			if err != nil {
				fmt.Println("Failed to send message: %v", err)
			} else {
				fmt.Println("Message is sent.")
			}

			return cardId
		}
	}
	return ""
}
Example #2
0
func sendAndroidNotification(msg *PushNotification) {
	var data map[string]interface{}
	if msg.Type == PUSH_TYPE_CLEAR {
		data = map[string]interface{}{"type": PUSH_TYPE_CLEAR, "channel_id": msg.ChannelId, "team_id": msg.TeamId}
	} else {
		data = map[string]interface{}{"type": PUSH_TYPE_MESSAGE, "message": emoji.Sprint(msg.Message), "channel_id": msg.ChannelId, "channel_name": msg.ChannelName, "team_id": msg.TeamId}
	}

	regIDs := []string{msg.DeviceId}
	gcmMsg := gcm.NewMessage(data, regIDs...)

	sender := &gcm.Sender{ApiKey: CfgPP.AndroidApiKey}

	if len(CfgPP.AndroidApiKey) > 0 {
		LogInfo("Sending android push notification")
		resp, err := sender.Send(gcmMsg, 2)

		if err != nil {
			LogError(fmt.Sprintf("Failed to send GCM push sid=%v did=%v err=%v", msg.ServerId, msg.DeviceId, err))
			return
		}

		if resp.Failure > 0 {
			LogError(fmt.Sprintf("Android response failure: %v", resp))
		}
	}
}
Example #3
0
func (gcmConnector *GCMConnector) sendMessageToGCM(msg server.MsgAndRoute) {
	gcmId := msg.Route.ApplicationId

	payload := gcmConnector.parseMessageToMap(msg.Message)

	var messageToGcm = gcm.NewMessage(payload, gcmId)
	guble.Info("sending message to %v ...", gcmId)
	result, err := gcmConnector.sender.Send(messageToGcm, 5)
	if err != nil {
		guble.Err("error sending message to cgmid=%v: %v", gcmId, err.Error())
		return
	}

	errorJson := result.Results[0].Error
	if errorJson != "" {
		gcmConnector.handleJsonError(errorJson, gcmId, msg.Route)
	} else {
		guble.Debug("delivered message to gcm cgmid=%v: %v", gcmId, errorJson)
	}

	//we only send to one receiver, so we know that we can replace the old id with the first registration id (=canonical id)
	if result.CanonicalIDs != 0 {
		gcmConnector.replaceSubscriptionWithCanonicalID(msg.Route, result.Results[0].RegistrationID)
	}
}
Example #4
0
/* Mark the card as completed and
   Send a notification to the owner of the card
*/
func Done(c *gin.Context) {
	cardId := c.Param("card_id")

	if card, ok := db.Card[cardId]; ok {
		card.Completed = true
		db.Card[cardId] = card
		if notif, okk := db.Notif[card.NotifId]; okk {
			if user, okkk := db.User[notif.OwnerId]; okkk {
				data := map[string]interface{}{"title": notif.Name + " is done.", "id": cardId}
				regIDs := []string{user.RegId}
				msg := gcm.NewMessage(data, regIDs...)

				// Create a Sender to send the message.
				sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}

				// Send the message and receive the response after at most two retries.
				_, err := sender.Send(msg, 2)
				if err != nil {
					c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to send message: %v", err))
				} else {
					c.String(http.StatusOK, "Message is sent.")
				}
			}
		}
	} else {
		c.String(http.StatusNotFound, "")
	}
}
Example #5
0
func (gcmConnector *GCMConnector) broadcastMessage(msg server.MsgAndRoute) {
	topic := msg.Message.Path
	payload := gcmConnector.parseMessageToMap(msg.Message)
	guble.Info("broadcasting message with topic %v ...", string(topic))

	subscriptions := gcmConnector.kvStore.Iterate(GCM_REGISTRATIONS_SCHEMA, "")
	count := 0
	for {
		select {
		case entry, ok := <-subscriptions:
			if !ok {
				guble.Info("send message to %v receivers", count)
				return
			}
			gcmId := entry[0]
			//TODO collect 1000 gcmIds and send them in one request!
			broadcastMessage := gcm.NewMessage(payload, gcmId)
			go func() {
				//TODO error handling of response!
				_, err := gcmConnector.sender.Send(broadcastMessage, 3)
				guble.Debug("sent broadcast message to gcmId=%v", gcmId)
				if err != nil {
					guble.Err("error sending broadcast message to cgmid=%v: %v", gcmId, err.Error())
				}
			}()
			count++
		}
	}
}
Example #6
0
func notify(meeting Meeting, status int) {

	data := map[string]interface{}{
		"action":       "meeting_started",
		"meeting_id":   meeting.Id.Hex(),
		"meeting_goal": meeting.Goal,
	}

	devices := devices(meeting)
	msg := gcm.NewMessage(data, devices...)

	cfg := config.Section("gcm")

	apikey := cfg.Key("apikey").String()

	sender := &gcm.Sender{ApiKey: apikey}

	_, err := sender.Send(msg, cfg.Key("retries").MustInt(3))

	if err != nil {
		log.Fatal("Failed to send message:", err)
	} else {
		log.Print(len(devices), " devices notified that ", meeting.String(), " changed to ", status)
	}
}
func NotifyUsers(deviceTokens []string) error {
	sender := &gcm.Sender{ApiKey: "AIzaSyBEHLA1FR4OlCRQE1vPv_mfqQaIF0ICZeA"}
	message := gcm.NewMessage(nil, deviceTokens...)
	_, err := sender.Send(message, 2)
	fmt.Println("Successfully sent a notification to device token : ", deviceTokens)
	if err != nil {
		return fmt.Errorf("Error sending notifications: %s", err)
	}
	return nil
}
Example #8
0
func (n *Notification) Send() (errList Notification, err error) {
	// GCM
	apnTask := make(chan bool)
	gcmTask := make(chan bool)
	var (
		apnWG sync.WaitGroup
		gcmWG sync.WaitGroup
	)
	go func() { // parallel between APN and GCM
		// APN
		p := apns.NewPayload()
		p.APS.Alert.Body = n.Message
		p.APS.ContentAvailable = 1
		m := apns.NewNotification()
		m.Payload = p
		m.Priority = apns.PriorityImmediate
		apnWG.Add(len(n.APNReceivers))
		for _, v := range APNReceivers {
			go func() {
				m.DeviceToken = v
				apnClient.Send(m)
				apnWG.Done()
			}() // parallel for APN
		}
		// HERE err handling for APN
		go func() {
			for _, f := range apnClient.FailedNotifs {
				errList.APNReceivers = append(errList.APNReceivers, f.Notif.ID)
			}
		}()
		apnWG.Wait()
		apnTask <- true
	}()
	// GCM
	go func() {
		gcmWG.Add(len(n.GCMReceivers))
		data := map[string]interface{}{"message": n.Message}
		for _, v := range GCMReceivers() {
			go func() {
				d := gcm.NewMessage(data, v)
				_, err := gcmClient.Send(d, 0)
				if err != nil {
					errList.GCMReceivers = append(errList.GCMReceivers, v)
				}
				gcmWG.Done()
			}()
		}
		gcmWG.Wait()
		gcmTask <- true
	}()
	<-apnTask
	<-gcmTask
	return
}
Example #9
0
File: gcm.go Project: worg/go
// Send Push
func (self *Gcm) Send() (interface{}, error) {
	msg := gcm.NewMessage(self.Data, self.RegIds...)
	// Create a Sender to send the message.
	sender := &gcm.Sender{ApiKey: APIKEY}
	// Send the message and receive the response after at most two retries.
	response, err := sender.Send(msg, 2)
	if err != nil {
		return response, err
	}
	return response, nil
}
Example #10
0
// Check returns nil if health-check succeeds, or an error if health-check fails
// by sending a request with only apikey. If the response is processed by the GCM endpoint
// the gcmStatus will be UP, otherwise the error from sending the message will be returned.
func (conn *GCMConnector) Check() error {
	payload := conn.parseMessageToMap(&protocol.Message{Body: []byte(`{"registration_ids":["ABC"]}`)})
	_, err := conn.Sender.Send(gcm.NewMessage(payload, ""), sendRetries)
	if err != nil {

		log.WithFields(log.Fields{
			"module": "GCM",
			"err":    err,
		}).Error("Error sending ping message")

		return err
	}
	return nil
}
Example #11
0
func gcmNotify(att string, msg string, errHandle *[]string, wg *sync.WaitGroup) (status bool) {
	status = true
	d := map[string]interface{}{"message": msg}
	sender := &gcm.Sender{ApiKey: gcmauth}
	data := gcm.NewMessage(d, att)
	_, err := sender.Send(data, 0)
	if err != nil {
		status = false
	}
	wg.Done()
	if status == false {
		*errHandle = append(*errHandle, att)
	}
	return
}
Example #12
0
func pushNotificationAndroid(req RequestGaurunNotification) bool {
	LogError.Debug("START push notification for Android")

	data := map[string]interface{}{"message": req.Message}
	if len(req.Extend) > 0 {
		for _, extend := range req.Extend {
			data[extend.Key] = extend.Value
		}
	}

	msg := gcm.NewMessage(data, req.Tokens...)
	msg.CollapseKey = req.CollapseKey
	msg.DelayWhileIdle = req.DelayWhileIdle
	msg.TimeToLive = req.TimeToLive

	stime := time.Now()
	resp, err := GCMClient.SendNoRetry(msg)
	etime := time.Now()
	ptime := etime.Sub(stime).Seconds()
	if err != nil {
		atomic.AddInt64(&StatGaurun.Android.PushError, 1)
		for i, token := range req.Tokens {
			LogPush(req.IDs[i], StatusFailedPush, token, ptime, req, err)
		}
		return false
	}

	if resp.Failure > 0 {
		atomic.AddInt64(&StatGaurun.Android.PushSuccess, int64(resp.Success))
		atomic.AddInt64(&StatGaurun.Android.PushError, int64(resp.Failure))
		if len(resp.Results) == len(req.Tokens) {
			for i, token := range req.Tokens {
				if resp.Results[i].Error != "" {
					LogPush(req.IDs[i], StatusFailedPush, token, ptime, req, errors.New(resp.Results[i].Error))
				}
			}
		}
		return true
	}

	for i, token := range req.Tokens {
		LogPush(req.IDs[i], StatusSucceededPush, token, ptime, req, nil)
	}
	StatGaurun.Android.PushSuccess += int64(len(req.Tokens))
	LogError.Debug("END push notification for Android")
	return true
}
Example #13
0
func (conn *GCMConnector) broadcastMessage(msg *server.MessageForRoute) {
	topic := msg.Message.Path
	payload := conn.parseMessageToMap(msg.Message)
	log.WithFields(log.Fields{
		"module":         "GCM",
		"topic":          string(topic),
		"channel_length": len(conn.routerC),
	}).Debug("Broadcasting message with ")

	subscriptions := conn.kvStore.Iterate(registrationsSchema, "")
	count := 0
	for {
		select {
		case entry, ok := <-subscriptions:
			if !ok {
				log.WithFields(log.Fields{
					"module":          "GCM",
					"receivers_count": count,
				}).Info("Sent to message to ")
				return
			}
			gcmID := entry[0]
			//TODO collect 1000 gcmIds and send them in one request!
			broadcastMessage := gcm.NewMessage(payload, gcmID)
			go func() {
				//TODO error handling of response!
				_, err := conn.Sender.Send(broadcastMessage, broadcastRetries)
				log.WithFields(log.Fields{
					"module": "GCM",
					"gcmID":  gcmID,
				}).Debug("Sent broadcast message to")
				if err != nil {

					log.WithFields(log.Fields{
						"module": "GCM",
						"gmcId":  gcmID,
						"err":    err,
					}).Error("Error sending broadcast message to")
				}
			}()
			count++
		}
	}
}
Example #14
0
func (this *CommandMsg) pushAndroid(server *Server) {
	registration_ids, registration_ids_ok := this.Command["registration_ids"]

	if !registration_ids_ok {
		log.Println("Registration ID(s) not provided!")
		return
	}

	msg, err := this.formatMessage()
	if err != nil {
		log.Println("Could not format message")
		return
	}

	data := map[string]interface{}{"event": msg.Event, "data": msg.Data, "time": msg.Time}

	regIDs := strings.Split(registration_ids, ",")
	gcmMessage := gcm.NewMessage(data, regIDs...)

	sender := server.GetGCMClient()

	server.Stats.LogGCMPush()
	gcmResponse, gcmErr := sender.Send(gcmMessage, 2)
	if gcmErr != nil {
		server.Stats.LogGCMError()
		log.Printf("Error (Android): %s\n", gcmErr)
		return
	}

	if gcmResponse.Failure > 0 {
		server.Stats.LogGCMFailure()
		if !server.Config.GetBool("redis_enabled") {
			log.Println("Could not push to android_error_queue since redis is not enabled")
			return
		}

		failurePayload := map[string]interface{}{"registration_ids": regIDs, "results": gcmResponse.Results}

		msg_str, _ := json.Marshal(failurePayload)
		server.Store.redis.Push(server.Config.Get("android_error_queue"), string(msg_str))
	}
}
Example #15
0
func CreateNotif(card me.CardModel, ts int) {
	if notif, ok := db.Notif[card.NotifId]; ok {
		if client, okk := db.User[notif.ClientId]; okk {
			data := map[string]interface{}{"title": notif.Name, "id": card.Id}
			regIDs := []string{client.RegId}
			msg := gcm.NewMessage(data, regIDs...)

			// Create a Sender to send the message.
			sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}

			// Send the message and receive the response after at most two retries.
			_, err := sender.Send(msg, 2)
			if err != nil {
				fmt.Println("Failed to send message: %v", err)
			} else {
				fmt.Println("Message is sent.")
			}
		}
	}
}
Example #16
0
func (conn *GCMConnector) sendMessage(msg *server.MessageForRoute) {
	gcmID := msg.Route.ApplicationID

	payload := conn.parseMessageToMap(msg.Message)

	var messageToGcm = gcm.NewMessage(payload, gcmID)

	log.WithFields(log.Fields{
		"module":         "GCM",
		"gcmID":          gcmID,
		"channel_length": len(conn.routerC),
	}).Debug("Sending message to ")

	result, err := conn.Sender.Send(messageToGcm, sendRetries)
	if err != nil {
		log.WithFields(log.Fields{
			"module": "GCM",
			"gcmID":  gcmID,
			"err":    err,
		}).Error("Error sending message to")

		return
	}

	errorJSON := result.Results[0].Error
	if errorJSON != "" {
		conn.handleJSONError(errorJSON, gcmID, msg.Route)
	} else {
		log.WithFields(log.Fields{
			"module":    "GCM",
			"gcmID":     gcmID,
			"errorJSON": errorJSON,
		}).Debug("Delivered message to ")
	}

	// we only send to one receiver,
	// so we know that we can replace the old id with the first registration id (=canonical id)
	if result.CanonicalIDs != 0 {
		conn.replaceSubscriptionWithCanonicalID(msg.Route, result.Results[0].RegistrationID)
	}
}
Example #17
0
func PushIt(w http.ResponseWriter, r *http.Request) error {
	c := appengine.NewContext(r)
	req := &FormData{}
	json.NewDecoder(r.Body).Decode(&req)

	client := urlfetch.Client(c)
	sender := &gcm.Sender{ApiKey: req.APIKey, Http: client}

	// Create the message to be sent.
	data := map[string]interface{}{"data": req.Message}
	regIDs := []string{req.RegId}
	msg := gcm.NewMessage(data, regIDs...)

	// Send the message and receive the response after at most two retries.
	_, err := sender.Send(msg, 2)
	if err != nil {
		result := &Result{Message: "Failed to send message: " + err.Error()}
		return json.NewEncoder(w).Encode(result)
	}
	result := &Result{Message: "Successfully sent"}
	return json.NewEncoder(w).Encode(result)
}
Example #18
0
func pushNotificationAndroid(req gaurun.RequestGaurunNotification) bool {
	data := map[string]interface{}{"message": req.Message}
	msg := gcm.NewMessage(data, req.Tokens...)
	msg.CollapseKey = req.CollapseKey
	msg.DelayWhileIdle = req.DelayWhileIdle
	msg.TimeToLive = req.TimeToLive

	sender := &gcm.Sender{ApiKey: gaurun.ConfGaurun.Android.ApiKey}
	sender.Http = new(http.Client)
	sender.Http.Timeout = time.Duration(gaurun.ConfGaurun.Android.Timeout) * time.Second

	resp, err := sender.SendNoRetry(msg)
	if err != nil {
		return false
	}

	if resp.Failure > 0 {
		return true
	}

	return true
}
Example #19
0
func (this *Sender) send(users []auth.User, vote storage.Vote) {
	funcPrefix := "Sending notifications"
	log.Debug.Printf("%s: start\n", funcPrefix)
	defer log.Debug.Printf("%s: end\n", funcPrefix)

	var devices Devices

	log.Debug.Printf("%s: getting DevIds from users...\n", funcPrefix)
	for i := range users {
		log.Debug.Printf("%s: getting DevId from user %+v...\n", funcPrefix, users[i])
		switch users[i].Device {
		case DEVICE_IOS:
			devices.AppleIds = append(devices.AppleIds, users[i].DevId)
		case DEVICE_ANDROID:
			devices.GoogleIds = append(devices.GoogleIds, users[i].DevId)
		default:
			devices.OtherUsers = append(devices.OtherUsers, users[i])
		}
	}

	if len(devices.GoogleIds) > 0 {
		log.Debug.Printf("%s: trying to send Google device notifications to %v\n", funcPrefix, devices.GoogleIds)
		data := map[string]interface{}{"date": strconv.FormatInt(vote.Date, 10), "id": string(vote.Id), "name": string(vote.Name), "owner": string(vote.Owner), "voted": strconv.FormatBool(vote.Voted)}
		msg := gcm.NewMessage(data, devices.GoogleIds...)
		sender := &gcm.Sender{ApiKey: this.GoogleApiKey}
		_, err := sender.Send(msg, 2)
		if err != nil {
			log.Error.Printf("%s: sending notification to Google device failed: %s\n", funcPrefix, err.Error())
		}
	}

	if len(devices.AppleIds) > 0 {
		log.Debug.Printf("%s: Apple notification Server: %s, Cert: %s, Key: %s\n", funcPrefix, this.AppleServer, this.AppleCertPath, this.AppleKeyPath)
		apn, err := apns.NewClient(this.AppleServer, this.AppleCertPath, this.AppleKeyPath)
		apn.MAX_PAYLOAD_SIZE = 2048
		if err != nil {
			log.Error.Printf("%s: sending notification to Apple device failed: %s\n", funcPrefix, err.Error())
		} else {
			payload := &ApplePayload{}
			payload.Aps.Alert = vote.Name
			payload.Aps.Title = "MOC Pulse"
			payload.Aps.Category = "newVote"
			payload.Aps.Vote = vote
			actions := &SimulatorAction{}
			actions.Title = "Vote"
			actions.Identifier = "voteButtonAction"
			payload.SimulatorActions = append(payload.SimulatorActions, *actions)
			bytes, _ := json.Marshal(payload)
			log.Debug.Printf("%s: Apple notification payload: %v\n", funcPrefix, string(bytes))
			for i := range devices.AppleIds {
				log.Debug.Printf("%s: trying to send Apple device notification to %v\n", funcPrefix, devices.AppleIds[i])
				err = apn.SendPayloadString(devices.AppleIds[i], bytes, 5)
				if err != nil {
					log.Error.Printf("%s: sending notification to Apple device failed: %s\n", funcPrefix, err.Error())
				}
			}
		}
	}

	if len(devices.OtherUsers) > 0 {
		mandrill.Key = this.MandrillKey
		err := mandrill.Ping()
		if err != nil {
			log.Error.Printf("%s: sending notification to Email failed: %s\n", funcPrefix, err.Error())
		} else {
			data := make(map[string]string)
			data["QUESTION"] = vote.Name
			data["VOTE"] = vote.Id
			for i := range devices.OtherUsers {
				data["TOKEN"] = devices.OtherUsers[i].Id
				log.Debug.Printf("%s: trying to send Email notification to %v\n", funcPrefix, devices.OtherUsers[i].Email)
				msg := mandrill.NewMessageTo(devices.OtherUsers[i].Email, devices.OtherUsers[i].FirstName+devices.OtherUsers[i].LastName)
				msg.Subject = this.MandrillSubject
				msg.FromEmail = this.MandrillFromEmail
				msg.FromName = this.MandrillFromName
				_, err := msg.SendTemplate(this.MandrillTemplate, data, false)
				if err != nil {
					log.Error.Printf("%s: sending notification to Email failed: %s\n", funcPrefix, err.Error())
				}
			}
		}
	}
}
Example #20
0
func sendMessageToGCM(tokens []string, payload map[string]interface{}) (bool, error) {
	// At any exit, decrement pending
	defer func() {
		go decrementPending()
	}()

	if len(tokens) == 0 {
		errText := "No tokens were supplied, exiting"
		log.Println(errText)
		return false, errors.New(errText)
	}

	// if payloadAsString == "" {
	// 	errText := "Payload was empty, exiting"
	// 	log.Println(errText)
	// 	return false, errors.New(errText)
	// }

	// Unpack the JSON payload
	// var payload map[string]interface{}
	// err := json.Unmarshal([]byte(payloadAsString), &payload)
	// if err != nil {
	// 	log.Println("Can't unmarshal the json: " + err.Error())
	// 	log.Println("Original: " + payloadAsString)
	// 	return false, err
	// }

	// All is well, make & send the message
	go appendAttempts(len(tokens))

	msg := gcm.NewMessage(payload, tokens...)
	sender := &gcm.Sender{ApiKey: settings.GCMAPIKey}
	response, err := sender.Send(msg, 2)
	if err != nil {
		log.Println("Failed to send message:")
		log.Println(err.Error())

		go appendFailures(1)
		return false, err
	}

	numCan := 0
	numErr := 0
	if response != nil {
		for i, result := range response.Results {
			// Canonicals
			if result.RegistrationID != "" {
				numCan++
				canonicalReplacements = append(canonicalReplacements, canonicalReplacement{tokens[i], result.RegistrationID})
			}
			if result.Error != "" {
				numErr++
				log.Printf("Error sending: %s", result.Error)

				if result.Error == "NotRegistered" {
					handleNotRegisteredError(tokens[i])
					go appendNotRegistered(1)
				}
			}
		}

		go appendCanonicals(numCan)
		go appendFailures(numErr)
	}

	log.Printf("Message sent. Attempts: %d, Errors: %d, Successful: %d (Canonicals: %d)", len(tokens), numErr, len(tokens)-numErr, numCan)

	return true, nil
}
Example #21
0
func main() {
	// Begin here.
	/* -------------------------------------  */
	/* 			Boilerplate					  */
	/* -------------------------------------  */
	/*
		Setting up Logging, this is standard practice for all go programs
	*/
	pwd, err := os.Getwd() // get present working directory
	if err != nil {
		log.Fatal(err)
	}
	fo, err := os.Create(pwd + string(filepath.Separator) + "server.log") // create log file in current dir
	if err != nil {
		log.Fatal(err)
	}
	log.SetOutput(io.Writer(fo))
	// 		Done setting up Logging

	// Initialize the config variables
	// This is triggered only once and loads up the conf file.
	if func() bool {
		_confMap = make(map[string]string)
		pwd, err := os.Getwd() // get present working directory
		if err != nil {
			log.Fatal(err)
		}
		path := pwd + string(filepath.Separator) + "cockpit" + string(filepath.Separator) + "conf"
		_, err = os.Stat(path)
		if err != nil {
			log.Fatal("Config file not found. Config file is located in same directory as executable in a folder .arwen/config")
		}
		_cfile, err = goconf.ReadConfigFile(path)
		if err != nil {
			log.Fatal("Error reading config file." + err.Error())
		}
		return true
	}() {
		log.Print("Loaded Logging, starting up server ...")
	} else {
		log.Fatal("Error loading conf file ...")
	}

	/* -------------------------------------  */
	/*			Coding Begins				  */
	/* -------------------------------------  */
	//Variable stores everything
	_store = make(map[string]interface{})
	_servers = make(map[string]interface{})
	// Channels to manage data
	httpChannel := make(chan map[string]interface{})                       // {action : {object}}
	poller := time.NewTicker(time.Duration(int64(5) * int64(time.Second))) // Actual time variable that is a counter
	alertChannel := make(chan map[string]string)
	pollerChannel := make(chan map[string]interface{})
	//serverChannel := make(chan []Serv)
	HTTPHandler.Init()

	// Load the contents of the servers.json to the _servers
	file, e := ioutil.ReadFile("./cockpit/servers.json")
	if e != nil {
		log.Fatal("File Error")
	}
	log.Print(file)
	if string(file) != "" {
		err = json.Unmarshal(file, &_servers)
		if err != nil {
			log.Fatal("Error reading servers.json")
		}
	}

	// Initiate HTTP Listener
	// Listener for the incoming HTTP request
	go func(store map[string]interface{}, servers map[string]interface{}, ch chan map[string]interface{}) {
		// Define the http listener
		router := mux.NewRouter()
		// ROUTER
		router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("{\"status\":\"alive\"}"))
		})
		router.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
			HTTPHandler.Auth(w, r)
		})
		router.HandleFunc("/add/{action}", func(w http.ResponseWriter, r *http.Request) {
			HTTPHandler.Add(w, r, ch)
		})
		router.HandleFunc("/server/{action}", func(w http.ResponseWriter, r *http.Request) {
			HTTPHandler.Server(w, r, servers, store)
		})
		router.HandleFunc("/alert", func(w http.ResponseWriter, r *http.Request) {
			// TODO : Put a conditional key here, we need that key to verify that message isn't bogus
			// If a message is recieved on this func, this needs to be sent as an alert ASAP
			log.Print("Message recieved")
			serv := r.FormValue("alert")
			err := r.FormValue("error")
			res := make(map[string]string)
			res["server"] = serv
			res["error"] = err
			alertChannel <- res
			w.Write([]byte("{\"status\":\"posted\"}"))
		})
		http.Handle("/", router)
		http.ListenAndServe(":63000", nil) // TODO add this to conf
	}(_store, _servers, httpChannel)

	for {
		select {
		case item := <-httpChannel:
			// Poll on Request
			for k, _ := range item {
				if k == "server" {
					// Do soemthing
					// Add this info to server map
					ser := make(map[string]interface{})
					ser["name"] = item[k].(map[string]interface{})["name"].(string)
					ser["key"] = item[k].(map[string]interface{})["key"].(string)
					ser["ip"] = item[k].(map[string]interface{})["ip"].(string)
					if _, ok := _servers[item[k].(map[string]interface{})["name"].(string)]; !ok {
						_servers[item[k].(map[string]interface{})["name"].(string)] = ser
					}
					fi, err := os.OpenFile("./cockpit/servers.json", os.O_RDWR, 0660)
					if err != nil {
						panic(err)
					}
					// close fi on exit and check for its returned error
					defer func() {
						if err := fi.Close(); err != nil {
							panic(err)
						}
					}()
					js, err := json.Marshal(_servers)
					if err != nil {
						log.Panic("Error Marshalling json")
					} else {
						_, err := fi.Write(js)
						if err != nil {
							log.Panic("Unable to write to json file")
						}
					}
				}
			}
		case <-poller.C:
			srv := make(map[string]interface{})
			for k, v := range _servers {
				srv[k] = v
			}
			go func(srv map[string]interface{}) {
				r := make(map[string]interface{})
				// Poller
				// Now loop over servers to check the status of the server
				// Dump the contents of _server as json file
				for _, val := range srv {
					ser := val.(map[string]interface{})
					resp, err := http.Get("http://" + ser["ip"].(string) + ":63001" + "/") // TODO: Add it to conf
					if err != nil {
						log.Print("Error in fetching value for the IP " + ser["ip"].(string))
						resp = nil
					}
					//log.Print(resp)
					if resp != nil {
						var f interface{}
						v, er := ioutil.ReadAll(resp.Body)
						if er != nil {
							log.Print("Error reading value from the server")
						} else {
							er := json.Unmarshal([]byte(v), &f)
							if er != nil {
								log.Print("Error in Unmarshaling data")
								var temp interface{}
								r[ser["name"].(string)] = temp
							} else {
								r[ser["name"].(string)] = f
							}
						}
					} else {
						t := make(map[string]interface{})
						t["status"] = "dead"
						r[ser["name"].(string)] = t
					}
					pollerChannel <- r
				}
			}(srv)

		case alert := <-alertChannel:
			// as of now just print this shit
			data := map[string]interface{}{"server": alert["server"],
				"error": alert["error"]}
			regIDs := []string{"APA91bFLfsr-5lsuunNLXs_qRxCjPW6c9spZIUAnuIXUlwQ0pSEi1U9Ln0ctLjSeD4xT5McsIv2MJSBlQE-v3Y8jm6JtNbzKlWXnK90goeEweQ36t-sGkTf_nVZ-jiB-TfxWS3mQHJxkd1M7PXf5-PWLeWfkOpusESD0z_Q0NMIy2tqAp9X_K7s"}
			msg := gcm.NewMessage(data, regIDs...)
			sender := &gcm.Sender{ApiKey: "AIzaSyCNJeYio3_-9tRF8fjuUep7BeV0c0rE8TU"}
			_, err := sender.Send(msg, 2)
			if err != nil {
				log.Print("Failed to send message:", err)
				return
			}
			log.Print(alert)
		case item := <-pollerChannel:
			// Copy to _server
			for k, v := range item {
				_store[k] = v
			}
		}
	}
}