wrapper.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package wrapper
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "golang-fave/engine/basket"
  14. "golang-fave/engine/cblocks"
  15. "golang-fave/engine/config"
  16. "golang-fave/engine/consts"
  17. "golang-fave/engine/logger"
  18. "golang-fave/engine/mysqlpool"
  19. "golang-fave/engine/sqlw"
  20. "golang-fave/engine/utils"
  21. "github.com/vladimirok5959/golang-server-sessions/session"
  22. )
  23. type Tx = sqlw.Tx
  24. var ErrNoRows = sqlw.ErrNoRows
  25. type Wrapper struct {
  26. l *logger.Logger
  27. W http.ResponseWriter
  28. R *http.Request
  29. S *session.Session
  30. c *cblocks.CacheBlocks
  31. Host string
  32. Port string
  33. CurrHost string
  34. DConfig string
  35. DHtdocs string
  36. DLogs string
  37. DTemplate string
  38. DTmp string
  39. IsBackend bool
  40. ConfMysqlExists bool
  41. UrlArgs []string
  42. CurrModule string
  43. CurrSubModule string
  44. MSPool *mysqlpool.MySqlPool
  45. ShopBasket *basket.Basket
  46. Config *config.Config
  47. DB *sqlw.DB
  48. User *utils.MySql_user
  49. ShopAllCurrencies *map[int]utils.MySql_shop_currency
  50. }
  51. func New(l *logger.Logger, w http.ResponseWriter, r *http.Request, s *session.Session, c *cblocks.CacheBlocks, host, port, chost, dirConfig, dirHtdocs, dirLogs, dirTemplate, dirTmp string, mp *mysqlpool.MySqlPool, sb *basket.Basket) *Wrapper {
  52. conf := config.ConfigNew()
  53. if err := conf.ConfigRead(dirConfig + string(os.PathSeparator) + "config.json"); err != nil {
  54. l.Log("Host config file: %s", r, true, err.Error())
  55. }
  56. return &Wrapper{
  57. l: l,
  58. W: w,
  59. R: r,
  60. S: s,
  61. c: c,
  62. Host: host,
  63. Port: port,
  64. CurrHost: chost,
  65. DConfig: dirConfig,
  66. DHtdocs: dirHtdocs,
  67. DLogs: dirLogs,
  68. DTemplate: dirTemplate,
  69. DTmp: dirTmp,
  70. UrlArgs: []string{},
  71. CurrModule: "",
  72. CurrSubModule: "",
  73. MSPool: mp,
  74. ShopBasket: sb,
  75. Config: conf,
  76. }
  77. }
  78. func (this *Wrapper) LogAccess(msg string, vars ...interface{}) {
  79. this.l.Log(msg, this.R, false, vars...)
  80. }
  81. func (this *Wrapper) LogError(msg string, vars ...interface{}) {
  82. this.l.Log(msg, this.R, true, vars...)
  83. }
  84. func (this *Wrapper) LogCpError(err *error) *error {
  85. if *err != nil {
  86. this.LogError("%s", *err)
  87. }
  88. return err
  89. }
  90. func (this *Wrapper) dbReconnect() error {
  91. if !utils.IsMySqlConfigExists(this.DConfig + string(os.PathSeparator) + "mysql.json") {
  92. return errors.New("can't read database configuration file")
  93. }
  94. mc, err := utils.MySqlConfigRead(this.DConfig + string(os.PathSeparator) + "mysql.json")
  95. if err != nil {
  96. return err
  97. }
  98. this.DB, err = sqlw.Open("mysql", mc.User+":"+mc.Password+"@tcp("+mc.Host+":"+mc.Port+")/"+mc.Name)
  99. if err != nil {
  100. return err
  101. }
  102. // Max 60 minutes and max 8 connection per host
  103. this.DB.SetConnMaxLifetime(time.Minute * 60)
  104. this.DB.SetMaxIdleConns(8)
  105. this.DB.SetMaxOpenConns(8)
  106. this.MSPool.Set(this.CurrHost, this.DB)
  107. return nil
  108. }
  109. func (this *Wrapper) UseDatabase() error {
  110. this.DB = this.MSPool.Get(this.CurrHost)
  111. if this.DB == nil {
  112. if err := this.dbReconnect(); err != nil {
  113. return err
  114. }
  115. }
  116. if err := this.DB.Ping(this.R.Context()); err != nil {
  117. this.DB.Close()
  118. if err := this.dbReconnect(); err != nil {
  119. return err
  120. } else {
  121. if err := this.DB.Ping(this.R.Context()); err != nil {
  122. this.DB.Close()
  123. this.MSPool.Del(this.CurrHost)
  124. return err
  125. }
  126. }
  127. }
  128. return nil
  129. }
  130. func (this *Wrapper) LoadSessionUser() bool {
  131. if this.S.GetInt("UserId", 0) <= 0 {
  132. return false
  133. }
  134. if this.DB == nil {
  135. return false
  136. }
  137. user := &utils.MySql_user{}
  138. err := this.DB.QueryRow(
  139. this.R.Context(),
  140. `SELECT
  141. id,
  142. first_name,
  143. last_name,
  144. email,
  145. password,
  146. admin,
  147. active
  148. FROM
  149. fave_users
  150. WHERE
  151. id = ?
  152. LIMIT 1;`,
  153. this.S.GetInt("UserId", 0),
  154. ).Scan(
  155. &user.A_id,
  156. &user.A_first_name,
  157. &user.A_last_name,
  158. &user.A_email,
  159. &user.A_password,
  160. &user.A_admin,
  161. &user.A_active,
  162. )
  163. if *this.LogCpError(&err) != nil {
  164. return false
  165. }
  166. if user.A_id != this.S.GetInt("UserId", 0) {
  167. return false
  168. }
  169. this.User = user
  170. return true
  171. }
  172. func (this *Wrapper) Write(data string) {
  173. // TODO: select context and don't write
  174. this.W.Write([]byte(data))
  175. }
  176. func (this *Wrapper) MsgSuccess(msg string) {
  177. // TODO: select context and don't write
  178. this.Write(fmt.Sprintf(
  179. `fave.ShowMsgSuccess('Success!', '%s', false);`,
  180. utils.JavaScriptVarValue(msg)))
  181. }
  182. func (this *Wrapper) MsgError(msg string) {
  183. // TODO: select context and don't write
  184. this.Write(fmt.Sprintf(
  185. `fave.ShowMsgError('Error!', '%s', true);`,
  186. utils.JavaScriptVarValue(msg)))
  187. }
  188. func (this *Wrapper) RenderToString(tcont []byte, data interface{}) string {
  189. tmpl, err := template.New("template").Parse(string(tcont))
  190. if err != nil {
  191. return err.Error()
  192. }
  193. var tpl bytes.Buffer
  194. if err := tmpl.Execute(&tpl, data); err != nil {
  195. return err.Error()
  196. }
  197. return tpl.String()
  198. }
  199. func (this *Wrapper) RenderFrontEnd(tname string, data interface{}, status int) {
  200. tmpl, err := template.New(tname+".html").Funcs(utils.TemplateAdditionalFuncs()).ParseFiles(
  201. this.DTemplate+string(os.PathSeparator)+tname+".html",
  202. this.DTemplate+string(os.PathSeparator)+"header.html",
  203. this.DTemplate+string(os.PathSeparator)+"sidebar-left.html",
  204. this.DTemplate+string(os.PathSeparator)+"sidebar-right.html",
  205. this.DTemplate+string(os.PathSeparator)+"footer.html",
  206. )
  207. if err != nil {
  208. utils.SystemErrorPageTemplate(this.W, err)
  209. return
  210. }
  211. var tpl bytes.Buffer
  212. err = tmpl.Execute(&tpl, consts.TmplData{
  213. System: utils.GetTmplSystemData("", ""),
  214. Data: data,
  215. })
  216. if err != nil {
  217. utils.SystemErrorPageTemplate(this.W, err)
  218. return
  219. }
  220. this.W.WriteHeader(status)
  221. this.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  222. this.W.Header().Set("Content-Type", "text/html; charset=utf-8")
  223. this.W.Write(tpl.Bytes())
  224. }
  225. func (this *Wrapper) RenderBackEnd(tcont []byte, data interface{}) {
  226. tmpl, err := template.New("template").Parse(string(tcont))
  227. if err != nil {
  228. utils.SystemErrorPageEngine(this.W, err)
  229. return
  230. }
  231. this.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  232. this.W.Header().Set("Content-Type", "text/html; charset=utf-8")
  233. var tpl bytes.Buffer
  234. err = tmpl.Execute(this.W, consts.TmplData{
  235. System: utils.GetTmplSystemData(this.CurrModule, this.CurrSubModule),
  236. Data: data,
  237. })
  238. if err != nil {
  239. utils.SystemErrorPageEngine(this.W, err)
  240. return
  241. }
  242. this.W.Write(tpl.Bytes())
  243. }
  244. func (this *Wrapper) GetCurrentPage(max int) int {
  245. curr := 1
  246. page := this.R.URL.Query().Get("p")
  247. if page != "" {
  248. if i, err := strconv.Atoi(page); err == nil {
  249. if i < 1 {
  250. curr = 1
  251. } else if i > max {
  252. curr = max
  253. } else {
  254. curr = i
  255. }
  256. }
  257. }
  258. return curr
  259. }
  260. func (this *Wrapper) ConfigSave() error {
  261. return this.Config.ConfigWrite(this.DConfig + string(os.PathSeparator) + "config.json")
  262. }
  263. func (this *Wrapper) SendEmailUsual(email, subject, message string) error {
  264. if (*this.Config).SMTP.Host == "" || (*this.Config).SMTP.Login == "" || (*this.Config).SMTP.Password == "" {
  265. return errors.New("SMTP server is not configured")
  266. }
  267. err := utils.SMTPSend(
  268. (*this.Config).SMTP.Host,
  269. utils.IntToStr((*this.Config).SMTP.Port),
  270. (*this.Config).SMTP.Login,
  271. (*this.Config).SMTP.Password,
  272. subject,
  273. message,
  274. []string{email},
  275. )
  276. status := 1
  277. emessage := ""
  278. if err != nil {
  279. status = 0
  280. emessage = err.Error()
  281. }
  282. if _, err := this.DB.Exec(
  283. this.R.Context(),
  284. `INSERT INTO fave_notify_mail SET
  285. id = NULL,
  286. email = ?,
  287. subject = ?,
  288. message = ?,
  289. error = ?,
  290. datetime = ?,
  291. status = ?
  292. ;`,
  293. email,
  294. subject,
  295. message,
  296. emessage,
  297. utils.UnixTimestampToMySqlDateTime(utils.GetCurrentUnixTimestamp()),
  298. status,
  299. ); err != nil {
  300. this.LogCpError(&err)
  301. }
  302. return err
  303. }
  304. func (this *Wrapper) SendEmailFast(email, subject, message string) error {
  305. status := 2
  306. emessage := ""
  307. if (*this.Config).SMTP.Host == "" || (*this.Config).SMTP.Login == "" || (*this.Config).SMTP.Password == "" {
  308. status = 0
  309. emessage = "SMTP server is not configured"
  310. }
  311. if _, err := this.DB.Exec(
  312. this.R.Context(),
  313. `INSERT INTO fave_notify_mail SET
  314. id = NULL,
  315. email = ?,
  316. subject = ?,
  317. message = ?,
  318. error = ?,
  319. datetime = ?,
  320. status = ?
  321. ;`,
  322. email,
  323. subject,
  324. message,
  325. emessage,
  326. utils.UnixTimestampToMySqlDateTime(utils.GetCurrentUnixTimestamp()),
  327. status,
  328. ); err != nil {
  329. return err
  330. }
  331. return nil
  332. }
  333. func (this *Wrapper) SendEmailTemplated(email, subject, tname string, data interface{}) error {
  334. tmpl, err := template.New(tname + ".html").Funcs(utils.TemplateAdditionalFuncs()).ParseFiles(
  335. this.DTemplate + string(os.PathSeparator) + tname + ".html",
  336. )
  337. if err != nil {
  338. return err
  339. }
  340. var tpl bytes.Buffer
  341. err = tmpl.Execute(&tpl, data)
  342. if err != nil {
  343. return err
  344. }
  345. return this.SendEmailFast(email, subject, string(tpl.Bytes()))
  346. }
  347. func (this *Wrapper) GetSessionId() string {
  348. cookie, err := this.R.Cookie("session")
  349. if err == nil && len(cookie.Value) == 40 {
  350. return cookie.Value
  351. }
  352. return ""
  353. }
  354. func (this *Wrapper) RecreateProductXmlFile() error {
  355. trigger := strings.Join([]string{this.DTmp, "trigger.xml.run"}, string(os.PathSeparator))
  356. if !utils.IsFileExists(trigger) {
  357. if _, err := os.Create(trigger); err != nil {
  358. return err
  359. }
  360. }
  361. return nil
  362. }
  363. func (this *Wrapper) RecreateProductImgFiles() error {
  364. trigger := strings.Join([]string{this.DTmp, "trigger.img.run"}, string(os.PathSeparator))
  365. if !utils.IsFileExists(trigger) {
  366. if _, err := os.Create(trigger); err != nil {
  367. return err
  368. }
  369. }
  370. return nil
  371. }
  372. func (this *Wrapper) RemoveProductImageThumbnails(product_id, filename string) error {
  373. pattern := this.DHtdocs + string(os.PathSeparator) + strings.Join([]string{"products", "images", product_id, filename}, string(os.PathSeparator))
  374. if files, err := filepath.Glob(pattern); err != nil {
  375. return err
  376. } else {
  377. // TODO: select context and don't do that
  378. for _, file := range files {
  379. if err := os.Remove(file); err != nil {
  380. return errors.New(fmt.Sprintf("[upload delete] Thumbnail file (%s) delete error: %s", file, err.Error()))
  381. }
  382. }
  383. }
  384. return this.RecreateProductImgFiles()
  385. }
  386. func (this *Wrapper) ShopGetAllCurrencies() *map[int]utils.MySql_shop_currency {
  387. if this.ShopAllCurrencies == nil {
  388. this.ShopAllCurrencies = &map[int]utils.MySql_shop_currency{}
  389. if rows, err := this.DB.Query(
  390. this.R.Context(),
  391. `SELECT
  392. id,
  393. name,
  394. coefficient,
  395. code,
  396. symbol
  397. FROM
  398. fave_shop_currencies
  399. ORDER BY
  400. id ASC
  401. ;`,
  402. ); err == nil {
  403. defer rows.Close()
  404. for rows.Next() {
  405. row := utils.MySql_shop_currency{}
  406. if err = rows.Scan(
  407. &row.A_id,
  408. &row.A_name,
  409. &row.A_coefficient,
  410. &row.A_code,
  411. &row.A_symbol,
  412. ); err == nil {
  413. (*this.ShopAllCurrencies)[row.A_id] = row
  414. }
  415. }
  416. }
  417. }
  418. return this.ShopAllCurrencies
  419. }
  420. func (this *Wrapper) ShopGetCurrentCurrency() *utils.MySql_shop_currency {
  421. currency_id := 1
  422. if cookie, err := this.R.Cookie("currency"); err == nil {
  423. currency_id = utils.StrToInt(cookie.Value)
  424. }
  425. if _, ok := (*this.ShopGetAllCurrencies())[currency_id]; ok != true {
  426. currency_id = 1
  427. }
  428. if p, ok := (*this.ShopGetAllCurrencies())[currency_id]; ok == true {
  429. return &p
  430. }
  431. return nil
  432. }