connector.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. type Folder struct {
  30. Uuid string
  31. ParentUuid string
  32. Type int
  33. Title string
  34. Snake string
  35. }
  36. type ForumMessage struct {
  37. Author string
  38. Time string
  39. Text string
  40. }
  41. func (c *connection) Init(filepath string) {
  42. if NOMYSQL {
  43. return
  44. }
  45. b, err := ioutil.ReadFile(filepath)
  46. if err != nil {
  47. fmt.Print(err)
  48. }
  49. propJson := string(b)
  50. json.Unmarshal([]byte(propJson), &c.connProperties)
  51. //c.connProperties.Db = "nosite"
  52. 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)
  53. c.dBOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/%s", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
  54. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  55. db, err := sql.Open("mysql", c.dBOpenStr)
  56. if err != nil {
  57. panic(err)
  58. }
  59. if err = db.Ping(); err != nil {
  60. db.Close()
  61. logger.Println("Fatal : Error with connection to database!")
  62. } else {
  63. fmt.Println("Connection succesfull!")
  64. return
  65. }
  66. logger.Print("Trying to connect to DB-server...")
  67. c.dBOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host)
  68. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  69. db, err = sql.Open("mysql", c.dBOpenStr)
  70. if err != nil {
  71. panic(err)
  72. }
  73. if err = db.Ping(); err != nil {
  74. db.Close()
  75. logger.Print("Fatal : Error with connection to database server!")
  76. return
  77. } else {
  78. }
  79. c.databaseInitialization()
  80. }
  81. /* создает на сервере необходимую бд и таблицы */
  82. func (c *connection) databaseInitialization() {
  83. db, err := sql.Open("mysql", c.dBOpenStr)
  84. if err != nil {
  85. panic(err)
  86. }
  87. defer db.Close()
  88. var counter int
  89. var act_query string
  90. logger.Printf("Checking for existence of database '%s' on server...", c.connProperties.Db)
  91. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  92. db.QueryRow(act_query).Scan(&counter)
  93. fmt.Print(counter)
  94. if counter != 0 {
  95. logger.Print("Server already has the specified database")
  96. } else {
  97. logger.Print("The server does not have the specified database")
  98. logger.Printf("Creating database '%s'...", c.connProperties.Db)
  99. act_query = "CREATE SCHEMA " + c.connProperties.Db + " DEFAULT CHARACTER SET utf8 ;"
  100. result, err := db.Exec(act_query)
  101. if err != nil {
  102. panic(err)
  103. }
  104. rowsCount, _ := result.RowsAffected()
  105. fmt.Printf("Lines changed: %d\n", rowsCount)
  106. if rowsCount == 1 {
  107. logger.Print("Succesfull!")
  108. }
  109. }
  110. logger.Print("Checking for existence of table 'users' on server...")
  111. act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_NAME = 'users' AND TABLE_SCHEMA = '" + c.connProperties.Db + "';"
  112. db.QueryRow(act_query).Scan(&counter)
  113. fmt.Print(counter)
  114. if counter != 0 {
  115. logger.Print("Server already has the specified table!")
  116. } else {
  117. logger.Print("The server does not have the specified table")
  118. logger.Printf("Creating table '%s'.'users'...", c.connProperties.Db)
  119. 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 ;"
  120. fmt.Print(act_query)
  121. _, err := db.Exec(act_query)
  122. if err != nil {
  123. panic(err)
  124. }
  125. logger.Print("Succesfull!")
  126. }
  127. /*
  128. CREATE TABLE `gosite`.`torrents` (
  129. `id` INT NOT NULL AUTO_INCREMENT,
  130. `hash` VARCHAR(45) NOT NULL,
  131. `name` VARCHAR(45) NOT NULL,
  132. `ownerid` VARCHAR(45) NOT NULL,
  133. `time` TIMESTAMP NOT NULL,
  134. `deleted` TINYINT NULL,
  135. UNIQUE INDEX `idtorrents_UNIQUE` (`id` ASC) VISIBLE,
  136. PRIMARY KEY (`hash`),
  137. UNIQUE INDEX `hash_UNIQUE` (`hash` ASC) VISIBLE);
  138. */
  139. }
  140. func (c connection) LogIn(username string, password string) bool {
  141. fmt.Printf("\n\nLogIn\nConnecting with:\n%s\n", c.dBOpenStr)
  142. db, err := sql.Open("mysql", c.dBOpenStr)
  143. if err != nil {
  144. panic(err)
  145. }
  146. defer db.Close()
  147. var counter int
  148. //fmt.Printf("%s\n%s\n", username, password)
  149. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s' AND password=SHA('%s');", c.connProperties.Db, username, password)
  150. db.QueryRow(act_query).Scan(&counter)
  151. fmt.Println("we have", counter, "rows")
  152. if counter == 0 {
  153. return false
  154. }
  155. return true
  156. }
  157. func (c connection) IsNameUsed(username string) bool {
  158. db, err := sql.Open("mysql", c.dBOpenStr)
  159. if err != nil {
  160. panic(err)
  161. }
  162. defer db.Close()
  163. var counter int
  164. act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s';", c.connProperties.Db, username)
  165. db.QueryRow(act_query).Scan(&counter)
  166. if counter == 0 {
  167. fmt.Printf("Username unused\n")
  168. return false
  169. }
  170. fmt.Printf("Username used\n")
  171. return true
  172. }
  173. func (c connection) SigInUser(username string, password string) bool {
  174. db, err := sql.Open("mysql", c.dBOpenStr)
  175. if err != nil {
  176. panic(err)
  177. }
  178. defer db.Close()
  179. act_query := fmt.Sprintf("INSERT INTO %s.users (username, password) VALUES ('%s', SHA('%s'))", c.connProperties.Db, username, password)
  180. result, err := db.Exec(act_query)
  181. if err != nil {
  182. panic(err)
  183. }
  184. rowsCount, _ := result.RowsAffected()
  185. if rowsCount == 1 {
  186. fmt.Printf("Lines changed: %d\n", rowsCount)
  187. return true
  188. } else {
  189. return false
  190. }
  191. }
  192. func (c connection) SubmitScore(score int) {
  193. fmt.Printf("Submiting score %d", score)
  194. }
  195. func (c connection) TakeTorrent(hash string) (Torrent, error) {
  196. db, err := sql.Open("mysql", c.dBOpenStr)
  197. if err != nil {
  198. panic(err)
  199. }
  200. defer db.Close()
  201. act_query := fmt.Sprintf("SELECT * FROM `%s`.`torrents` WHERE `hash`='%s'", c.connProperties.Db, hash)
  202. fmt.Println(act_query)
  203. rows, err := db.Query(act_query)
  204. if err != nil {
  205. panic(err)
  206. }
  207. defer rows.Close()
  208. var torrent Torrent
  209. for rows.Next() {
  210. if err := rows.Scan(
  211. &torrent.ID,
  212. &torrent.Hash,
  213. &torrent.Name,
  214. &torrent.OwnerID,
  215. &torrent.Time,
  216. &torrent.Deleted,
  217. ); err != nil {
  218. log.Fatal(err)
  219. }
  220. fmt.Println(torrent)
  221. return torrent, nil
  222. }
  223. return torrent, fmt.Errorf("Torrent not found")
  224. }
  225. // Takes 'amount' latest torrents in order of Time desc
  226. // (torrents[0] is a newest)
  227. // If amount is 0 returns all torrents in same order as usual
  228. func (c connection) GetLastTorrents(amount int64) (torrents []Torrent, count int64, err error) {
  229. db, err := sql.Open("mysql", c.dBOpenStr)
  230. if err != nil {
  231. return
  232. }
  233. defer db.Close()
  234. var act_query string
  235. act_query = fmt.Sprintf("SELECT * FROM `%s`.`torrents`", c.connProperties.Db)
  236. act_query += " ORDER BY `time` DESC"
  237. if amount != 0 {
  238. act_query += fmt.Sprintf(" LIMIT %d", amount)
  239. }
  240. fmt.Println(act_query)
  241. rows, err := db.Query(act_query)
  242. if err != nil {
  243. return
  244. }
  245. defer rows.Close()
  246. for rows.Next() {
  247. var torrent Torrent
  248. if err := rows.Scan(
  249. &torrent.ID,
  250. &torrent.Hash,
  251. &torrent.Name,
  252. &torrent.OwnerID,
  253. &torrent.Time,
  254. &torrent.Deleted,
  255. ); err != nil {
  256. log.Fatal(err)
  257. }
  258. torrents = append(torrents, torrent)
  259. count++
  260. }
  261. return
  262. }
  263. // Takes 'amount' latest news for headline in order of Time desc
  264. // (news[0] is a newest)
  265. // If amount is 0 returns all news in same order as usual
  266. func (c connection) GetLastNews(amount int64) (news []NewsItem, count int64, err error) {
  267. newsTopicUuid := "557adf6b-6988-4dfe-89d1-85e56947e067"
  268. db, err := sql.Open("mysql", c.dBOpenStr)
  269. if err != nil {
  270. return
  271. }
  272. defer db.Close()
  273. var act_query string
  274. 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)
  275. if amount != 0 {
  276. act_query += fmt.Sprintf(" LIMIT %d", amount)
  277. }
  278. fmt.Println(act_query)
  279. rows, err := db.Query(act_query)
  280. if err != nil {
  281. return
  282. }
  283. defer rows.Close()
  284. for rows.Next() {
  285. var templateStr string
  286. var item NewsItem
  287. if err := rows.Scan(
  288. &templateStr,
  289. &item.Author,
  290. &item.Time,
  291. ); err != nil {
  292. log.Fatal(err)
  293. }
  294. item.NewsText = template.HTML(templateStr)
  295. news = append(news, item)
  296. count++
  297. }
  298. return
  299. }
  300. func (c connection) TakeChildFolders(parentUuid string, amount int64) (folders []Folder, err error){
  301. db, err := sql.Open("mysql", c.dBOpenStr)
  302. if err != nil {
  303. return
  304. }
  305. defer db.Close()
  306. var act_query string
  307. act_query = fmt.Sprintf("SELECT * FROM `%s`.`folders` as `folders`", c.connProperties.Db)
  308. act_query += fmt.Sprintf(" WHERE `folders`.`parent_uuid` = '%s'", parentUuid)
  309. act_query += " ORDER BY `id` DESC"
  310. if amount != 0 {
  311. act_query += fmt.Sprintf(" LIMIT %d", amount)
  312. }
  313. fmt.Println(act_query)
  314. rows, err := db.Query(act_query)
  315. if err != nil {
  316. return
  317. }
  318. defer rows.Close()
  319. for rows.Next() {
  320. var folder Folder
  321. var id interface{}
  322. if err := rows.Scan(
  323. &id,
  324. &folder.Uuid,
  325. &folder.ParentUuid,
  326. &folder.Type,
  327. &folder.Title,
  328. &folder.Snake,
  329. ); err != nil {
  330. log.Fatal(err)
  331. }
  332. folders = append(folders, folder)
  333. }
  334. return
  335. }
  336. func (c connection) TakeChildFolderBySnake(parentUuid string, snake string) (folder Folder, err error){
  337. db, err := sql.Open("mysql", c.dBOpenStr)
  338. if err != nil {
  339. return
  340. }
  341. defer db.Close()
  342. var act_query string
  343. act_query = fmt.Sprintf("SELECT * FROM `%s`.`folders` as `folders`", c.connProperties.Db)
  344. act_query += fmt.Sprintf(" WHERE `folders`.`parent_uuid` = '%s'", parentUuid)
  345. act_query += fmt.Sprintf(" AND `folders`.`snake` = '%s'", snake)
  346. fmt.Println(act_query)
  347. rows, err := db.Query(act_query)
  348. if err != nil {
  349. return
  350. }
  351. defer rows.Close()
  352. for rows.Next() {
  353. var id interface{}
  354. if err := rows.Scan(
  355. &id,
  356. &folder.Uuid,
  357. &folder.ParentUuid,
  358. &folder.Type,
  359. &folder.Title,
  360. &folder.Snake,
  361. ); err != nil {
  362. log.Fatal(err)
  363. }
  364. }
  365. return
  366. }
  367. func (c connection) TakeTopicMessages(parentUuid string, amount int64) (messages []ForumMessage, err error) {
  368. db, err := sql.Open("mysql", c.dBOpenStr)
  369. if err != nil {
  370. return
  371. }
  372. defer db.Close()
  373. var act_query string
  374. act_query = fmt.Sprintf("SELECT `users`.`username`, `messages`.`time`, `messages`.`text` FROM `%s`.`messages` as `messages`", c.connProperties.Db)
  375. act_query += fmt.Sprintf(" INNER JOIN `%s`.`users` as `users` ON `users`.`idusers` = `messages`.`author`", c.connProperties.Db)
  376. act_query += fmt.Sprintf(" WHERE `messages`.`parent_uuid` = '%s'", parentUuid)
  377. if amount != 0 {
  378. act_query += fmt.Sprintf(" LIMIT %d", amount)
  379. }
  380. fmt.Println(act_query)
  381. rows, err := db.Query(act_query)
  382. if err != nil {
  383. return
  384. }
  385. defer rows.Close()
  386. for rows.Next() {
  387. var message ForumMessage
  388. if err := rows.Scan(
  389. &message.Author,
  390. &message.Time,
  391. &message.Text,
  392. ); err != nil {
  393. log.Fatal(err)
  394. }
  395. messages = append(messages, message)
  396. }
  397. return
  398. }
  399. /*
  400. func main() {
  401. var dBConnector connection
  402. dBConnector.Init("config.json")
  403. if (dBConnector.LogIn("Alex", "09Alex09")) {
  404. fmt.Printf("Succesfull logIn\n")
  405. } else {
  406. fmt.Printf("logIn error\n")
  407. }
  408. if (dBConnector.LogIn("Alax", "09Alex09")) {
  409. fmt.Printf("Succesfull logIn\n")
  410. } else {
  411. fmt.Printf("logIn error\n")
  412. }
  413. }
  414. */