module_shop_act_upload_delete.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package modules
  2. import (
  3. "os"
  4. "path/filepath"
  5. "golang-fave/engine/wrapper"
  6. "golang-fave/utils"
  7. )
  8. func (this *Modules) RegisterAction_ShopUploadDelete() *Action {
  9. return this.newAction(AInfo{
  10. WantDB: true,
  11. Mount: "shop-upload-delete",
  12. WantAdmin: true,
  13. }, func(wrap *wrapper.Wrapper) {
  14. pf_id := wrap.R.FormValue("id")
  15. pf_file := wrap.R.FormValue("file")
  16. if !utils.IsNumeric(pf_id) {
  17. wrap.MsgError(`Inner system error`)
  18. return
  19. }
  20. if pf_file == "" {
  21. wrap.MsgError(`Inner system error`)
  22. return
  23. }
  24. if err := wrap.DB.Transaction(func(tx *wrapper.Tx) error {
  25. // Block rows
  26. if _, err := tx.Exec("SELECT id FROM shop_products WHERE id = ? FOR UPDATE;", utils.StrToInt(pf_id)); err != nil {
  27. return err
  28. }
  29. if _, err := tx.Exec("SELECT product_id FROM shop_product_images WHERE product_id = ? FOR UPDATE;", utils.StrToInt(pf_id)); err != nil {
  30. return err
  31. }
  32. // Delete row
  33. if _, err := tx.Exec("DELETE FROM shop_product_images WHERE product_id = ? AND filename = ?;", utils.StrToInt(pf_id), pf_file); err != nil {
  34. return err
  35. }
  36. // Delete file
  37. target_file_full := wrap.DHtdocs + string(os.PathSeparator) + "products" + string(os.PathSeparator) + "images" + string(os.PathSeparator) + pf_id + string(os.PathSeparator) + pf_file
  38. os.Remove(target_file_full)
  39. // Delete thumbnails
  40. pattern := wrap.DHtdocs + string(os.PathSeparator) + "products" + string(os.PathSeparator) + "images" + string(os.PathSeparator) + pf_id + string(os.PathSeparator) + "thumb-*-" + pf_file
  41. if files, err := filepath.Glob(pattern); err == nil {
  42. for _, file := range files {
  43. if err := os.Remove(file); err != nil {
  44. wrap.LogError("[upload delete] Thumbnail file (%s) delete error: %s", file, err.Error())
  45. }
  46. }
  47. }
  48. return nil
  49. }); err != nil {
  50. wrap.MsgError(err.Error())
  51. return
  52. }
  53. wrap.Write(`$('#list-images a').each(function(i, e) { if($(e).attr('title') == '` + pf_file + `') { $(e).parent().remove(); return; } });`)
  54. })
  55. }