connector.go 13 KB

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