utils.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package utils
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "regexp"
  12. "strings"
  13. "sync" //"fmt"
  14. "time" //"reflect"
  15. "golang.org/x/net/html/charset"
  16. )
  17. type MutexCounter struct {
  18. Value int64
  19. m sync.Mutex
  20. }
  21. func (t *MutexCounter) Inc(inc int64) *MutexCounter {
  22. t.m.Lock()
  23. t.Value += inc
  24. t.m.Unlock()
  25. return t
  26. }
  27. func (t *MutexCounter) Dec(inc int64) *MutexCounter {
  28. t.m.Lock()
  29. t.Value -= inc
  30. t.m.Unlock()
  31. return t
  32. }
  33. func (t *MutexCounter) Eq(val int64) bool {
  34. return t.Value == val
  35. }
  36. func Now() int64 {
  37. return time.Now().Unix()
  38. }
  39. func ToUTF8(str, origEncoding string) string {
  40. byteReader := bytes.NewReader([]byte(str))
  41. reader, _ := charset.NewReaderLabel(origEncoding, byteReader)
  42. strBytes, _ := ioutil.ReadAll(reader)
  43. return string(strBytes)
  44. }
  45. func GetFiles(directory string) ([]os.FileInfo, error) {
  46. files, err := ioutil.ReadDir(directory)
  47. if err != nil {
  48. return []os.FileInfo{}, err
  49. }
  50. return files, nil
  51. }
  52. func FileGetContents(filename string) (string, error) {
  53. b, err := ioutil.ReadFile(filename)
  54. if err != nil {
  55. return "", err
  56. }
  57. return string(b), nil
  58. }
  59. // FileExists reports whether the named file or directory exists.
  60. func FileExists(name string) bool {
  61. if _, err := os.Stat(name); err != nil {
  62. if os.IsNotExist(err) {
  63. return false
  64. }
  65. }
  66. return true
  67. }
  68. func CopyDir(source, dest string) error {
  69. var (
  70. err error
  71. file *os.File
  72. sourceinfo os.FileInfo
  73. objects []os.FileInfo
  74. )
  75. if sourceinfo, err = os.Stat(source); err != nil {
  76. return err
  77. }
  78. if err = os.MkdirAll(dest, sourceinfo.Mode()); err != nil {
  79. return err
  80. }
  81. file, _ = os.Open(source)
  82. if objects, err = file.Readdir(-1); err != nil {
  83. return err
  84. }
  85. for _, obj := range objects {
  86. srcPointer := source + "/" + obj.Name()
  87. dstPointer := dest + "/" + obj.Name()
  88. if obj.IsDir() {
  89. if err = CopyDir(srcPointer, dstPointer); err != nil {
  90. return err
  91. }
  92. } else if err = CopyFile(srcPointer, dstPointer); err != nil {
  93. return err
  94. }
  95. }
  96. return nil
  97. }
  98. func CopyFile(source, dest string) error {
  99. var (
  100. err error
  101. sourcefile *os.File
  102. destfile *os.File
  103. )
  104. if sourcefile, err = os.Open(source); err != nil {
  105. return err
  106. }
  107. defer sourcefile.Close()
  108. if destfile, err = os.Create(dest); err != nil {
  109. return err
  110. }
  111. defer destfile.Close()
  112. if _, err = io.Copy(destfile, sourcefile); err == nil {
  113. sourceinfo, err := os.Stat(source)
  114. if err != nil {
  115. err = os.Chmod(dest, sourceinfo.Mode())
  116. }
  117. }
  118. return nil
  119. }
  120. func FilePutContents(filename string, content string, perm os.FileMode) error {
  121. return FilePutContentsBytes(filename, []byte(content), perm)
  122. }
  123. func Mkdir(perm os.FileMode, paths ...string) (err error) {
  124. for _, path := range paths {
  125. if _, err := os.Stat(path); os.IsNotExist(err) {
  126. if err = os.MkdirAll(path, perm); err != nil {
  127. return err
  128. }
  129. }
  130. }
  131. return
  132. }
  133. func FilePutContentsBytes(filename string, content []byte, perm os.FileMode) error {
  134. var (
  135. // err error
  136. // f *os.File
  137. dir = path.Dir(filename)
  138. )
  139. // fmt.Println(filename, dir)
  140. if _, err := os.Stat(dir); os.IsNotExist(err) {
  141. if err = os.MkdirAll(dir, perm); err != nil {
  142. return err
  143. }
  144. }
  145. // if _, err := os.Stat(filename); os.IsNotExist(err) {
  146. // // if f, err = os.Create(filename); err != nil {
  147. // // return err
  148. // // }
  149. // err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644)
  150. // } else {
  151. // fmt.Println(" the word is not in the file")
  152. // }
  153. // } else if f, err = os.OpenFile(filename, os.O_WRONLY, os.ModeAppend); err != nil {
  154. // return err
  155. // }
  156. // defer f.Close()
  157. // _, err = f.Write(content)
  158. // return err
  159. return ioutil.WriteFile(filename, []byte(content), 0644)
  160. }
  161. func RemoveFile(file string) error {
  162. if err := os.Remove(file); err != nil {
  163. return err
  164. }
  165. return nil
  166. }
  167. func Encode(delimiter string, values ...string) string {
  168. return ToBase64(strings.Join(values, delimiter))
  169. }
  170. func ToBase64(s string) string {
  171. return base64.StdEncoding.EncodeToString([]byte(s))
  172. }
  173. func FromBase64(value string) (string, error) {
  174. dec, err := base64.StdEncoding.DecodeString(value)
  175. return string(dec), err
  176. }
  177. func Decode(delimiter, value string) ([]string, error) {
  178. decoded, err := FromBase64(value)
  179. if err != nil {
  180. return []string{}, err
  181. }
  182. return strings.Split(string(decoded), delimiter), nil
  183. }
  184. type Thumbnail struct {
  185. Resolution string
  186. // Adiciona o arquivo de entrada
  187. // path e o caminho do arquivo e pages sao as paginas a serem convertidas
  188. // pages = "[0]" - representa a pagina 1
  189. // pages = "" - representa todas as paginas
  190. Input string
  191. Output string
  192. InExt string
  193. Page string
  194. }
  195. func NewThumbnail() *Thumbnail {
  196. t := &Thumbnail{}
  197. t.Resolution = "x300"
  198. return t
  199. }
  200. var (
  201. ThumbSoffice = regexp.MustCompile("(doc|ppt|pps|pot|xls|xlt|xlw|dot|csv|txt|rtf)(x|m)?")
  202. )
  203. func (t *Thumbnail) Gen() error {
  204. var err error
  205. if t.Input == "" {
  206. return fmt.Errorf("Input is empty")
  207. }
  208. if t.InExt == "" {
  209. // todo -- pegar a extensao do arquivo de entrada
  210. }
  211. cmd := ""
  212. remove := false
  213. // Converte alguns tipos de arquivo para a imagem para depois converter para thumbnail
  214. if ThumbSoffice.Match([]byte(strings.ToLower(t.InExt))) {
  215. //cmd = "convert -thumbnail %s -background white -alpha remove %s %s"
  216. cmd = "soffice --headless --convert-to png --outdir %s %s"
  217. index := strings.LastIndex(t.Output, "/")
  218. outputdir := t.Output[0:index]
  219. if err = Exec(fmt.Sprintf(cmd, outputdir, t.Input)); err != nil {
  220. return err
  221. }
  222. t.Input = t.Output
  223. // strings.Replace(t.Input, t.InExt, ".png", -1)
  224. fmt.Println("new input -", t.InExt, "-", t.Input)
  225. remove = true
  226. }
  227. // Cria o thumbnail
  228. cmd = "convert -thumbnail %s -background white -alpha remove %s %s"
  229. Exec(fmt.Sprintf(cmd, t.Resolution, t.Input+t.Page, t.Output))
  230. // Apaga o arquivo temporario gerado pela conversao intermediaria
  231. if remove {
  232. // RemoveFile(t.Input)
  233. }
  234. return nil
  235. }
  236. func Exec(cmd string) error {
  237. fmt.Println("Executando .. ", cmd)
  238. out, err := exec.Command("bash", "-c", cmd).Output()
  239. if err != nil {
  240. fmt.Println("error occured ", err.Error())
  241. return err
  242. }
  243. fmt.Println("out >> ", string(out))
  244. return err
  245. }
  246. /*
  247. func Push(slice interface{}, el interface{}, call func(interface{}) bool) {
  248. switch reflect.TypeOf(slice).Kind() {
  249. case reflect.Slice:
  250. s := reflect.ValueOf(t)
  251. push := true
  252. item := reflect.ValueOf(el).Elem()
  253. for i := 0; i < s.Len(); i++ {
  254. push = call(s. ,item)
  255. }
  256. if push {
  257. s = append(s, item)
  258. }
  259. }
  260. }
  261. */