connector.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. package main
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. _ "github.com/go-sql-driver/mysql"
  9. )
  10. type ConnectionProperties struct {
  11. User string
  12. Pass string
  13. Host string
  14. Db string
  15. }
  16. type connection struct {
  17. dBOpenStr string
  18. connProperties ConnectionProperties
  19. }
  20. type Torrent struct {
  21. ID int64
  22. Hash string
  23. Name string
  24. OwnerID string
  25. Time string
  26. Deleted bool
  27. }
  28. func (c *connection) Init(filepath string) {
  29. if NOMYSQL {
  30. return
  31. }
  32. b, err := ioutil.ReadFile(filepath)
  33. if err != nil {
  34. fmt.Print(err)
  35. }
  36. propJson := string(b)
  37. json.Unmarshal([]byte(propJson), &c.connProperties)
  38. //c.connProperties.Db = "nosite"
  39. fmt.Printf("Connection data:\n%s\n%s\n%s\n%s\n", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
  40. c.dBOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/%s", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
  41. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  42. db, err := sql.Open("mysql", c.dBOpenStr)
  43. if err != nil {
  44. panic(err)
  45. }
  46. if err = db.Ping(); err != nil {
  47. db.Close()
  48. logger.Println("Fatal : Error with connection to database!")
  49. } else {
  50. fmt.Println("Connection succesfull!")
  51. return
  52. }
  53. logger.Print("Trying to connect to DB-server...")
  54. c.dBOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host)
  55. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  56. db, err = sql.Open("mysql", c.dBOpenStr)
  57. if err != nil {
  58. panic(err)
  59. }
  60. if err = db.Ping(); err != nil {
  61. db.Close()
  62. logger.Print("Fatal : Error with connection to database server!")
  63. return
  64. } else {
  65. }
  66. c.databaseInitialization()
  67. }
  68. /* создает на сервере необходимую бд и таблицы */
  69. func (c *connection) databaseInitialization() {
  70. db, err := sql.Open("mysql", c.dBOpenStr)
  71. if err != nil {
  72. panic(err)
  73. }
  74. defer db.Close()
  75. var counter int
  76. var act_query string
  77. logger.Printf("Checking for existence of database '%s' on server...", c.connProperties.Db)
  78. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  79. db.QueryRow(act_query).Scan(&counter)
  80. fmt.Print(counter)
  81. if counter != 0 {
  82. logger.Print("Server already has the specified database")
  83. } else {
  84. logger.Print("The server does not have the specified database")
  85. logger.Printf("Creating database '%s'...", c.connProperties.Db)
  86. act_query = "CREATE SCHEMA " + c.connProperties.Db + " DEFAULT CHARACTER SET utf8 ;"
  87. result, err := db.Exec(act_query)
  88. if err != nil {
  89. panic(err)
  90. }
  91. rowsCount, _ := result.RowsAffected()
  92. fmt.Printf("Lines changed: %d\n", rowsCount)
  93. if rowsCount == 1 {
  94. logger.Print("Succesfull!")
  95. }
  96. }
  97. logger.Print("Checking for existence of table 'users' on server...")
  98. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_NAME = 'users' AND TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  99. db.QueryRow(act_query).Scan(&counter)
  100. fmt.Print(counter)
  101. if counter != 0 {
  102. logger.Print("Server already has the specified table!")
  103. } else {
  104. logger.Print("The server does not have the specified table")
  105. logger.Printf("Creating table '%s'.'users'...", c.connProperties.Db)
  106. act_query = "CREATE TABLE `" + c.connProperties.Db + "`.`users` ( `idusers` INT NOT NULL AUTO_INCREMENT,`username` VARCHAR(45) NOT NULL, `password` VARCHAR(45) NOT NULL, PRIMARY KEY(`idusers`), UNIQUE INDEX `idusers_UNIQUE` (`idusers` ASC), UNIQUE INDEX `username_UNIQUE` (`username` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 ;"
  107. fmt.Print(act_query)
  108. _, err := db.Exec(act_query)
  109. if err != nil {
  110. panic(err)
  111. }
  112. logger.Print("Succesfull!")
  113. }
  114. /*
  115. CREATE TABLE `gosite`.`torrents` (
  116. `id` INT NOT NULL AUTO_INCREMENT,
  117. `hash` VARCHAR(45) NOT NULL,
  118. `name` VARCHAR(45) NOT NULL,
  119. `ownerid` VARCHAR(45) NOT NULL,
  120. `time` TIMESTAMP NOT NULL,
  121. `deleted` TINYINT NULL,
  122. UNIQUE INDEX `idtorrents_UNIQUE` (`id` ASC) VISIBLE,
  123. PRIMARY KEY (`hash`),
  124. UNIQUE INDEX `hash_UNIQUE` (`hash` ASC) VISIBLE);
  125. */
  126. }
  127. func (c connection) LogIn(username string, password string) bool {
  128. fmt.Printf("\n\nLogIn\nConnecting with:\n%s\n", c.dBOpenStr)
  129. db, err := sql.Open("mysql", c.dBOpenStr)
  130. if err != nil {
  131. panic(err)
  132. }
  133. defer db.Close()
  134. var counter int
  135. //fmt.Printf("%s\n%s\n", username, password)
  136. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s' AND password=SHA('%s');", c.connProperties.Db, username, password)
  137. db.QueryRow(act_query).Scan(&counter)
  138. fmt.Println("we have", counter, "rows")
  139. if counter == 0 {
  140. return false
  141. }
  142. return true
  143. }
  144. func (c connection) IsNameUsed(username string) bool {
  145. db, err := sql.Open("mysql", c.dBOpenStr)
  146. if err != nil {
  147. panic(err)
  148. }
  149. defer db.Close()
  150. var counter int
  151. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s';", c.connProperties.Db, username)
  152. db.QueryRow(act_query).Scan(&counter)
  153. if counter == 0 {
  154. fmt.Printf("Username unused\n")
  155. return false
  156. }
  157. fmt.Printf("Username used\n")
  158. return true
  159. }
  160. func (c connection) SigInUser(username string, password string) bool {
  161. db, err := sql.Open("mysql", c.dBOpenStr)
  162. if err != nil {
  163. panic(err)
  164. }
  165. defer db.Close()
  166. act_query := fmt.Sprintf("INSERT INTO %s.users (username, password) VALUES ('%s', SHA('%s'))", c.connProperties.Db, username, password)
  167. result, err := db.Exec(act_query)
  168. if err != nil {
  169. panic(err)
  170. }
  171. rowsCount, _ := result.RowsAffected()
  172. if rowsCount == 1 {
  173. fmt.Printf("Lines changed: %d\n", rowsCount)
  174. return true
  175. } else {
  176. return false
  177. }
  178. }
  179. func (c connection) SubmitScore(score int) {
  180. fmt.Printf("Submiting score %d", score)
  181. }
  182. func (c connection) TakeTorrent(hash string) (Torrent, error) {
  183. db, err := sql.Open("mysql", c.dBOpenStr)
  184. if err != nil {
  185. panic(err)
  186. }
  187. defer db.Close()
  188. act_query := fmt.Sprintf("SELECT * FROM `%s`.`torrents` WHERE `hash`='%s'", c.connProperties.Db, hash)
  189. fmt.Println(act_query)
  190. rows, err := db.Query(act_query)
  191. if err != nil {
  192. panic(err)
  193. }
  194. defer rows.Close()
  195. var torrent Torrent
  196. for rows.Next() {
  197. if err := rows.Scan(
  198. &torrent.ID,
  199. &torrent.Hash,
  200. &torrent.Name,
  201. &torrent.OwnerID,
  202. &torrent.Time,
  203. &torrent.Deleted,
  204. ); err != nil {
  205. log.Fatal(err)
  206. }
  207. fmt.Println(torrent)
  208. return torrent, nil
  209. }
  210. return torrent, fmt.Errorf("Torrent not found")
  211. }
  212. /*
  213. func main() {
  214. var dBConnector connection
  215. dBConnector.Init("config.json")
  216. if (dBConnector.LogIn("Alex", "09Alex09")) {
  217. fmt.Printf("Succesfull logIn\n")
  218. } else {
  219. fmt.Printf("logIn error\n")
  220. }
  221. if (dBConnector.LogIn("Alax", "09Alex09")) {
  222. fmt.Printf("Succesfull logIn\n")
  223. } else {
  224. fmt.Printf("logIn error\n")
  225. }
  226. }
  227. */