func CommonSelectFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		id := req.PostFormValue("courseID")
		_, school, ok := validateSession(req, store)
		if ok {
			if id == "" {
				http.ServeFile(w, req, "DHUCourseChooseHTML/commonselect.html")
				return
			} else {
				var done bool
				var err error
				var course CourseContent
				DBsession := GetSession()
				defer DBsession.Close()
				cTable := DBsession.DB(school).C("CourseTable")
				for i := 0; i < 3; i++ {
					course, err = APICommonselect(cTable, id)
					if err == nil {
						done = true
						break
					}
				}
				if done {
					r.JSON(w, http.StatusOK, course)
					return
				}
			}
		}
		http.Redirect(w, req, "/errMessage", http.StatusMovedPermanently)
	}
}
func HomeSelectFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		coursetype := req.PostFormValue("coursetype")
		if ok := validateCourseType(coursetype); ok {
			sessionid, school, ok := validateSession(req, store)
			if ok {
				var done bool
				var err error
				var teachSchemas []TeachSchema
				DBsession := GetSession()
				defer DBsession.Close()
				for i := 0; i < 3; i++ {
					cTable := DBsession.DB(school).C("CourseTable")
					cIndex := DBsession.DB(school).C("CourseIndex")
					teachSchemas, err = APIHomeSelect(cTable, cIndex, sessionid[:6], coursetype)
					if err == nil {
						done = true
						break
					} else {
						fmt.Println(err)
					}
				}
				if done {
					r.JSON(w, http.StatusOK, map[string]([]TeachSchema){"TeachSchema": teachSchemas})
					return
				}
			}
		} else {
			http.ServeFile(w, req, "DHUCourseChooseHTML/homeselect.html")
		}
		// http.Redirect(w,req,"/errMessage",http.StatusMovedPermanently)
	}
}
func HomeRegisterFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		var slist SelectLists
		stuid, school, ok := validateSession(req, store)
		if ok {
			result, err := ioutil.ReadAll(req.Body)
			if err == nil {
				err = json.Unmarshal([]byte(result), &slist)
				if err == nil {
					DBsession := GetSession()
					defer DBsession.Close()
					cTable := DBsession.DB(school).C("CourseTable")
					if ok := validateCourse(slist, cTable); ok {
						courseInfo := saveAndRegister(stuid, school, slist)
						r.JSON(w, http.StatusOK, courseInfo)
						return
					}
					//Note:If the user post some illegal courses then we think it is a crawler or program
				}
			}
		}
		http.Redirect(w, req, "/errMessage", http.StatusMovedPermanently)
		return
	}
}
func HomeFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		status := req.PostFormValue("userstatus")
		if validateHomeStatus(status) {
			stuid, school, ok := validateSession(req, store)
			if ok {
				if status == "" {
					http.ServeFile(w, req, "DHUCourseChooseHTML/home.html")
					return
				} else {
					var err error
					var done bool
					var courselist []RigisteredCourse
					DBsession := GetSession()
					defer DBsession.Close()
					cRigister := DBsession.DB(school).C("RigisterInfo")
					for i := 0; i < 3; i++ {
						courselist, err = getrigisteredFunc(stuid, cRigister)
						if err == nil {
							done = true
							break
						}
					}
					if done {
						r.JSON(w, http.StatusOK, map[string]([]RigisteredCourse){"RigisterCourse": courselist})
						return
					}
				}
			}
		}
		http.Redirect(w, req, "/errMessage", http.StatusMovedPermanently)
	}
}
Example #5
0
// ScenariosByNameHandler
func ScenariosByNameHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		scenarioName := vars["name"]
		ren.JSON(w, http.StatusOK, ScenarioContent(conf.Scenarios.ScenarioDir, scenarioName))
	}
}
Example #6
0
// TaskDeleteByIDRouteHandler deletes the task data for the given ID
func TaskDeleteByIDRouteHandler(ren *render.Render, conf *config.Config, dispatch *dispatcher.Dispatcher) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		tid := vars["id"]
		taskID, err := strconv.Atoi(tid)
		if err != nil {
			log.Println(err)
		}
		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Println(err)
		}
		defer db.Conn.Close()

		task := db.GetTaskByID(taskID)
		if len(task) > 0 {
			dispatch.RemoveTaskChan <- task[0]
			db.DeleteTask(taskID)
		} else {
			ren.JSON(w, http.StatusOK, map[string]interface{}{"error": ErrNoEntryFound.Error()})
			return
		}
		ren.JSON(w, http.StatusOK, map[string]interface{}{"task": taskID})
	}
}
func HomeDeleteFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		courseNo := req.PostFormValue("courseNo")
		if courseNo == "" {
			http.Redirect(w, req, "/errMessage", http.StatusMovedPermanently)
		}
		jsonstatus := map[string]bool{courseNo: false}
		stuid, school, ok := validateSession(req, store)
		if ok {
			var stuInfo StudentRigisterCourse
			DBsession := GetSession()
			defer DBsession.Close()
			cRigister := DBsession.DB(school).C("RigisterInfo")
			err := cRigister.Find(bson.M{"studentid": stuid, "courselist": bson.M{"$elemMatch": bson.M{"courseno": courseNo, "coursestate": courseInQueue}}}).One(&stuInfo)
			if err == nil {
				conflict := true
				//alterDatabase function use conflict(true) to set the course status from inqueue to deleted
				for _, courseInfo := range stuInfo.CourseList {
					if courseInfo.CourseNo == courseNo {
						// fmt.Println(courseNo)
						// fmt.Println(conflict)
						alterDatabase(conflict, school, courseInfo.CourseID, courseNo, stuid, courseInfo.QueueNumber)
						break
					}
				}
				jsonstatus[courseNo] = true
			}
		}
		r.JSON(w, http.StatusOK, jsonstatus)
	}
}
Example #8
0
// SchedulesByTaskIDHandler
func SchedulesByTaskIDHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		taskID := vars["task_id"]
		ren.JSON(w, http.StatusOK, map[string]string{"sent": taskID})
	}
}
func LoginFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		loginJSON := map[string]int{"LoginStatus": networkErrStatus}
		id := req.PostFormValue("UserID")
		if id == "" {
			http.ServeFile(w, req, "DHUCourseChooseHTML/login.html")
			return
		}
		pw := req.PostFormValue("UserPassword")
		//TODO It should be a form value that come from the user request
		school := "DHU"
		DBsession := GetSession()
		defer DBsession.Close()
		cLogin := DBsession.DB(school).C("StudentInfo")
		name, err := validateLogin(id, pw, school, cLogin)
		switch err {
		case nil:
			name = url.QueryEscape(name)
			http.SetCookie(w, &http.Cookie{Name: "stuName", Value: name})
			session, _ := store.Get(req, "sessionid")
			session.Values["stuid"] = id
			session.Values["school"] = school
			session.Save(req, w)
			loginJSON["LoginStatus"] = successStatus
		case passwordErr:
			loginJSON["LoginStatus"] = passwordErrStatus
		}

		r.JSON(w, http.StatusOK, loginJSON)
	}
}
Example #10
0
func cookieWriteHandler(formatter *render.Render) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		expiration := time.Now().Add(365 * 24 * time.Hour)
		cookie := http.Cookie{Name: "sample", Value: "this is a cookie", Expires: expiration}
		http.SetCookie(w, &cookie)
		formatter.JSON(w, http.StatusOK, "cookie set")
	}
}
Example #11
0
func MakeBuildListHandler(r *render.Render) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, req *http.Request) {
		var (
			buildList = []AutomatedBuild{}
		)

		r.JSON(w, http.StatusOK, buildList)
	}
}
Example #12
0
// TasksRunningHandler
func TasksRunningHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Fatalln(err)
			return
		}
		ren.JSON(w, http.StatusOK, db.TasksRunning())
	}
}
Example #13
0
// CommandsRouteHandler provides the handler for commands data
func CommandsRouteHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Println(err)
		}
		defer db.Conn.Close()
		ren.JSON(w, http.StatusOK, map[string]interface{}{"commands": db.GetCommands()})
	}
}
Example #14
0
// SchedulesHandler
func SchedulesHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		results, err := scheduler.ShowSchedules(conf)
		if err != nil {
			log.Println(err)
			return
		}
		ren.JSON(w, http.StatusOK, map[string]interface{}{"schedules": results})
	}
}
Example #15
0
// TorrentHandler is now commented
func TorrentHandler(w http.ResponseWriter, req *http.Request, renderer *render.Render) {
	searchString := req.FormValue("search")
	log.Printf("Searching for %s", searchString)

	torrents := make(map[int][]string)
	torrents = SearchTorrentsFor(searchString, torrents)

	// prepare response page
	renderer.HTML(w, http.StatusOK, "content", torrents)
}
Example #16
0
func vcapHandler(formatter *render.Render, appEnv *cfenv.App) http.HandlerFunc {
	val, err := cftools.GetVCAPServiceProperty("beer-service", "target-url", appEnv)

	return func(w http.ResponseWriter, req *http.Request) {
		if err != nil {
			formatter.JSON(w, http.StatusInternalServerError, struct{ Error string }{err.Error()})
			return
		}
		formatter.JSON(w, http.StatusOK, struct{ Foo string }{val})
	}
}
Example #17
0
// TasksResultsByUUIDHandler
func TasksResultsByUUIDHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		uuid := vars["task_uuid"]
		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Fatalln(err)
			return
		}
		ren.JSON(w, http.StatusOK, db.TaskResultsByUUID(uuid))
	}
}
Example #18
0
// ListDownloadsHandler AJAX method is now commented
func ListDownloadsHandler(w http.ResponseWriter, req *http.Request, renderer *render.Render) {
	dir := req.FormValue("dir")

	if strings.HasPrefix(dir, "~") {
		homedir := os.Getenv("HOME")
		dir = homedir + dir[1:]
	}

	files := structures.PrepareDirectoryContents(dir)

	renderer.HTML(w, http.StatusOK, "downloadDirectory", files)
}
Example #19
0
func addMoveHandler(formatter *render.Render, repo matchRepository) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		matchID := vars["id"]
		match, err := repo.getMatch(matchID)
		if err != nil {
			formatter.JSON(w, http.StatusNotFound, err.Error())
		} else {
			payload, _ := ioutil.ReadAll(req.Body)
			var moveRequest newMoveRequest
			err := json.Unmarshal(payload, &moveRequest)
			newBoard, err := match.GameBoard.PerformMove(gogo.Move{Player: moveRequest.Player, Position: gogo.Coordinate{X: moveRequest.Position.X, Y: moveRequest.Position.Y}})
			if err != nil {
				formatter.JSON(w, http.StatusBadRequest, err.Error())
			} else {
				match.GameBoard = newBoard
				err = repo.updateMatch(matchID, match)
				if err != nil {
					formatter.JSON(w, http.StatusInternalServerError, err.Error())
				} else {
					var mdr matchDetailsResponse
					mdr.copyMatch(match)
					formatter.JSON(w, http.StatusCreated, &mdr)
				}
			}
		}
	}
}
Example #20
0
func getMatchDetailsHandler(formatter *render.Render, repo matchRepository) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		matchID := vars["id"]
		match, err := repo.getMatch(matchID)
		if err != nil {
			formatter.JSON(w, http.StatusNotFound, err.Error())
		} else {
			var mdr matchDetailsResponse
			mdr.copyMatch(match)
			formatter.JSON(w, http.StatusOK, &mdr)
		}
	}
}
Example #21
0
func getMatchListHandler(formatter *render.Render, repo matchRepository) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		repoMatches, err := repo.getMatches()
		if err == nil {
			matches := make([]newMatchResponse, len(repoMatches))
			for idx, match := range repoMatches {
				matches[idx].copyMatch(match)
			}
			formatter.JSON(w, http.StatusOK, matches)
		} else {
			formatter.JSON(w, http.StatusNotFound, err.Error())
		}
	}
}
Example #22
0
// JobByIDRouteHandler provides the handler for jobs data for the given ID
func JobByIDRouteHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		jid := vars["id"]

		jobID, err := strconv.Atoi(jid)
		if err != nil {
			log.Println(err)
			ren.JSON(w, 400, map[string]error{"error": err})
			return
		}

		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Println(err)
			ren.JSON(w, http.StatusOK, map[string]error{"error": err})
			return
		}
		defer db.Conn.Close()

		if t := db.GetJobByID(jobID); len(t) > 0 {
			ren.JSON(w, http.StatusOK, map[string]interface{}{"task": t})
		} else {
			ren.JSON(w, http.StatusOK, map[string]interface{}{"task": ErrNoJobsFound.Error()})
		}
	}
}
Example #23
0
// NewCommandRouteHandler creates a new command with the POST'd data
func NewCommandRouteHandler(ren *render.Render, dispatcher *dispatcher.Dispatcher) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var c database.Command

		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&c)
		if err != nil {
			ren.JSON(w, 400, map[string]error{"error": err})
			return
		}
		defer r.Body.Close()

		switch {
		case c.CMD == "":
			ren.JSON(w, 400, map[string]error{"error": ErrMissingCMDField})
			return
		case c.Args == "":
			ren.JSON(w, 400, map[string]error{"error": ErrMissingArgsField})
			return
		}

		dispatcher.SenderChan <- &c
		ren.JSON(w, http.StatusOK, map[string]database.Command{"command": c})
	}
}
Example #24
0
// DeploymentsByNameHandler
func DeploymentsByNameHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Fatalln(err)
			return
		}
		var dp NewDeploymentParams
		decoder := json.NewDecoder(r.Body)
		err = decoder.Decode(&dp)
		if err != nil {
			log.Println(err)
			return
		}
		ren.JSON(w, http.StatusOK, db.DeploymentsByName(dp.Name))
	}
}
Example #25
0
// CommandDeleteByIDRouteHandler deletes the command data for the given ID
func CommandDeleteByIDRouteHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		tid := vars["id"]
		commandID, err := strconv.Atoi(tid)
		if err != nil {
			log.Println(err)
		}
		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Println(err)
		}
		defer db.Conn.Close()

		db.DeleteCommand(commandID)

		ren.JSON(w, http.StatusOK, map[string]interface{}{"command": commandID})
	}
}
Example #26
0
func FeedBackFunc(r *render.Render, store *sessions.CookieStore) ServePrimeFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		done := map[string]bool{"Done": false}
		message := req.PostFormValue("Message")
		if message == "" {
			http.ServeFile(w, req, "DHUCourseChooseHTML/feedback.html")
			return
		}
		stuid, school, ok := validateSession(req, store)
		if len(message) < 300 {
			if ok {
				storeFeedBackMessage(stuid, school, message)
			} else {
				storeFeedBackMessage("", "", message)
			}
			done["Done"] = true
		}
		r.JSON(w, http.StatusOK, done)
	}
}
Example #27
0
func addTelemetryHandler(formatter *render.Render, dispatcher queueDispatcher) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		payload, _ := ioutil.ReadAll(req.Body)
		var newTelemetryCommand telemetryCommand
		err := json.Unmarshal(payload, &newTelemetryCommand)
		if err != nil {
			formatter.Text(w, http.StatusBadRequest, "Failed to parse add telemetry command.")
			return
		}
		if !newTelemetryCommand.isValid() {
			formatter.Text(w, http.StatusBadRequest, "Invalid telemetry command.")
			return
		}

		evt := dronescommon.TelemetryUpdatedEvent{
			DroneID:          newTelemetryCommand.DroneID,
			RemainingBattery: newTelemetryCommand.RemainingBattery,
			Uptime:           newTelemetryCommand.Uptime,
			CoreTemp:         newTelemetryCommand.CoreTemp,
			ReceivedOn:       time.Now().Unix(),
		}
		fmt.Printf("Dispatching telemetry event for drone %s\n", newTelemetryCommand.DroneID)
		dispatcher.DispatchMessage(evt)
		formatter.JSON(w, http.StatusCreated, evt)
	}
}
Example #28
0
func addPositionHandler(formatter *render.Render, dispatcher queueDispatcher) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		payload, _ := ioutil.ReadAll(req.Body)
		var newPositionCommand positionCommand
		err := json.Unmarshal(payload, &newPositionCommand)
		if err != nil {
			formatter.Text(w, http.StatusBadRequest, "Failed to parse add position command.")
			return
		}
		if !newPositionCommand.isValid() {
			formatter.Text(w, http.StatusBadRequest, "Invalid position command.")
			return
		}
		evt := dronescommon.PositionChangedEvent{
			DroneID:         newPositionCommand.DroneID,
			Longitude:       newPositionCommand.Longitude,
			Latitude:        newPositionCommand.Latitude,
			Altitude:        newPositionCommand.Altitude,
			CurrentSpeed:    newPositionCommand.CurrentSpeed,
			HeadingCardinal: newPositionCommand.HeadingCardinal,
			ReceivedOn:      time.Now().Unix(),
		}
		dispatcher.DispatchMessage(evt)
		formatter.JSON(w, http.StatusCreated, evt)
	}
}
Example #29
0
// CommandByIDRouteHandler provides the handler for commands data for the given ID
func CommandByIDRouteHandler(ren *render.Render, conf *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		tid := vars["id"]

		commandID, err := strconv.Atoi(tid)
		if err != nil {
			log.Println(err)
		}

		db, err := database.NewDatabase(conf)
		if err != nil {
			log.Println(err)
		}
		defer db.Conn.Close()

		if t := db.GetCommandByID(commandID); len(t) > 0 {
			ren.JSON(w, http.StatusOK, map[string]interface{}{"command": t})
		} else {
			ren.JSON(w, http.StatusOK, map[string]interface{}{"command": ErrNoCommandsFound.Error()})
		}
	}
}
Example #30
0
// NewJobRouteHandler creates a new job with the POST'd data
func NewJobRouteHandler(ren *render.Render, dispatcher *dispatcher.Dispatcher) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var nj database.Job

		decoder := json.NewDecoder(r.Body)
		err := decoder.Decode(&nj)
		if err != nil {
			ren.JSON(w, 400, map[string]error{"error": err})
			return
		}
		defer r.Body.Close()
		switch {
		case nj.Name == "":
			ren.JSON(w, 400, map[string]error{"error": ErrMissingNameField})
			return
		}

		dispatcher.SenderChan <- &nj
		ren.JSON(w, http.StatusOK, map[string]database.Job{"job": nj})
	}
}