/src/main.go
Go | 2332 lines | 1652 code | 387 blank | 293 comment | 450 complexity | b4718ee88a93fb959b156dba5c1309ea MD5 | raw file
- package main
- import (
- "encoding/base64"
- "encoding/json"
- "fmt"
- "html/template"
- "log"
- // "flag"
- "net/http"
- "os"
- // "net/url"
- "path/filepath"
- "regexp"
- "strings"
- "bytes"
- "database/sql"
- "strconv"
- "io"
- "net"
- "mime"
- "io/ioutil"
- // "math/rand"
- // "reflect"
- auth "./authentication"
- db "./local_database"
- survey "./survey"
- "github.com/minio/minio-go"
- "github.com/badoux/checkmail"
- "github.com/fsnotify/fsnotify"
- "github.com/gorilla/mux"
- "github.com/gorilla/securecookie"
- "github.com/gorilla/websocket"
- "github.com/oxtoacart/bpool"
- uuid "github.com/satori/go.uuid"
- "gopkg.in/mgo.v2/bson"
- "github.com/rs/xid"
- "github.com/dpapathanasiou/go-recaptcha"
- "github.com/kirves/go-form-it" // import directly into this repo
- "github.com/kirves/go-form-it/fields"
- "github.com/gocraft/dbr"
- )
- var clients = make(map[*websocket.Conn]bool)
- var clientId = make(map[*websocket.Conn]string)
- var clientUser = make(map[*websocket.Conn]string)
- var broadcast = make(chan Message)
- // var socketClients = make(map[string], map[*websocket.Conn]bool)
- var upgrader = websocket.Upgrader{}
- var Global = 0 // For testing rooms functionality
- type Message struct {
- Id int `json:"id"`
- Email string `json:"email"`
- Username string `json:"username"`
- Message string `json:"message"`
- IsPublic bool `json:"isPublic"`
- Signature string `json:"signature"`
- Complete bool `json:"complete"`
- Creating bool `json:"creating"`
- Session string `json:"session"`
- OriginalQuestion int `json:"originalquestion"`
- IsTab bool `json:"isTab"`
- Tab int `json:"tab"`
- File string `json:"file"`
- Owner string `json:"owner"`
- Task map[string]interface{} `json:"task"`
- }
- type Answer struct {
- Question int `json:"question"`
- Response string `json:"response"`
- }
- type Course struct {
- Name string
- Description string `form_widget:"textarea"`
- Type string
- LessonsSections int `form_options:"skip"`
- TotalSections int `form_options:"skip"`
- Link string `form_options:"skip"`
- Difficulty int `form_options:"skip"`
- Catagory string
- IsPublic bool `form_label:"Is Public"`
- }
- type Task struct {
- Name string `json:"name"`
- Body string `json:"body"`
- IsPublic string `json:"isPublic"`
- OriginalQuestion int `json:"originalQuestion"`
- Complete bool `json:"complete"`
- Board string `json:"board"`
- Owner int `json:"owner"`
- Tab int `json:"tab"`
- Index int `json:"index"`
- }
- //Basic user Structure (translates into SQL model)
- type User struct {
- Email string `json:"email"`
- Username string `json:"username"`
- DisplayName string `json:"display_name"`
- }
- type PageTemplate struct {
- Main string
- }
- func main() {
- // Create simple fileserver
- r := mux.NewRouter()
- fs := http.FileServer(http.Dir("../public/static/"))
- loadTemplates()
- http.Handle("/", r)
- http.Handle("/static/", http.StripPrefix("/static/", fs))
- //Add log to file
- //https://stackoverflow.com/questions/19965795/go-golang-write-log-to-file
- // f, err := os.OpenFile("golog.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
- // if err != nil {
- // log.Fatalf("Error opening file: %v", err)
- // }
- // defer f.Close()
- // log.SetOutput(f)
- log.SetFlags(log.LstdFlags | log.Lshortfile)
- //Digital Ocean Spaces SDK
- endpoint := "s3.amazonaws.com"
- accessKeyID := "AKIAIWRI2VNGP4PCA2EA"
- secretAccessKey := "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"
- useSSL := true
- // Initialize minio client object.
- minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
- if err != nil {
- log.Fatalln(err)
- }
-
- // Make a new bucket called mymusic.
- bucketName := "paariomain"
- location := "us-east-2"
- err = minioClient.MakeBucket(bucketName, location)
- if err != nil {
- // Check to see if we already own this bucket (which happens if you run this twice)
- exists, err := minioClient.BucketExists(bucketName)
- if err == nil && exists {
- log.Printf("We already own %s\n", bucketName)
- } else {
- log.Fatalln(err)
- }
- }
- log.Printf("Successfully created %s\n", bucketName)
- adminModels := map[string]interface{}{
- "course": Course{},
- "task": Task{},
- }
- recaptcha.Init ("6LfBNFwUAAAAANnttb-9nUX83ZZw4LrOTLKdAQiI")
- //survey.Load_Survey_Database()
- //For local testing
- db.Connect_To_Test_Database()
- survey.Load_Survey_Database()
- defer survey.MongoDatabase.Close()
- defer survey.QuestionDatabase.Close()
- defer db.MainDatabase.Close()
- r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "404.html", nil, r)
- })
- r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser != "" {
- http.Redirect(w, r, "/app/dashboard/", http.StatusTemporaryRedirect)
- return
- }
- renderTemplate(w, "index.html", nil, r)
- })
- r.HandleFunc("/firebase-messaging-sw.js", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
- b, err := ioutil.ReadFile("firebase-messaging-sw.js") // just pass the file name
- if err != nil {
- fmt.Print(err)
- }
- fmt.Fprintf(w, string(b))
- })
- r.HandleFunc("/api/users/token/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- token := r.FormValue("token")
- database := db.MainDatabase
- rows, err := database.Query(fmt.Sprintf("SELECT fb_token FROM device WHERE fb_token='%v';", token))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
-
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count > 0 {
- fmt.Fprintf(w, "{\"Error\":\"Already Added Token\"}")
- return
- }
- rows, err = database.Query(fmt.Sprintf("INSERT INTO device (auth_user, fb_token) VALUES (%v, '%v');", userId, token))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
-
- for rows.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Added Token\"}")
- })
- r.HandleFunc("/register/signup/", func(w http.ResponseWriter, r *http.Request) {
- redirect := r.URL.Query().Get("redirect")
- renderTemplate(w, "sign_up.html", map[string]interface{}{
- "RedirectUrl": redirect,
- }, r)
- })
- r.HandleFunc("/admin/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "admin_home.html", nil, r)
- })
- r.HandleFunc("/terms/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "terms.html", nil, r)
- })
- r.HandleFunc("/privacy/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "privacy.html", nil, r)
- })
- r.HandleFunc("/about/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "about.html", nil, r)
- })
- r.HandleFunc("/contact/", func(w http.ResponseWriter, r *http.Request) {
- renderTemplate(w, "contact.html", nil, r)
- })
-
- r.HandleFunc("/api/board/edit/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- name := r.FormValue("board_name")
- vision := r.FormValue("board_vision")
- boardId := r.FormValue("board_id")
- database := db.MainDatabase
- rows, err := database.Query(fmt.Sprintf("SELECT id FROM boards WHERE owner=%v AND id=%v;", userId, boardId))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
-
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count <= 0 {
- fmt.Fprintf(w, "{\"Error\":\"Not Board Owner\"}")
- return
- }
- insert_row, error := database.Query(fmt.Sprintf("UPDATE boards SET name='%v', vision='%v' WHERE id=%v;", name, vision, boardId))
- if error != nil {
- log.Fatal(error)
- }
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Board changed\"}")
- })
- // r.HandleFunc("/app/", func(w http.ResponseWriter, r *http.Request) {
- // renderTemplate(w, "admin_home.html", nil, r)
- // })
- r.HandleFunc("/api/board/tabs/get/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- tab := r.FormValue("tab")
- session := r.FormValue("board")
- database := db.MainDatabase
-
- rows, err := database.Query(fmt.Sprintf("SELECT task.id, task.timestamp, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=false AND complete=false AND boards.session='%v' AND tab=%v AND task.owner=%v ORDER BY task.timestamp desc;", session, tab, userId))
- if err != nil {
- log.Fatal(err)
- }
- cols, _ := rows.Columns()
- var mapList []map[string]interface{}
- notLast := rows.Next()
- for notLast {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
-
-
- }
- notLast = rows.Next()
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
-
- queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- if (m["originalquestion"] == nil) {
- queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- }
- completed_rows, err := database.Query(queryStr)
- if err != nil {
- log.Fatal(err)
- }
- mapOfCompleted := getColumnMap(completed_rows)
- m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- mapList = append(mapList, m)
- }
-
- jsonStr, err := json.Marshal(mapList)
- if err != nil {
- log.Fatal(err)
- }
- privateString := string(jsonStr)
- rows.Close()
- rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.body, task.timestamp, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=false AND complete=true AND boards.session='%v' AND tab=%v AND task.owner=%v ORDER BY task.timestamp desc;", session, tab, userId))
- if err != nil {
- log.Fatal(err)
- }
- cols, _ = rows.Columns()
- var mapListComplete []map[string]interface{}
- notLast = rows.Next()
- for notLast {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
-
-
- }
- notLast = rows.Next()
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
-
- queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- if (m["originalquestion"] == nil) {
- queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- }
- completed_rows, err := database.Query(queryStr)
- if err != nil {
- log.Fatal(err)
- }
- mapOfCompleted := getColumnMap(completed_rows)
- m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- mapListComplete = append(mapListComplete, m)
- }
-
- jsonStr, err = json.Marshal(mapListComplete)
- if err != nil {
- log.Fatal(err)
- }
- completeString := string(jsonStr)
- rows.Close()
- rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.body, task.timestamp, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=true AND boards.session='%v' AND tab=%v ORDER BY task.timestamp desc;", session, tab))
- if err != nil {
- log.Fatal(err)
- }
- cols, _ = rows.Columns()
- var mapListPublic []map[string]interface{}
- notLast = rows.Next()
- for notLast {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
- notLast = rows.Next()
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
-
- queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- if (m["originalquestion"] == nil) {
- queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- }
- completed_rows, err := database.Query(queryStr)
- if err != nil {
- log.Fatal(err)
- }
- mapOfCompleted := getColumnMap(completed_rows)
- m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- mapListPublic = append(mapListPublic, m)
- }
- jsonStr, err = json.Marshal(mapListPublic)
- if err != nil {
- log.Fatal(err)
- }
- publicString := string(jsonStr)
- rows.Close()
- fmt.Fprintf(w, `{"Success": {"private": %v, "public": %v, "complete": %v}}`, privateString, publicString, completeString)
- })
- r.HandleFunc("/app/board/", func(w http.ResponseWriter, r *http.Request) {
- database := db.MainDatabase
- rows, err := database.Query("SELECT id, name, body FROM task WHERE isPublic=true ORDER BY task.timestamp desc;")
- if err != nil {
- log.Fatal(err)
- }
- cols, _ := rows.Columns()
- var mapList []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapList = append(mapList, m)
- }
- rows.Close()
- rows, err = database.Query("SELECT id, name, body, originalquestion FROM task WHERE isPublic=false AND complete=false ORDER BY task.timestamp desc;")
- if err != nil {
- log.Fatal(err)
- }
- defer rows.Close()
- cols, _ = rows.Columns()
- var mapListPrivate []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListPrivate = append(mapListPrivate, m)
- }
- rows.Close()
- rows, err = database.Query("SELECT id, name, body, originalquestion FROM task WHERE isPublic=false AND complete=true ORDER BY task.timestamp desc;")
- if err != nil {
- log.Fatal(err)
- }
- defer rows.Close()
- cols, _ = rows.Columns()
- var mapListComplete []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListComplete = append(mapListComplete, m)
- }
- taskForm := forms.BaseForm(forms.POST, "").SetId("taskForm").SetParam("name", "taskForm").Elements(
- fields.TextAreaField("Body", 30, 50).AddClass("materialize-textarea").SetLabel("Body"),
- fields.SubmitButton("submit", "Submit").AddClass("waves-effect waves-light btn"),
- )
- renderTemplate(w, "board_index.html", map[string]interface{}{"taskForm": taskForm, "publicTasks": mapList, "privateTasks": mapListPrivate, "completeTasks": mapListComplete}, r)
- })
- r.HandleFunc("/app/boards/{session}/", func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- session := vars["session"]
- currentUser := getUserName(r)
- if currentUser == "" {
- http.Redirect(w, r, fmt.Sprintf("/register/login/?redirect=/app/boards/%v/", session), http.StatusTemporaryRedirect)
- return
- }
- database := db.MainDatabase
- rows, err := database.Query(fmt.Sprintf("SELECT * FROM boards WHERE session='%v';", session))
- if err != nil {
- log.Println(err)
- }
- cols, _ := rows.Columns()
-
- var mapListBoard []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListBoard = append(mapListBoard, m)
- }
- userId := getUserId(r)
- password := r.FormValue("password")
- rows, err = database.Query(fmt.Sprintf("SELECT user_boards.id FROM user_boards JOIN boards ON boards.id=user_boards.boards WHERE boards.session='%v' AND (user_boards.auth_user=%v OR boards.password='%v');", session, userId, password))
- if err != nil {
- log.Println(err)
- }
- defer rows.Close()
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count <= 0 {
- http.Redirect(w, r, fmt.Sprintf("/app/board/password/?redirect=%v", session), http.StatusTemporaryRedirect)
- return
- }
-
- if len(mapListBoard) == 0 {
- http.Redirect(w, r, "/app/dashboard/", http.StatusTemporaryRedirect)
- return
- }
- rows.Close()
- tabQuery := fmt.Sprintf(`SELECT tab.id, tab.title, tab.board FROM tab JOIN boards ON boards.id=tab.board WHERE tab.board=%v;`, mapListBoard[0]["id"])
- rows, err = database.Query(tabQuery)
- if err != nil {
- log.Fatal(err)
- }
- cols, _ = rows.Columns()
- var mapListTabs []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
-
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
-
- }
-
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
-
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListTabs = append(mapListTabs, m)
- }
- //currentTab := mapListTabs[0]["id"]
- // rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=true AND boards.session='%v' AND tab=%v ORDER BY task.timestamp desc;", session, currentTab))
- // if err != nil {
- // log.Fatal(err)
- // }
- // cols, _ = rows.Columns()
- // var mapList []map[string]interface{}
- // for rows.Next() {
- // // Create a slice of interface{}'s to represent each column,
- // // and a second slice to contain pointers to each item in the columns slice.
- // columns := make([]interface{}, len(cols))
- // columnPointers := make([]interface{}, len(cols))
- // for i, _ := range columns {
- // columnPointers[i] = &columns[i]
- // }
-
- // // Scan the result into the column pointers...
- // if err := rows.Scan(columnPointers...); err != nil {
-
- // }
-
- // // Create our map, and retrieve the value for each column from the pointers slice,
- // // storing it in the map with the name of the column as the key.
- // m := make(map[string]interface{})
- // for i, colName := range cols {
- // val := columnPointers[i].(*interface{})
- // m[colName] = *val
- // }
-
- // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- // //fmt.Println(m)
-
- // queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
-
- // log.Println(fmt.Sprintf("\n===================\n%v\n===================\n", m["originalquestion"] ))
-
- // if (m["originalquestion"] == nil) {
- // queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- // }
- // completed_rows, err := database.Query(queryStr)
- // if err != nil {
- // log.Fatal(err)
- // }
- // mapOfCompleted := getColumnMap(completed_rows)
- // m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- // mapList = append(mapList, m)
- // }
- // rows.Close()
- // rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.name, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE active=true AND isPublic=false AND complete=false AND boards.session='%v' AND task.owner=%v AND tab=%v ORDER BY task.timestamp desc;", session, userId, currentTab))
- // if err != nil {
- // log.Fatal(err)
- // }
- // defer rows.Close()
- // cols, _ = rows.Columns()
- // var mapListPrivate []map[string]interface{}
- // for rows.Next() {
- // // Create a slice of interface{}'s to represent each column,
- // // and a second slice to contain pointers to each item in the columns slice.
- // columns := make([]interface{}, len(cols))
- // columnPointers := make([]interface{}, len(cols))
- // for i, _ := range columns {
- // columnPointers[i] = &columns[i]
- // }
-
- // // Scan the result into the column pointers...
- // if err := rows.Scan(columnPointers...); err != nil {
-
- // }
-
- // // Create our map, and retrieve the value for each column from the pointers slice,
- // // storing it in the map with the name of the column as the key.
- // m := make(map[string]interface{})
- // for i, colName := range cols {
- // val := columnPointers[i].(*interface{})
- // m[colName] = *val
- // }
- // queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
- // if (m["originalquestion"] == nil) {
- // queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- // }
- // completed_rows, err := database.Query(queryStr)
- // if err != nil {
- // log.Fatal(err)
- // }
- // mapOfCompleted := getColumnMap(completed_rows)
- // m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- // //fmt.Println(m)
- // mapListPrivate = append(mapListPrivate, m)
- // }
- // rows.Close()
- // rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.name, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN authentication_users ON task.owner=authentication_users.id JOIN boards ON boards.session=task.board WHERE active=true AND isPublic=false AND complete=true AND boards.session='%v' AND task.owner=%v AND tab=%v ORDER BY task.timestamp desc;", session, userId, currentTab))
- // if err != nil {
- // log.Fatal(err)
- // }
- // cols, _ = rows.Columns()
- // var mapListComplete []map[string]interface{}
- // for rows.Next() {
- // // Create a slice of interface{}'s to represent each column,
- // // and a second slice to contain pointers to each item in the columns slice.
- // columns := make([]interface{}, len(cols))
- // columnPointers := make([]interface{}, len(cols))
- // for i, _ := range columns {
- // columnPointers[i] = &columns[i]
- // }
-
- // // Scan the result into the column pointers...
- // if err := rows.Scan(columnPointers...); err != nil {
-
- // }
-
- // // Create our map, and retrieve the value for each column from the pointers slice,
- // // storing it in the map with the name of the column as the key.
- // m := make(map[string]interface{})
- // for i, colName := range cols {
- // val := columnPointers[i].(*interface{})
- // m[colName] = *val
- // }
- // queryStr := fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task.originalquestion=%v OR task_2.id=%v);`, m["originalquestion"], m["id"])
- // if (m["originalquestion"] == nil) {
- // queryStr = fmt.Sprintf(`SELECT authentication_users.displayname FROM task JOIN task AS task_2 ON task_2.id=task.originalquestion FULL OUTER JOIN authentication_users ON authentication_users.id = task.owner WHERE task.complete = true AND (task_2.id=%v);`, m["id"])
- // }
- // completed_rows, err := database.Query(queryStr)
- // if err != nil {
- // log.Fatal(err)
- // }
- // mapOfCompleted := getColumnMap(completed_rows)
- // m["completed"] = mapOfCompleted
- // m["body"] = template.HTML(m["body"].(string))
- // // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- // //fmt.Println(m)
- // mapListComplete = append(mapListComplete, m)
- // }
- // rows.Close()
- taskForm := forms.BaseForm(forms.POST, "").SetId("taskForm").SetParam("name", "taskForm").Elements(
- fields.TextAreaField("Body", 30, 50).AddClass("materialize-textarea").SetLabel("Body"),
- fields.SubmitButton("submit", "Submit").AddClass("waves-effect waves-light btn"),
- )
- log.Println(mapListTabs[0]["id"])
- var firstTab int64
- cookie, err := r.Cookie("lastTab")
- if err == nil {
- cookieVal, err := strconv.Atoi(cookie.Value)
- if err != nil{
-
- }
- firstTab = int64(cookieVal)
- }else{
- firstTab = mapListTabs[0]["id"].(int64)
- }
- log.Println(firstTab)
-
- userIdInt, err := strconv.Atoi(userId)
- //"publicTasks": mapList, "privateTasks": mapListPrivate, "completeTasks": mapListComplete
- renderTemplate(w, "board_index_redux.html", map[string]interface{}{"UserId": userIdInt, "FirstTab": firstTab, "Tabs": mapListTabs, "Board":mapListBoard[0], "SessionId": session, "taskForm": taskForm}, r)
- })
- r.HandleFunc("/app/courses/create/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- http.Redirect(w, r, "/register/login/?redirect=/app/courses/create/", http.StatusTemporaryRedirect)
- return
- }
- form := forms.BaseFormFromModel(adminModels["course"], forms.POST, "/api/courses/create/").SetParam("name", "courseForm")
- taskForm := forms.BaseFormFromModel(adminModels["task"], forms.POST, "").SetId("taskForm").SetParam("name", "taskForm")
- renderTemplate(w, "courses_create_new.html", map[string]interface{}{"form": form, "taskForm": taskForm}, r)
- })
-
- r.HandleFunc("/admin/{model}/", func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- form := forms.BaseFormFromModel(adminModels[vars["model"]], forms.POST, "")
- renderTemplate(w, "admin_model.html", map[string]interface{}{"form": form}, r)
- })
- r.HandleFunc("/admin/{model}/add/", func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- form := forms.BaseFormFromModel(adminModels[vars["model"]], forms.POST, "")
- renderTemplate(w, "admin_create_model.html", map[string]interface{}{"form": form, "model": vars["model"]}, r)
- })
-
- r.HandleFunc("/admin/{model}/{id:[0-9]+}/", func(w http.ResponseWriter, r *http.Request) {
- //TODO Make this interface work on dynamic typing
- vars := mux.Vars(r)
- var objectDoesNotExist = false
- var currentModel Course
- query := fmt.Sprintf("SELECT * FROM %v WHERE %v.id='%v';", vars["model"], vars["model"], vars["id"])
- rows, err := db.MainDatabase.Query(query)
- if err != nil {
- log.Fatal(err)
- }
- n, err := dbr.Load(rows, ¤tModel)
- if err != nil {
- log.Fatal(err)
- }
- if n != 1 {
- objectDoesNotExist = true
- }
- form := forms.BaseFormFromModel(currentModel, forms.POST, "")
- data := map[string]interface{}{"form": form, "model": vars["model"]}
- if objectDoesNotExist {
- data["form"] = nil
- }
- renderTemplate(w, "admin_create_model.html", data, r)
- })
- r.HandleFunc("/api/register/signup/", func(w http.ResponseWriter, r *http.Request) {
- firstName := r.FormValue("first_name")
- //lastName := r.FormValue("last_name")
- email := r.FormValue("email")
- password := r.FormValue("password")
- confirmPassword := r.FormValue("password_confirm")
- confirmTerms := r.FormValue("agree_terms")
- captcha := r.FormValue("g-recaptcha-response")
-
- confirmCaptcha, error := recaptcha.Confirm (getIPAdress(r), captcha)
- if error != nil {
- log.Println(error)
- }
- if confirmTerms != "true" {
- fmt.Fprintf(w, "{\"Error\":\"Please agree to the Terms of Use and Privacy Policy.\"}")
- return
- }
- if !confirmCaptcha {
- fmt.Fprintf(w, "{\"Error\":\"Please fill out captcha.\"}")
- return
- }
- if password != confirmPassword {
- log.Println("Passwords do not match.")
- fmt.Fprintf(w, "{\"Error\":\"Your password must match.\"}")
- return
- }
- err := checkmail.ValidateFormat(email)
- if err != nil {
- fmt.Println(err)
- fmt.Fprintf(w, "{\"Error\":\"Please enter a valid email address (example@example.com).\"}")
- return
- }
- didCreate, id := auth.CreateUser(email, "maxmarksjr", password, firstName, "foo.db")
- if !didCreate {
- fmt.Fprintf(w, "{\"Error\":\"Account Exists\"}")
- return
- }
- setSession(email,id, w)
- fmt.Fprintf(w, "{\"Success\":\"Account Created\"}")
- })
- r.HandleFunc("/api/register/login/", func(w http.ResponseWriter, r *http.Request) {
- email := r.FormValue("email")
- password := r.FormValue("password")
- didLogin, id := auth.LoginUser(email, password)
- if didLogin {
- setSession(email, id, w)
- fmt.Println("User Logged in")
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- } else {
- clearSession(w)
- fmt.Println("User not logged in")
- fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- }
- })
- r.HandleFunc("/api/tasks/delete/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- task := r.FormValue("task")
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("UPDATE task SET active=false WHERE owner=%v AND id=%v;", userId, task))
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, `{"Error":"Not Task Owner"}`)
- return
- }
-
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- })
-
- r.HandleFunc("/api/tasks/file/", func(w http.ResponseWriter, r *http.Request) {
- log.Println("File Upload Started...")
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- file, handler, err := r.FormFile("fileUploadPrivate")
- if err != nil {
- log.Println(err)
- }
- defer file.Close()
- f, err := os.OpenFile(fmt.Sprintf("temp/%v", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- log.Fatal(err)
- }
- fmt.Println(f.Name()) // For example "dir/prefix054003078"
- io.Copy(f, file)
- //TODO Write the code to get the file
- contentType := mime.TypeByExtension(filepath.Ext(f.Name()))
- // Upload the file with FPutObject
- n, err := minioClient.FPutObject(bucketName, fmt.Sprintf("media/%v/%v", userId, handler.Filename), f.Name(), minio.PutObjectOptions{ContentType:contentType})
- if err != nil {
- log.Fatalln(err)
- }
- log.Printf("Successfully uploaded %s of size %d\n", handler.Filename, n)
- os.Remove(f.Name())
- log.Println(file)
-
- var tmpMsg Message
- tmpMsg.File = fmt.Sprintf("/media/%v/", userId)+handler.Filename
- //tmpMsg.Id = r.FormValue("signature")
- log.Println("File Uploading")
- log.Println(r.FormValue("signature"))
- tmpMsg.Signature = r.FormValue("signature")
- tmpMsg.Session = r.FormValue("session")
- tmpMsg.Message = r.FormValue("Message")
- tmpMsg.IsPublic = false
- tmpMsg.Tab, err = strconv.Atoi(r.FormValue("tab"))
- tmpMsg.Creating = true
- tmpMsg.Id = -1
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, board, owner, tab, file) VALUES ('%v', '%v', %v, '%v', %v, %v, '%v') RETURNING id;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, tmpMsg.Session, userId, tmpMsg.Tab, tmpMsg.File))
- if error != nil {
- log.Fatal(error)
- }
- var id int
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err := database.Query(fmt.Sprintf("SELECT task.id, task.owner, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE task.id=%v;", id))
- if err != nil {
- log.Fatal(err)
- }
- tmpMsg.Task = getColumnMap(rows)[0]
- tmpMsg.Id = id
- // Send it out to every client that is currently connected
- for client := range clients {
- if tmpMsg.Session == clientId[client]{
- err := client.WriteJSON(tmpMsg)
- if err != nil {
- log.Printf("error: %v", err)
- client.Close()
- delete(clients, client)
- }
- }
- }
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- })
- r.HandleFunc("/api/tasks/file/public/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- userId := getUserId(r)
- file, handler, err := r.FormFile("fileUploadPublic")
- if err != nil {
- log.Println(err)
- }
- defer file.Close()
- f, err := os.OpenFile(fmt.Sprintf("temp/%v", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
- if err != nil {
- log.Fatal(err)
- }
- fmt.Println(f.Name()) // For example "dir/prefix054003078"
- io.Copy(f, file)
- //TODO Write the code to get the file
- contentType := "application/octet-stream"
- // Upload the file with FPutObject
- n, err := minioClient.FPutObject(bucketName, fmt.Sprintf("media/%v/%v", userId, handler.Filename), f.Name(), minio.PutObjectOptions{ContentType:contentType})
- if err != nil {
- log.Fatalln(err)
- }
- log.Printf("Successfully uploaded %s of size %d\n", handler.Filename, n)
- os.Remove(f.Name())
- log.Println(file)
- // os.Mkdir(fmt.Sprintf("../public/static/media/%v/", userId), 0777)
- // f, err := os.OpenFile(fmt.Sprintf("../public/static/media/%v/", userId) + handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
- // defer f.Close()
- // io.Copy(f, file)
-
- // log.Println(file)
- //currentSession := r.FormValue("session")
-
- var tmpMsg Message
- tmpMsg.File = fmt.Sprintf("/media/%v/", userId)+handler.Filename
- //tmpMsg.Id = r.FormValue("signature")
- log.Println("File Uploading")
- log.Println(r.FormValue("signature"))
- tmpMsg.Signature = r.FormValue("signature")
- tmpMsg.Session = r.FormValue("session")
- tmpMsg.Message = r.FormValue("Message")
- tmpMsg.IsPublic = true
- tmpMsg.Tab, err = strconv.Atoi(r.FormValue("tab"))
- tmpMsg.Creating = true
- tmpMsg.Id = -1
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, board, owner, tab, file) VALUES ('%v', '%v', %v, '%v', %v, %v, '%v') RETURNING id;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, tmpMsg.Session, userId, tmpMsg.Tab, tmpMsg.File))
- if error != nil {
- log.Fatal(error)
- }
- var id int
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err := database.Query(fmt.Sprintf("SELECT task.id, task.owner, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE task.id=%v;", id))
- if err != nil {
- log.Fatal(err)
- }
- tmpMsg.Task = getColumnMap(rows)[0]
- tmpMsg.Id = id
- // Send it out to every client that is currently connected
- for client := range clients {
- if tmpMsg.Session == clientId[client]{
- err := client.WriteJSON(tmpMsg)
- if err != nil {
- log.Printf("error: %v", err)
- client.Close()
- delete(clients, client)
- }
- }
- }
- fmt.Fprintf(w, "{\"Success\":\"User Logged In\"}")
- })
- r.HandleFunc("/api/courses/create/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
- return
- }
- name := r.FormValue("Name")
- description := r.FormValue("Description")
- courseType := r.FormValue("Type")
- catagory := r.FormValue("Catagory")
- isPublic := r.FormValue("IsPublic")
- database := db.MainDatabase
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO course(name, description, type, catagory, isPublic) VALUES ('%v', '%v', '%v', '%v', '%v');", name, description, courseType, catagory, isPublic))
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Course Created\"}")
- })
- r.HandleFunc("/api/boards/add/", func(w http.ResponseWriter, r *http.Request) {
- userId := getUserId(r)
- if userId == "" {
- return
- }
- boardId := r.FormValue("boardId")
- database := db.MainDatabase
- insertQuery := fmt.Sprintf("INSERT INTO user_boards VALUES (%v, %v);", userId, boardId)
- log.Println(insertQuery)
- insert_row, error := database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- fmt.Fprintf(w, "{\"Success\":\"Board Added\"}")
- })
- r.HandleFunc("/api/survey/intro/", func(w http.ResponseWriter, r *http.Request) {
- currentSurveySession := getSurveySession(r)
- fmt.Printf("\nHello World My Name is %v\n", currentSurveySession)
- questionId := r.FormValue("question")
- question := survey.Get_Survey_Question(questionId)
- if questionId == "4" {
- if err := r.ParseForm(); err != nil {
- // handle error
- }
- fmt.Println(r.PostForm["mainInput"])
- response := survey.Process_Task_Answer(r.PostForm["mainInput"], question, questionId, currentSurveySession)
- if response != "" {
- fmt.Fprintf(w, response)
- } else {
- fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- }
- }else if questionId == "5"{
- //name := results["name"][0]
- //Check if the user is logged in
- survey.SessionList[currentSurveySession]["mainInput"] = r.PostForm["mainInput"]
- survey.SessionList[currentSurveySession]["password"] = r.PostForm["password"]
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, "{\"Error\":\"No Auth\"}")
- return
- }
- userId := getUserId(r)
- results := survey.SessionList[currentSurveySession]
- vision := sanitizeInput(results["vision"][0])
- tasks := results["tasks"]
- boardName := sanitizeInput(r.PostForm["mainInput"][0])
- password := sanitizeInput(r.PostForm["password"][0])
- projectType := sanitizeInput(results["type"][0])
- sessionId := xid.New()
- insertQuery := fmt.Sprintf("INSERT INTO boards (name, vision, session, password, type, owner) VALUES ('%v', '%v', '%v', '%v', '%v', %v) RETURNING id;", boardName, vision, sessionId, password, projectType, userId)
- database := db.MainDatabase
- insert_row, error := database.Query(insertQuery)
- var boardId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&boardId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = fmt.Sprintf("INSERT INTO user_boards (auth_user, boards) VALUES (%v, %v);", userId, boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- insertQuery = fmt.Sprintf("INSERT INTO tab (title, board) VALUES ('Main', %v) RETURNING id;", boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
-
- var tabId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&tabId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = "INSERT INTO task (body, board, owner, isPublic, complete, tab) VALUES %v;"
- var buffer bytes.Buffer
- for index := range tasks {
- currentStr := fmt.Sprintf(`('%v', '%v', %v, false, true, %v)`, sanitizeInput(tasks[index]), sessionId, userId, tabId)
- buffer.WriteString(currentStr)
- if index != len(tasks) - 1 {
- buffer.WriteString(",")
- }
- }
- insertQuery = fmt.Sprintf(insertQuery, buffer.String())
- fmt.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- }
- for insert_row.Next() {
- continue
- }
-
- fmt.Fprintf(w, "{\"Done\":\"Complete\"}")
- return
- }else{
- answer := r.FormValue("mainInput")
- fmt.Println(answer)
- fmt.Printf(questionId)
- response := survey.Process_Intro_Answer(answer, question, questionId, currentSurveySession)
- fmt.Println(response)
- fmt.Println("========================")
- //fmt.Println(question[0])
- //fmt.Println(response)
- if response != "" {
- fmt.Fprintf(w, response)
- } else {
- fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- }
- }
-
- //fmt.Fprintf(w, "{\"Error\":\"Incorrect\"}")
- })
- r.HandleFunc("/app/board/finish/", func(w http.ResponseWriter, r *http.Request) {
- currentSurveySession := getSurveySession(r)
- //Check if the user is logged in
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, "{\"Error\":\"No Auth\"}")
- return
- }
- results := survey.SessionList[currentSurveySession]
- userId := getUserId(r)
- fmt.Printf("\n\n%v\n\n", results)
- vision := sanitizeInput(results["vision"][0])
- tasks := results["tasks"]
- boardName := sanitizeInput(results["mainInput"][0])
- password := sanitizeInput(results["password"][0])
- projectType := sanitizeInput(results["type"][0])
- sessionId := xid.New()
- insertQuery := fmt.Sprintf("INSERT INTO boards (name, vision, session, password, type, owner) VALUES ('%v', '%v', '%v', '%v', '%v', %v) RETURNING id;", boardName, vision, sessionId, password, projectType, userId)
- log.Println(insertQuery)
- database := db.MainDatabase
- insert_row, error := database.Query(insertQuery)
- var boardId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&boardId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = fmt.Sprintf("INSERT INTO user_boards VALUES (%v, %v);", userId, boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- continue
- }
- insertQuery = fmt.Sprintf("INSERT INTO tab (title, board) VALUES ('Main', %v) RETURNING id;", boardId)
- log.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
-
- var tabId int
- if error != nil {
- log.Println(error)
- fmt.Fprintf(w, "{\"Error\":\"Server Error\"}")
- return
- }
- for insert_row.Next() {
- err := insert_row.Scan(&tabId)
- if err != nil {
- log.Fatal(err)
- }
- }
- insertQuery = "INSERT INTO task (body, board, owner, isPublic, complete, tab) VALUES %v;"
- var buffer bytes.Buffer
- for index := range tasks {
- currentStr := fmt.Sprintf(`('%v', '%v', %v, false, true, %v)`, sanitizeInput(tasks[index]), sessionId, userId, tabId)
- buffer.WriteString(currentStr)
- if index != len(tasks) - 1 {
- buffer.WriteString(",")
- }
- }
- insertQuery = fmt.Sprintf(insertQuery, buffer.String())
- fmt.Println(insertQuery)
- insert_row, error = database.Query(insertQuery)
- if error != nil {
- log.Println(error)
- }
- for insert_row.Next() {
- continue
- }
-
- http.Redirect(w, r, fmt.Sprintf("/app/boards/%v/",sessionId), http.StatusTemporaryRedirect)
- return
- })
- r.HandleFunc("/app/dashboard/", func(w http.ResponseWriter, r *http.Request) {
- currentUser := getUserName(r)
- if currentUser == "" {
- http.Redirect(w, r, "/register/login/?redirect=/app/dashboard/", http.StatusTemporaryRedirect)
- return
- }
- userId := getUserId(r)
- // query := fmt.Sprintf("SELECT course.id, course.name, course.type, course.difficulty, course.totalLessons FROM user_courses JOIN course ON course.id = user_courses.course JOIN authentication_users ON authentication_users.id = user_courses.auth_user WHERE authentication_users.email='%v';", currentUser)
- query := fmt.Sprintf("SELECT boards.id, name, vision, session FROM user_boards JOIN boards ON boards.id = user_boards.boards WHERE user_boards.auth_user = %v ORDER BY boards.id desc;", userId);
- database := db.MainDatabase
- rows, err := database.Query(query)
- if err != nil {
- log.Fatal(err)
- }
- cols, _ := rows.Columns()
- var courses []Course
- fmt.Println(courses)
- var mapList []map[string]interface{}
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
- fmt.Println(columnPointers)
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapList = append(mapList, m)
- // courses = append(courses, Course{
- // Name: m["name"].(string),
- // Type: m["type"].(string),
- // LessonsSections: 0,
- // TotalSections: int(m["totallessons"].(int64)),
- // Link: "#",
- // })
- }
- data := map[string]interface{}{
- "Boards": mapList,
- }
- renderTemplate(w, "dashboard.html", data, r)
- })
- r.HandleFunc("/register/login/", func(w http.ResponseWriter, r *http.Request) {
- redirect := r.URL.Query().Get("redirect")
- renderTemplate(w, "login.html", map[string]interface{}{
- "RedirectUrl": redirect,
- }, r)
- })
- r.HandleFunc("/app/board/password/", func(w http.ResponseWriter, r *http.Request) {
- redirect := r.URL.Query().Get("redirect")
- renderTemplate(w, "board_require_password.html", map[string]interface{}{
- "RedirectUrl": fmt.Sprintf("/app/boards/%v/", redirect),
- "Session": redirect,
- }, r)
- })
- r.HandleFunc("/api/boards/password/", func(w http.ResponseWriter, r *http.Request) {
- password := r.FormValue("mainInput")
- session := r.FormValue("session")
- database := db.MainDatabase
-
- rows, err := database.Query(fmt.Sprintf("SELECT id FROM boards WHERE password='%v' AND session='%v';", password, session))
- if err != nil {
- log.Fatal(err)
- }
- var count = 0
- for rows.Next() {
- count += 1
- }
- if count <= 0 {
- fmt.Fprintf(w, "{\"Error\":\"Your password must match.\"}")
- return
- }
- fmt.Fprintf(w, fmt.Sprintf(`{"Success":"%v"}`, password))
- })
- //https://stackoverflow.com/questions/37934162/output-uuid-in-go-as-a-short-string
- r.HandleFunc("/app/starting_survey/", func(w http.ResponseWriter, r *http.Request) {
- currentSurveySession := getSurveySession(r)
- vision := r.FormValue("mainInput")
- if currentSurveySession != "" {
- fmt.Printf("Found session: %v\n", currentSurveySession)
- } else {
- var escaper = strings.NewReplacer("9", "99", "-", "90", "_", "91")
- var unescaper = strings.NewReplacer("99", "9", "90", "-", "91", "_")
- sessionUUID, err := uuid.NewV4()
- if err != nil {
- log.Fatal(err)
- }
- s := escaper.Replace(base64.RawURLEncoding.EncodeToString(sessionUUID.Bytes()))
- dec, err := base64.RawURLEncoding.DecodeString(unescaper.Replace(s))
- sessionId := fmt.Sprintf("%x", dec)
- setSurveySession(sessionId, w)
- fmt.Printf("Created new session: %v\n", sessionId)
- c := survey.MongoDatabase.DB("intro_survey").C("sessions")
- err = c.Insert(bson.M{"sessionId": sessionId})
- if err != nil {
- log.Fatal(err)
- }
- survey.SessionList[sessionId] = make(map[string][]string)
- }
- renderTemplate(w, "survey.html", map[string]interface{}{
- "Vision": vision,
- }, r)
- })
- r.HandleFunc("/app/board/create/", func(w http.ResponseWriter, r *http.Request) {
- currentSurveySession := getSurveySession(r)
- if currentSurveySession != "" {
- fmt.Printf("Found session: %v\n", currentSurveySession)
- survey.SessionList[currentSurveySession] = make(map[string][]string)
- } else {
- var escaper = strings.NewReplacer("9", "99", "-", "90", "_", "91")
- var unescaper = strings.NewReplacer("99", "9", "90", "-", "91", "_")
- sessionUUID, err := uuid.NewV4()
- if err != nil {
- log.Fatal(err)
- }
- s := escaper.Replace(base64.RawURLEncoding.EncodeToString(sessionUUID.Bytes()))
- dec, err := base64.RawURLEncoding.DecodeString(unescaper.Replace(s))
- sessionId := fmt.Sprintf("%x", dec)
- setSurveySession(sessionId, w)
- fmt.Printf("Created new session: %v\n", sessionId)
- c := survey.MongoDatabase.DB("intro_survey").C("sessions")
- err = c.Insert(bson.M{"sessionId": sessionId})
- if err != nil {
- log.Fatal(err)
- }
- survey.SessionList[sessionId] = make(map[string][]string)
- }
- renderTemplate(w, "survey.html", map[string]interface{}{
- "SkipFirst": true,
- }, r)
- })
- // Configure websocket routine
- http.HandleFunc("/ws", handleConnections)
- // http.HandleFunc("/ws/{model}/", func(w http.ResponseWriter, r *http.Request) {
- // vars := websocket.Vars(r)
- // fmt.Println("Hello World")
- // fmt.Println(vars["vars"])
- // })
- go setTemplateChangeWatcher()
- go handleMessages()
- // Start the server on localhost port 8000 and log any errors
- log.Println("http server started on :8000")
- err_listen := http.ListenAndServe(":8000", nil)
- if err_listen != nil {
- log.Fatal("ListenAndServe: ", err_listen)
- }
- }
- func getColumnMap(rows *sql.Rows) (mapListComplete []map[string]interface{}){
- cols, _ := rows.Columns()
- for rows.Next() {
- // Create a slice of interface{}'s to represent each column,
- // and a second slice to contain pointers to each item in the columns slice.
- columns := make([]interface{}, len(cols))
- columnPointers := make([]interface{}, len(cols))
- for i, _ := range columns {
- columnPointers[i] = &columns[i]
- }
- // Scan the result into the column pointers...
- if err := rows.Scan(columnPointers...); err != nil {
- }
- // Create our map, and retrieve the value for each column from the pointers slice,
- // storing it in the map with the name of the column as the key.
- m := make(map[string]interface{})
- for i, colName := range cols {
- val := columnPointers[i].(*interface{})
- m[colName] = *val
- }
- // Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...]
- //fmt.Println(m)
- mapListComplete = append(mapListComplete, m)
- }
- return mapListComplete
- }
- //https://husobee.github.io/golang/ip-address/2015/12/17/remote-ip-go.html
- //ipRange - a structure that holds the start and end of a range of ip addresses
- type ipRange struct {
- start net.IP
- end net.IP
- }
- // inRange - check to see if a given ip address is within a range given
- func inRange(r ipRange, ipAddress net.IP) bool {
- // strcmp type byte comparison
- if bytes.Compare(ipAddress, r.start) >= 0 && bytes.Compare(ipAddress, r.end) < 0 {
- return true
- }
- return false
- }
- var privateRanges = []ipRange{
- ipRange{
- start: net.ParseIP("10.0.0.0"),
- end: net.ParseIP("10.255.255.255"),
- },
- ipRange{
- start: net.ParseIP("100.64.0.0"),
- end: net.ParseIP("100.127.255.255"),
- },
- ipRange{
- start: net.ParseIP("172.16.0.0"),
- end: net.ParseIP("172.31.255.255"),
- },
- ipRange{
- start: net.ParseIP("192.0.0.0"),
- end: net.ParseIP("192.0.0.255"),
- },
- ipRange{
- start: net.ParseIP("192.168.0.0"),
- end: net.ParseIP("192.168.255.255"),
- },
- ipRange{
- start: net.ParseIP("198.18.0.0"),
- end: net.ParseIP("198.19.255.255"),
- },
- }
- // isPrivateSubnet - check to see if this ip is in a private subnet
- func isPrivateSubnet(ipAddress net.IP) bool {
- // my use case is only concerned with ipv4 atm
- if ipCheck := ipAddress.To4(); ipCheck != nil {
- // iterate over all our ranges
- for _, r := range privateRanges {
- // check if this ip is in a private range
- if inRange(r, ipAddress){
- return true
- }
- }
- }
- return false
- }
- func getIPAdress(r *http.Request) string {
- for _, h := range []string{"X-Forwarded-For", "X-Real-Ip"} {
- addresses := strings.Split(r.Header.Get(h), ",")
- // march from right to left until we get a public address
- // that will be the address right before our proxy.
- for i := len(addresses) -1 ; i >= 0; i-- {
- ip := strings.TrimSpace(addresses[i])
- // header can contain spaces too, strip those out.
- realIP := net.ParseIP(ip)
- if !realIP.IsGlobalUnicast() || isPrivateSubnet(realIP) {
- // bad address, go to next
- continue
- }
- return ip
- }
- }
- return ""
- }
- //https://gist.github.com/mschoebel/9398202
- //Hey, don't tell anyone about these keys. They are super secret
- var cookieHandler = securecookie.New(
- []byte{170, 218, 150, 242, 74, 205, 63, 28, 156, 229, 161, 187, 83, 45, 188, 101, 50, 41, 39, 172, 35, 94, 233, 246, 31, 172, 196, 107, 136, 14, 121, 13, 27, 177, 229, 118, 18, 62, 129, 81, 168, 80, 1, 147, 128, 58, 26, 242, 15, 231, 45, 140, 15, 107, 45, 143, 91, 205, 249, 238, 201, 15, 155, 7},
- []byte{253, 146, 211, 216, 77, 3, 0, 42, 233, 90, 117, 198, 18, 178, 226, 136, 121, 207, 160, 243, 244, 40, 69, 97, 255, 133, 215, 65, 239, 35, 100, 179},
- )
- func getUserName(request *http.Request) (userName string) {
- if cookie, err := request.Cookie("session"); err == nil {
- cookieValue := make(map[string]string)
- if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
- userName = cookieValue["name"]
- } else {
- return ""
- }
- }
- return userName
- }
- func getUserId(request *http.Request) (id string) {
- if cookie, err := request.Cookie("session"); err == nil {
- cookieValue := make(map[string]string)
- if err = cookieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
- id = cookieValue["id"]
- } else {
- return ""
- }
- }
- return id
- }
- func setVisionCookie(vision string, response http.ResponseWriter) {
- value := map[string]string{
- "vision": vision,
- }
- if encoded, err := cookieHandler.Encode("home_vision", value); err == nil {
- cookie := &http.Cookie{
- Name: "home_vision",
- Value: encoded,
- Path: "/",
- }
- http.SetCookie(response, cookie)
- }
- }
- func getVisionCookie(request *http.Request) (vision string) {
- if cookie, err := request.Cookie("home_vision"); err == nil {
- cookieValue := make(map[string]string)
- if err = cookieHandler.Decode("home_vision", cookie.Value, &cookieValue); err == nil {
- vision = cookieValue["vision"]
- } else {
- return ""
- }
- }
- return vision
- }
- func setSurveySession(sessionId string, response http.ResponseWriter) {
- value := map[string]string{
- "sessionId": sessionId,
- }
- if encoded, err := cookieHandler.Encode("intro_session", value); err == nil {
- cookie := &http.Cookie{
- Name: "intro_session",
- Value: encoded,
- Path: "/",
- }
- http.SetCookie(response, cookie)
- }
- }
- func getSurveySession(request *http.Request) (sessionId string) {
- if cookie, err := request.Cookie("intro_session"); err == nil {
- cookieValue := make(map[string]string)
- if err = cookieHandler.Decode("intro_session", cookie.Value, &cookieValue); err == nil {
- sessionId = cookieValue["sessionId"]
- } else {
- return ""
- }
- }
- return sessionId
- }
- func setSession(userName string, id int, response http.ResponseWriter) {
- value := map[string]string{
- "name": userName,
- "id": fmt.Sprintf("%v", id),
- }
- if encoded, err := cookieHandler.Encode("session", value); err == nil {
- cookie := &http.Cookie{
- Name: "session",
- Value: encoded,
- Path: "/",
- }
- http.SetCookie(response, cookie)
- }
- }
- func clearSession(response http.ResponseWriter) {
- cookie := &http.Cookie{
- Name: "session",
- Value: "",
- Path: "/",
- MaxAge: -1,
- }
- http.SetCookie(response, cookie)
- }
- func setTemplateChangeWatcher() {
- // creates a new file watcher
- watcher, err := fsnotify.NewWatcher()
- if err != nil {
- fmt.Println("ERROR", err)
- }
- defer watcher.Close()
- //
- done := make(chan bool)
- //
- go func() {
- for {
- select {
- // watch for events
- case event := <-watcher.Events:
- fmt.Printf("Reloading Templates: %#v\n", event)
- loadTemplates()
- // watch for errors
- case err := <-watcher.Errors:
- fmt.Println("ERROR", err)
- }
- }
- }()
- err = watcher.Add("../public/layout")
- if err != nil {
- log.Fatal(err)
- }
- err = watcher.Add("../public/main")
- if err != nil {
- log.Fatal(err)
- }
- err = watcher.Add("../public/main/registration")
- if err != nil {
- log.Fatal(err)
- }
- err = watcher.Add("../public/main/errors")
- if err != nil {
- log.Fatal(err)
- }
- err = watcher.Add("../public/main/boards")
- if err != nil {
- log.Fatal(err)
- }
- err = watcher.Add("../public/main/courses")
- if err != nil {
- log.Fatal(err)
- }
- err = watcher.Add("../public/main/admin")
- if err != nil {
- log.Fatal(err)
- }
- <-done
- }
- func sanitizeInput(str string) (outStr string) {
- var replacer = strings.NewReplacer("'", "''")
- outStr = replacer.Replace(str)
- return outStr
- }
- //https://hackernoon.com/golang-template-2-template-composition-and-how-to-organize-template-files-4cb40bcdf8f6
- var mainTmpl = `{{define "main" }} {{ template "base" . }} {{ end }}`
- var templates map[string]*template.Template
- var TemplateLayoutPath = "../public/layout/"
- var TemplateIncludePath = "../public/main/"
- var bufpool *bpool.BufferPool
- func loadTemplates() {
- if templates == nil {
- templates = make(map[string]*template.Template)
- }
- mainTemplate := template.New("main")
- mainTemplate, err := mainTemplate.Parse(mainTmpl)
- if err != nil {
- log.Fatal(err)
- }
- layoutFiles, err := filepath.Glob(TemplateLayoutPath + "*.html")
- if err != nil {
- log.Fatal(err)
- }
- //Just noting how long this took. Thanks kinda dynamic variables
- var includeFiles []string
- filepath.Walk(TemplateIncludePath, func(path string, f os.FileInfo, _ error) error {
- if !f.IsDir() {
- r, err := regexp.MatchString(".html", f.Name())
- if err == nil && r {
- includeFiles = append(includeFiles, path)
- }
- }
- return nil
- })
- if err != nil {
- log.Fatal(err)
- }
- for _, file := range includeFiles {
- fileName := filepath.Base(file)
- files := append(layoutFiles, file)
- templates[fileName], err = mainTemplate.Clone()
- if err != nil {
- log.Fatal(err)
- }
- templates[fileName] = template.Must(templates[fileName].ParseFiles(files...))
- }
- bufpool = bpool.NewBufferPool(64)
- }
- func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}, r *http.Request) {
- tmpl, ok := templates[name]
- if !ok {
- http.Error(w, fmt.Sprintf("The template %s does not exist.", name),
- http.StatusInternalServerError)
- }
- userEmail := getUserName(r)
- var isLoggedIn bool
- if userEmail == "" {
- isLoggedIn = false
- // fmt.Printf(userEmail)
- } else {
- isLoggedIn = true
- }
- baseParamters := map[string]interface{}{
- "isLoggedIn": isLoggedIn,
- "SiteTitle": "Paario",
- }
- if data != nil {
- for k, v := range data {
- if _, ok := data[k]; ok {
- baseParamters[k] = v
- }
- }
- }
- buf := bufpool.Get()
- defer bufpool.Put(buf)
- err := tmpl.Execute(buf, baseParamters)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- }
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- buf.WriteTo(w)
- }
- func handleConnections(w http.ResponseWriter, r *http.Request) {
- // Upgrade initial GET request to a websocket
- session := r.FormValue("sessionId")
-
- currentUser := getUserName(r)
- if currentUser == "" {
- fmt.Fprintf(w, `{"Error":"Not Authenticated"}`)
-
- }
- userId := getUserId(r)
- ws, err := upgrader.Upgrade(w, r, nil)
- if err != nil {
- log.Fatal(err)
- }
- // Make sure we close the connection when the function returns
- defer ws.Close()
- // Register our new client
- clients[ws] = true
- clientId[ws] = fmt.Sprintf("%v", session)
- clientUser[ws] = fmt.Sprintf("%v", userId)
- Global += 1
- for {
- var msg Message
- // Read in a new message as JSON and map it to a Message object
- err := ws.ReadJSON(&msg)
- if err != nil {
- log.Printf("error: %v", err)
- delete(clients, ws)
- break
- }
- log.Println(msg)
- currentSession := clientId[ws]
- log.Println(currentSession)
- // Send the newly received message to the broadcast channel
- var tmpMsg Message
- tmpMsg = msg
- currentUser := getUserName(r)
- tmpMsg.OriginalQuestion = tmpMsg.Id
- database := db.MainDatabase
- currentUser = sanitizeInput(currentUser)
- tmpMsg.Message = sanitizeInput(tmpMsg.Message)
- userId := getUserId(r)
- log.Printf("\n\n%v\n\n", userId)
- if tmpMsg.IsTab {
- if tmpMsg.Message != "" {
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO tab(title, board) VALUES ('%v', %v) RETURNING id;", tmpMsg.Message, tmpMsg.Username))
-
- if error != nil {
- log.Fatal(error)
- }
- var id int
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- tmpMsg.Session = currentSession
- tmpMsg.IsTab = true
- tmpMsg.IsPublic = true
- tmpMsg.Id = id
- log.Println(tmpMsg)
- broadcast <- tmpMsg
- }
- }else{
- tmpMsg.IsTab = false
- if tmpMsg.Id != -1 && tmpMsg.Creating {
- rows, err := database.Query(fmt.Sprintf("SELECT originalquestion FROM task WHERE originalquestion=%v AND owner=%v;", tmpMsg.Id, userId))
- if err != nil {
- log.Fatal(err)
- }
- var count = 0
- for rows.Next() {
- count += 1
- }
-
- if !(count > 0) {
- var id int
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, originalquestion, board, owner, tab, file) VALUES ('%v', '%v', %v, %v, '%v', %v, %v, '%v') RETURNING id;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, tmpMsg.Id, currentSession, userId, tmpMsg.Tab, tmpMsg.File))
- if error != nil {
- log.Fatal(error)
- }
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.tab, task.owner, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE task.id=%v;", id))
- if err != nil {
- log.Fatal(err)
- }
- tmpMsg.Task = getColumnMap(rows)[0]
- tmpMsg.Id = id
- //broadcast <- tmpMsg
- log.Println(currentUser)
- }
- }else{
- var id int
- log.Println(fmt.Sprintf("Finding: %v", tmpMsg.Id))
- rows, err := database.Query(fmt.Sprintf("SELECT id FROM task WHERE id=%v;", tmpMsg.Id))
- if err != nil {
- log.Fatal(err)
- }
- var count = 0
- for rows.Next() {
- count += 1
- }
- log.Println(fmt.Sprintf("COUNT: %v", count))
-
- if count > 0 {
- insert_row, error := database.Query(fmt.Sprintf("UPDATE task SET complete=%v WHERE id=%v;", tmpMsg.Complete, tmpMsg.Id))
- if error != nil {
- log.Fatal(error)
- }
- for insert_row.Next() {
- continue
- }
- fmt.Println(id)
- //tmpMsg.Id = id
- log.Println(fmt.Sprintf("Updating: %v", tmpMsg.Id))
- } else {
- insert_row, error := database.Query(fmt.Sprintf("INSERT INTO task(name, body, isPublic, board, owner, tab) VALUES ('%v', '%v', %v, '%v', %v, %v) RETURNING id ;", currentUser, tmpMsg.Message, tmpMsg.IsPublic, currentSession, userId, tmpMsg.Tab))
- if error != nil {
- log.Fatal(error)
- }
- for insert_row.Next() {
- err := insert_row.Scan(&id)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err = database.Query(fmt.Sprintf("SELECT task.id, task.owner, task.body, task.originalquestion, authentication_users.displayname, task.file FROM task JOIN boards ON boards.session=task.board JOIN authentication_users ON task.owner=authentication_users.id WHERE task.id=%v;", id))
- if err != nil {
- log.Fatal(err)
- }
- tmpMsg.Task = getColumnMap(rows)[0]
- tmpMsg.Id = id
- }
- }
- if (tmpMsg.IsPublic) {
- rows, err := database.Query(fmt.Sprintf("SELECT name FROM boards WHERE session='%v';", currentSession))
- if err != nil {
- log.Fatal(err)
- }
- var boardName string
- for rows.Next() {
- err = rows.Scan(&boardName)
- if err != nil {
- log.Fatal(err)
- }
- }
- rows, err = database.Query(fmt.Sprintf("SELECT fb_token FROM device JOIN user_boards ON user_boards.auth_user=device.auth_user WHERE user_boards.boards=%v AND NOT device.auth_user=%v;", tmpMsg.Username, userId))
- if err != nil {
- log.Println(err)
- }
- var regIds []string
- for rows.Next() {
- var reg_id string
- err = rows.Scan(®_id)
- if err != nil {
- log.Fatal(err)
- }
- regIds = append(regIds, reg_id)
- }
- regJson, err := json.Marshal(regIds)
- if err != nil {
- log.Println("Cannot encode to JSON ", err)
- }
- url := "https://fcm.googleapis.com/fcm/send"
- var jsonStr = []byte(fmt.Sprintf(`{"registration_ids": %v, "notification": {"title": "%v", "body": "%v: %v", "click_action":"https://paar.io/app/boards/%v/"}}`, string(regJson), boardName, tmpMsg.Task["displayname"], tmpMsg.Message, currentSession))
- log.Println(string(jsonStr))
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
- req.Header.Set("Authorization", "key=AAAAskOw0U8:APA91bHWWqwO1AF_dq1MkXwpMdawR7aIx3-0kpTsrWNm01WUopc8mfbDm6JVee_Q1naJIbMQXo08Bxpc-i3kzlQRRq5954oFBUT1zZqby3U9ciQvqZjKfw4JRd1Z7N869la6Nj4gdSPJ")
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- panic(err)
- }
- log.Println(resp)
- }
-
- tmpMsg.Session = currentSession
- //tmpMsg.Response = survey.Process_Answer(msg.Response, question)
- log.Println(tmpMsg)
- broadcast <- tmpMsg
- log.Println(currentUser)
- }
-
- //log.Printf(msg.Email + " " + msg.Message)
-
- }
- }
- func handleMessages() {
- for {
- // Grab the next message from the broadcast channel
- msg := <- broadcast
- fmt.Println(msg)
- // Send it out to every client that is currently connected
- for client := range clients {
- if msg.IsPublic{
- if msg.Session == clientId[client]{
- err := client.WriteJSON(msg)
- if err != nil {
- log.Printf("error: %v", err)
- client.Close()
- delete(clients, client)
- }
- }
- }else{
- log.Println(msg.Task["owner"])
- if msg.Session == clientId[client] && fmt.Sprintf("%v", msg.Task["owner"]) == clientUser[client]{
- err := client.WriteJSON(msg)
- if err != nil {
- log.Printf("error: %v", err)
- client.Close()
- delete(clients, client)
- }
- }
- }
-
- }
- }
- }