connector.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package main
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "io/ioutil"
  8. "log"
  9. _ "github.com/go-sql-driver/mysql"
  10. )
  11. type ConnectionProperties struct {
  12. User string
  13. Pass string
  14. Host string
  15. Db string
  16. }
  17. type connection struct {
  18. dBOpenStr string
  19. connProperties ConnectionProperties
  20. }
  21. type Torrent struct {
  22. ID int64
  23. Hash string
  24. Name string
  25. OwnerID string
  26. Time string
  27. Deleted bool
  28. }
  29. func (c *connection) Init(filepath string) {
  30. if NOMYSQL {
  31. return
  32. }
  33. b, err := ioutil.ReadFile(filepath)
  34. if err != nil {
  35. fmt.Print(err)
  36. }
  37. propJson := string(b)
  38. json.Unmarshal([]byte(propJson), &c.connProperties)
  39. //c.connProperties.Db = "nosite"
  40. 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)
  41. c.dBOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/%s", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
  42. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  43. db, err := sql.Open("mysql", c.dBOpenStr)
  44. if err != nil {
  45. panic(err)
  46. }
  47. if err = db.Ping(); err != nil {
  48. db.Close()
  49. logger.Println("Fatal : Error with connection to database!")
  50. } else {
  51. fmt.Println("Connection succesfull!")
  52. return
  53. }
  54. logger.Print("Trying to connect to DB-server...")
  55. c.dBOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host)
  56. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  57. db, err = sql.Open("mysql", c.dBOpenStr)
  58. if err != nil {
  59. panic(err)
  60. }
  61. if err = db.Ping(); err != nil {
  62. db.Close()
  63. logger.Print("Fatal : Error with connection to database server!")
  64. return
  65. } else {
  66. }
  67. c.databaseInitialization()
  68. }
  69. /* создает на сервере необходимую бд и таблицы */
  70. func (c *connection) databaseInitialization() {
  71. db, err := sql.Open("mysql", c.dBOpenStr)
  72. if err != nil {
  73. panic(err)
  74. }
  75. defer db.Close()
  76. var counter int
  77. var act_query string
  78. logger.Printf("Checking for existence of database '%s' on server...", c.connProperties.Db)
  79. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  80. db.QueryRow(act_query).Scan(&counter)
  81. fmt.Print(counter)
  82. if counter != 0 {
  83. logger.Print("Server already has the specified database")
  84. } else {
  85. logger.Print("The server does not have the specified database")
  86. logger.Printf("Creating database '%s'...", c.connProperties.Db)
  87. act_query = "CREATE SCHEMA " + c.connProperties.Db + " DEFAULT CHARACTER SET utf8 ;"
  88. result, err := db.Exec(act_query)
  89. if err != nil {
  90. panic(err)
  91. }
  92. rowsCount, _ := result.RowsAffected()
  93. fmt.Printf("Lines changed: %d\n", rowsCount)
  94. if rowsCount == 1 {
  95. logger.Print("Succesfull!")
  96. }
  97. }
  98. logger.Print("Checking for existence of table 'users' on server...")
  99. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_NAME = 'users' AND TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  100. db.QueryRow(act_query).Scan(&counter)
  101. fmt.Print(counter)
  102. if counter != 0 {
  103. logger.Print("Server already has the specified table!")
  104. } else {
  105. logger.Print("The server does not have the specified table")
  106. logger.Printf("Creating table '%s'.'users'...", c.connProperties.Db)
  107. 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 ;"
  108. fmt.Print(act_query)
  109. _, err := db.Exec(act_query)
  110. if err != nil {
  111. panic(err)
  112. }
  113. logger.Print("Succesfull!")
  114. }
  115. /*
  116. CREATE TABLE `gosite`.`torrents` (
  117. `id` INT NOT NULL AUTO_INCREMENT,
  118. `hash` VARCHAR(45) NOT NULL,
  119. `name` VARCHAR(45) NOT NULL,
  120. `ownerid` VARCHAR(45) NOT NULL,
  121. `time` TIMESTAMP NOT NULL,
  122. `deleted` TINYINT NULL,
  123. UNIQUE INDEX `idtorrents_UNIQUE` (`id` ASC) VISIBLE,
  124. PRIMARY KEY (`hash`),
  125. UNIQUE INDEX `hash_UNIQUE` (`hash` ASC) VISIBLE);
  126. */
  127. }
  128. func (c connection) LogIn(username string, password string) bool {
  129. fmt.Printf("\n\nLogIn\nConnecting with:\n%s\n", c.dBOpenStr)
  130. db, err := sql.Open("mysql", c.dBOpenStr)
  131. if err != nil {
  132. panic(err)
  133. }
  134. defer db.Close()
  135. var counter int
  136. //fmt.Printf("%s\n%s\n", username, password)
  137. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s' AND password=SHA('%s');", c.connProperties.Db, username, password)
  138. db.QueryRow(act_query).Scan(&counter)
  139. fmt.Println("we have", counter, "rows")
  140. if counter == 0 {
  141. return false
  142. }
  143. return true
  144. }
  145. func (c connection) IsNameUsed(username string) bool {
  146. db, err := sql.Open("mysql", c.dBOpenStr)
  147. if err != nil {
  148. panic(err)
  149. }
  150. defer db.Close()
  151. var counter int
  152. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s';", c.connProperties.Db, username)
  153. db.QueryRow(act_query).Scan(&counter)
  154. if counter == 0 {
  155. fmt.Printf("Username unused\n")
  156. return false
  157. }
  158. fmt.Printf("Username used\n")
  159. return true
  160. }
  161. func (c connection) SigInUser(username string, password string) bool {
  162. db, err := sql.Open("mysql", c.dBOpenStr)
  163. if err != nil {
  164. panic(err)
  165. }
  166. defer db.Close()
  167. act_query := fmt.Sprintf("INSERT INTO %s.users (username, password) VALUES ('%s', SHA('%s'))", c.connProperties.Db, username, password)
  168. result, err := db.Exec(act_query)
  169. if err != nil {
  170. panic(err)
  171. }
  172. rowsCount, _ := result.RowsAffected()
  173. if rowsCount == 1 {
  174. fmt.Printf("Lines changed: %d\n", rowsCount)
  175. return true
  176. } else {
  177. return false
  178. }
  179. }
  180. func (c connection) SubmitScore(score int) {
  181. fmt.Printf("Submiting score %d", score)
  182. }
  183. func (c connection) TakeTorrent(hash string) (Torrent, error) {
  184. db, err := sql.Open("mysql", c.dBOpenStr)
  185. if err != nil {
  186. panic(err)
  187. }
  188. defer db.Close()
  189. act_query := fmt.Sprintf("SELECT * FROM `%s`.`torrents` WHERE `hash`='%s'", c.connProperties.Db, hash)
  190. fmt.Println(act_query)
  191. rows, err := db.Query(act_query)
  192. if err != nil {
  193. panic(err)
  194. }
  195. defer rows.Close()
  196. var torrent Torrent
  197. for rows.Next() {
  198. if err := rows.Scan(
  199. &torrent.ID,
  200. &torrent.Hash,
  201. &torrent.Name,
  202. &torrent.OwnerID,
  203. &torrent.Time,
  204. &torrent.Deleted,
  205. ); err != nil {
  206. log.Fatal(err)
  207. }
  208. fmt.Println(torrent)
  209. return torrent, nil
  210. }
  211. return torrent, fmt.Errorf("Torrent not found")
  212. }
  213. // Takes 'amount' latest torrents in order of Time desc
  214. // (torrents[0] is a newest)
  215. // If amount is 0 returns all torrents in same order as usual
  216. func (c connection) GetLastTorrents(amount int64) (torrents []Torrent, count int64, err error) {
  217. db, err := sql.Open("mysql", c.dBOpenStr)
  218. if err != nil {
  219. return
  220. }
  221. defer db.Close()
  222. var act_query string
  223. act_query = fmt.Sprintf("SELECT * FROM `%s`.`torrents`", c.connProperties.Db)
  224. act_query += " ORDER BY `time` DESC"
  225. if amount != 0 {
  226. act_query += fmt.Sprintf(" LIMIT %d", amount)
  227. }
  228. fmt.Println(act_query)
  229. rows, err := db.Query(act_query)
  230. if err != nil {
  231. return
  232. }
  233. defer rows.Close()
  234. for rows.Next() {
  235. var torrent Torrent
  236. if err := rows.Scan(
  237. &torrent.ID,
  238. &torrent.Hash,
  239. &torrent.Name,
  240. &torrent.OwnerID,
  241. &torrent.Time,
  242. &torrent.Deleted,
  243. ); err != nil {
  244. log.Fatal(err)
  245. }
  246. torrents = append(torrents, torrent)
  247. count++
  248. }
  249. return
  250. }
  251. // Takes 'amount' latest news for headline in order of Time desc
  252. // (news[0] is a newest)
  253. // If amount is 0 returns all news in same order as usual
  254. func (c connection) GetLastNews(amount int64) (news []NewsItem, count int64, err error) {
  255. newsTopicUuid := "557adf6b-6988-4dfe-89d1-85e56947e067"
  256. db, err := sql.Open("mysql", c.dBOpenStr)
  257. if err != nil {
  258. return
  259. }
  260. defer db.Close()
  261. var act_query string
  262. act_query = fmt.Sprintf("SELECT text, users.username, msg.time FROM %s.messages as msg INNER JOIN %s.folders as folders ON msg.parent_uuid = folders.uuid INNER JOIN %s.users as users ON msg.author = users.idusers WHERE folders.parent_uuid = '%s' ORDER BY msg.time DESC", c.connProperties.Db, c.connProperties.Db, c.connProperties.Db, newsTopicUuid)
  263. if amount != 0 {
  264. act_query += fmt.Sprintf(" LIMIT %d", amount)
  265. }
  266. fmt.Println(act_query)
  267. rows, err := db.Query(act_query)
  268. if err != nil {
  269. return
  270. }
  271. defer rows.Close()
  272. for rows.Next() {
  273. var templateStr string
  274. var item NewsItem
  275. if err := rows.Scan(
  276. &templateStr,
  277. &item.Author,
  278. &item.Time,
  279. ); err != nil {
  280. log.Fatal(err)
  281. }
  282. item.NewsText = template.HTML(templateStr)
  283. news = append(news, item)
  284. count++
  285. }
  286. return
  287. }
  288. /*
  289. func main() {
  290. var dBConnector connection
  291. dBConnector.Init("config.json")
  292. if (dBConnector.LogIn("Alex", "09Alex09")) {
  293. fmt.Printf("Succesfull logIn\n")
  294. } else {
  295. fmt.Printf("logIn error\n")
  296. }
  297. if (dBConnector.LogIn("Alax", "09Alex09")) {
  298. fmt.Printf("Succesfull logIn\n")
  299. } else {
  300. fmt.Printf("logIn error\n")
  301. }
  302. }
  303. */