wrapper.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/cblocks"
  14. "golang-fave/consts"
  15. "golang-fave/engine/basket"
  16. "golang-fave/engine/mysqlpool"
  17. "golang-fave/engine/sqlw"
  18. "golang-fave/engine/wrapper/config"
  19. "golang-fave/logger"
  20. "golang-fave/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. this.MSPool.Set(this.CurrHost, this.DB)
  103. return nil
  104. }
  105. func (this *Wrapper) UseDatabase() error {
  106. this.DB = this.MSPool.Get(this.CurrHost)
  107. if this.DB == nil {
  108. if err := this.dbReconnect(); err != nil {
  109. return err
  110. }
  111. }
  112. if err := this.DB.Ping(); err != nil {
  113. this.DB.Close()
  114. if err := this.dbReconnect(); err != nil {
  115. return err
  116. }
  117. if err := this.DB.Ping(); err != nil {
  118. this.DB.Close()
  119. return err
  120. }
  121. }
  122. // Max 60 minutes and max 4 connection per host
  123. this.DB.SetConnMaxLifetime(time.Minute * 60)
  124. this.DB.SetMaxIdleConns(4)
  125. this.DB.SetMaxOpenConns(4)
  126. return nil
  127. }
  128. func (this *Wrapper) LoadSessionUser() bool {
  129. if this.S.GetInt("UserId", 0) <= 0 {
  130. return false
  131. }
  132. if this.DB == nil {
  133. return false
  134. }
  135. user := &utils.MySql_user{}
  136. err := this.DB.QueryRow(`
  137. SELECT
  138. id,
  139. first_name,
  140. last_name,
  141. email,
  142. password,
  143. admin,
  144. active
  145. FROM
  146. users
  147. WHERE
  148. id = ?
  149. LIMIT 1;`,
  150. this.S.GetInt("UserId", 0),
  151. ).Scan(
  152. &user.A_id,
  153. &user.A_first_name,
  154. &user.A_last_name,
  155. &user.A_email,
  156. &user.A_password,
  157. &user.A_admin,
  158. &user.A_active,
  159. )
  160. if *this.LogCpError(&err) != nil {
  161. return false
  162. }
  163. if user.A_id != this.S.GetInt("UserId", 0) {
  164. return false
  165. }
  166. this.User = user
  167. return true
  168. }
  169. func (this *Wrapper) Write(data string) {
  170. this.W.Write([]byte(data))
  171. }
  172. func (this *Wrapper) MsgSuccess(msg string) {
  173. this.Write(fmt.Sprintf(
  174. `fave.ShowMsgSuccess('Success!', '%s', false);`,
  175. utils.JavaScriptVarValue(msg)))
  176. }
  177. func (this *Wrapper) MsgError(msg string) {
  178. this.Write(fmt.Sprintf(
  179. `fave.ShowMsgError('Error!', '%s', true);`,
  180. utils.JavaScriptVarValue(msg)))
  181. }
  182. func (this *Wrapper) RenderToString(tcont []byte, data interface{}) string {
  183. tmpl, err := template.New("template").Parse(string(tcont))
  184. if err != nil {
  185. return err.Error()
  186. }
  187. var tpl bytes.Buffer
  188. if err := tmpl.Execute(&tpl, data); err != nil {
  189. return err.Error()
  190. }
  191. return tpl.String()
  192. }
  193. func (this *Wrapper) RenderFrontEnd(tname string, data interface{}, status int) {
  194. tmpl, err := template.New(tname+".html").Funcs(utils.TemplateAdditionalFuncs()).ParseFiles(
  195. this.DTemplate+string(os.PathSeparator)+tname+".html",
  196. this.DTemplate+string(os.PathSeparator)+"header.html",
  197. this.DTemplate+string(os.PathSeparator)+"sidebar-left.html",
  198. this.DTemplate+string(os.PathSeparator)+"sidebar-right.html",
  199. this.DTemplate+string(os.PathSeparator)+"footer.html",
  200. )
  201. if err != nil {
  202. utils.SystemErrorPageTemplate(this.W, err)
  203. return
  204. }
  205. var tpl bytes.Buffer
  206. err = tmpl.Execute(&tpl, consts.TmplData{
  207. System: utils.GetTmplSystemData("", ""),
  208. Data: data,
  209. })
  210. if err != nil {
  211. utils.SystemErrorPageTemplate(this.W, err)
  212. return
  213. }
  214. this.W.WriteHeader(status)
  215. this.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  216. this.W.Header().Set("Content-Type", "text/html; charset=utf-8")
  217. this.W.Write(tpl.Bytes())
  218. }
  219. func (this *Wrapper) RenderBackEnd(tcont []byte, data interface{}) {
  220. tmpl, err := template.New("template").Parse(string(tcont))
  221. if err != nil {
  222. utils.SystemErrorPageEngine(this.W, err)
  223. return
  224. }
  225. this.W.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  226. this.W.Header().Set("Content-Type", "text/html; charset=utf-8")
  227. var tpl bytes.Buffer
  228. err = tmpl.Execute(this.W, consts.TmplData{
  229. System: utils.GetTmplSystemData(this.CurrModule, this.CurrSubModule),
  230. Data: data,
  231. })
  232. if err != nil {
  233. utils.SystemErrorPageEngine(this.W, err)
  234. return
  235. }
  236. this.W.Write(tpl.Bytes())
  237. }
  238. func (this *Wrapper) GetCurrentPage(max int) int {
  239. curr := 1
  240. page := this.R.URL.Query().Get("p")
  241. if page != "" {
  242. if i, err := strconv.Atoi(page); err == nil {
  243. if i < 1 {
  244. curr = 1
  245. } else if i > max {
  246. curr = max
  247. } else {
  248. curr = i
  249. }
  250. }
  251. }
  252. return curr
  253. }
  254. func (this *Wrapper) ConfigSave() error {
  255. return this.Config.ConfigWrite(this.DConfig + string(os.PathSeparator) + "config.json")
  256. }
  257. func (this *Wrapper) SendEmailUsual(email, subject, message string) error {
  258. if (*this.Config).SMTP.Host == "" || (*this.Config).SMTP.Login == "" || (*this.Config).SMTP.Password == "" {
  259. return errors.New("SMTP server is not configured")
  260. }
  261. err := utils.SMTPSend(
  262. (*this.Config).SMTP.Host,
  263. utils.IntToStr((*this.Config).SMTP.Port),
  264. (*this.Config).SMTP.Login,
  265. (*this.Config).SMTP.Password,
  266. subject,
  267. message,
  268. []string{email},
  269. )
  270. status := 1
  271. emessage := ""
  272. if err != nil {
  273. status = 0
  274. emessage = err.Error()
  275. }
  276. if _, err := this.DB.Exec(
  277. `INSERT INTO notify_mail SET
  278. id = NULL,
  279. email = ?,
  280. subject = ?,
  281. message = ?,
  282. error = ?,
  283. datetime = ?,
  284. status = ?
  285. ;`,
  286. email,
  287. subject,
  288. message,
  289. emessage,
  290. utils.UnixTimestampToMySqlDateTime(utils.GetCurrentUnixTimestamp()),
  291. status,
  292. ); err != nil {
  293. this.LogCpError(&err)
  294. }
  295. return err
  296. }
  297. func (this *Wrapper) SendEmailFast(email, subject, message string) error {
  298. status := 2
  299. emessage := ""
  300. if (*this.Config).SMTP.Host == "" || (*this.Config).SMTP.Login == "" || (*this.Config).SMTP.Password == "" {
  301. status = 0
  302. emessage = "SMTP server is not configured"
  303. }
  304. if _, err := this.DB.Exec(
  305. `INSERT INTO notify_mail SET
  306. id = NULL,
  307. email = ?,
  308. subject = ?,
  309. message = ?,
  310. error = ?,
  311. datetime = ?,
  312. status = ?
  313. ;`,
  314. email,
  315. subject,
  316. message,
  317. emessage,
  318. utils.UnixTimestampToMySqlDateTime(utils.GetCurrentUnixTimestamp()),
  319. status,
  320. ); err != nil {
  321. return err
  322. }
  323. return nil
  324. }
  325. func (this *Wrapper) SendEmailTemplated(email, subject, tname string, data interface{}) error {
  326. tmpl, err := template.New(tname + ".html").Funcs(utils.TemplateAdditionalFuncs()).ParseFiles(
  327. this.DTemplate + string(os.PathSeparator) + tname + ".html",
  328. )
  329. if err != nil {
  330. return err
  331. }
  332. var tpl bytes.Buffer
  333. err = tmpl.Execute(&tpl, data)
  334. if err != nil {
  335. return err
  336. }
  337. return this.SendEmailFast(email, subject, string(tpl.Bytes()))
  338. }
  339. func (this *Wrapper) GetSessionId() string {
  340. cookie, err := this.R.Cookie("session")
  341. if err == nil && len(cookie.Value) == 40 {
  342. return cookie.Value
  343. }
  344. return ""
  345. }
  346. func (this *Wrapper) RecreateProductXmlFile() error {
  347. trigger := strings.Join([]string{this.DTmp, "trigger.xml.run"}, string(os.PathSeparator))
  348. if !utils.IsFileExists(trigger) {
  349. if _, err := os.Create(trigger); err != nil {
  350. return err
  351. }
  352. }
  353. return nil
  354. }
  355. func (this *Wrapper) RecreateProductImgFiles() error {
  356. trigger := strings.Join([]string{this.DTmp, "trigger.img.run"}, string(os.PathSeparator))
  357. if !utils.IsFileExists(trigger) {
  358. if _, err := os.Create(trigger); err != nil {
  359. return err
  360. }
  361. }
  362. return nil
  363. }
  364. func (this *Wrapper) RemoveProductImageThumbnails(product_id, filename string) error {
  365. pattern := this.DHtdocs + string(os.PathSeparator) + strings.Join([]string{"products", "images", product_id, filename}, string(os.PathSeparator))
  366. if files, err := filepath.Glob(pattern); err != nil {
  367. return err
  368. } else {
  369. for _, file := range files {
  370. if err := os.Remove(file); err != nil {
  371. return errors.New(fmt.Sprintf("[upload delete] Thumbnail file (%s) delete error: %s", file, err.Error()))
  372. }
  373. }
  374. }
  375. return this.RecreateProductImgFiles()
  376. }
  377. func (this *Wrapper) ShopGetAllCurrencies() *map[int]utils.MySql_shop_currency {
  378. if this.ShopAllCurrencies == nil {
  379. this.ShopAllCurrencies = &map[int]utils.MySql_shop_currency{}
  380. if rows, err := this.DB.Query(
  381. `SELECT
  382. id,
  383. name,
  384. coefficient,
  385. code,
  386. symbol
  387. FROM
  388. shop_currencies
  389. ORDER BY
  390. id ASC
  391. ;`,
  392. ); err == nil {
  393. defer rows.Close()
  394. for rows.Next() {
  395. row := utils.MySql_shop_currency{}
  396. if err = rows.Scan(
  397. &row.A_id,
  398. &row.A_name,
  399. &row.A_coefficient,
  400. &row.A_code,
  401. &row.A_symbol,
  402. ); err == nil {
  403. (*this.ShopAllCurrencies)[row.A_id] = row
  404. }
  405. }
  406. }
  407. }
  408. return this.ShopAllCurrencies
  409. }
  410. func (this *Wrapper) ShopGetCurrentCurrency() *utils.MySql_shop_currency {
  411. currency_id := 1
  412. if cookie, err := this.R.Cookie("currency"); err == nil {
  413. currency_id = utils.StrToInt(cookie.Value)
  414. }
  415. if _, ok := (*this.ShopGetAllCurrencies())[currency_id]; ok != true {
  416. currency_id = 1
  417. }
  418. if p, ok := (*this.ShopGetAllCurrencies())[currency_id]; ok == true {
  419. return &p
  420. }
  421. return nil
  422. }