main.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. ArOZ Online System - fscov File Naming Format Conversion Tool
  3. This micro-servie is designed to convert filename from and to umfilename (ArOZ Online System File Explorer Custom Format)
  4. and standard UTF-8 File System filename.
  5. Usage:
  6. ./fsconv
  7. (Convert all the files, folder and sub-directories from and to umfilename to UTF8 filename.)
  8. ./fsconv {target} {mode (um / utf)}
  9. (Convert all the files, folder and sub-directories to filename in given mode, target can be file or directory.)
  10. */
  11. package main
  12. import (
  13. "fmt"
  14. "io/ioutil"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "reflect"
  19. "sort"
  20. "strings"
  21. "bytes"
  22. "encoding/hex"
  23. "flag"
  24. )
  25. //Commonly used functions
  26. func in_array(val interface{}, array interface{}) (exists bool, index int) {
  27. exists = false
  28. index = -1
  29. switch reflect.TypeOf(array).Kind() {
  30. case reflect.Slice:
  31. s := reflect.ValueOf(array)
  32. for i := 0; i < s.Len(); i++ {
  33. if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
  34. index = i
  35. exists = true
  36. return
  37. }
  38. }
  39. }
  40. return
  41. }
  42. func file_exists(path string) bool {
  43. if _, err := os.Stat(path); os.IsNotExist(err) {
  44. return false
  45. }
  46. return true
  47. }
  48. func file_get_contents(path string) string {
  49. dat, err := ioutil.ReadFile(path)
  50. if err != nil {
  51. panic("Unable to read file: " + path)
  52. }
  53. return (string(dat))
  54. }
  55. func scan_recursive(dir_path string, ignore []string) ([]string, []string) {
  56. folders := []string{}
  57. files := []string{}
  58. // Scan
  59. filepath.Walk(dir_path, func(path string, f os.FileInfo, err error) error {
  60. _continue := false
  61. // Loop : Ignore Files & Folders
  62. for _, i := range ignore {
  63. // If ignored path
  64. if strings.Index(path, i) != -1 {
  65. // Continue
  66. _continue = true
  67. }
  68. }
  69. if _continue == false {
  70. f, err = os.Stat(path)
  71. // If no error
  72. if err != nil {
  73. panic("ERROR. " + err.Error())
  74. }
  75. // File & Folder Mode
  76. f_mode := f.Mode()
  77. // Is folder
  78. if f_mode.IsDir() {
  79. // Append to Folders Array
  80. folders = append(folders, path)
  81. // Is file
  82. } else if f_mode.IsRegular() {
  83. // Append to Files Array
  84. files = append(files, path)
  85. }
  86. }
  87. return nil
  88. })
  89. return folders, files
  90. }
  91. func hex2bin(s string) ([]byte, error) {
  92. ret, err := hex.DecodeString(s)
  93. return ret, err
  94. }
  95. func bin2hex(s string) (string) {
  96. src := []byte(s)
  97. encodedStr := hex.EncodeToString(src)
  98. return encodedStr;
  99. }
  100. type ByLen []string
  101. func (a ByLen) Len() int {
  102. return len(a)
  103. }
  104. func (a ByLen) Less(i, j int) bool {
  105. return len(a[i]) > len(a[j])
  106. }
  107. func (a ByLen) Swap(i, j int) {
  108. a[i], a[j] = a[j], a[i]
  109. }
  110. func main() {
  111. dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  112. if len(os.Args) < 2 {
  113. //Default options, usually double click will start this process
  114. folders, files := scan_recursive(dir, []string{os.Args[0]})
  115. for i := 0; i < len(files); i++ {
  116. thisFilepath := strings.ReplaceAll(files[i], "\\", "/")
  117. filename := path.Base(thisFilepath)
  118. extension := filepath.Ext(filename)
  119. name := filename[0 : len(filename)-len(extension)]
  120. //Check if it has the inith prefix
  121. if len(name) > 5 && name[0:5] == "inith"{
  122. //This is hex filename. Translate its name to normal filename
  123. originalName,_ := hex2bin(name[5:])
  124. safeName := getSafeFilename(string(originalName))
  125. fmt.Println(filename + " -> " + safeName + extension)
  126. err := os.Rename(files[i], path.Dir(thisFilepath) + "/" + safeName + extension)
  127. if (err != nil){
  128. panic(err)
  129. }
  130. }
  131. }
  132. //Sort the array of folders by string length, hence deeper folder will be renamed first
  133. sort.Sort(ByLen(folders))
  134. applicationStartupPath, _ := Realpath(path.Dir(os.Args[0]))
  135. for j := 0; j < len(folders); j++{
  136. foldername := path.Base(folders[j])
  137. if (foldername != applicationStartupPath && len(filepath.Base(foldername)) > 2){
  138. //All subdirectories except the root
  139. if (isHex(filepath.Base(foldername))){
  140. //This folder use hex foldername. Convert it to UTF8 filename
  141. convFoldername, _ := hex2bin(filepath.Base(foldername));
  142. safeName := getSafeFilename(string(convFoldername))
  143. fmt.Println(filepath.Base(foldername) + " -> " + string(safeName))
  144. os.Rename(foldername,filepath.Dir(foldername) + "/" + string(safeName))
  145. }
  146. }
  147. }
  148. }else if (len(os.Args) == 2 && os.Args[1] == "help"){
  149. //Show help message
  150. fmt.Println("ArOZ Online UM File Naming Method Converter")
  151. fmt.Println("Usage: \n./fsconv Convert all files under current directory and its sub-directories into UTF-8 file naming method.")
  152. fmt.Println("./fsconv -um Convert all files under current directory and its sub-directories into UM File Naming Method representation.")
  153. fmt.Println("Flags")
  154. fmt.Println("-r Recirsive directory conversion, accept { true / false }")
  155. fmt.Println("-i Input file / directory path")
  156. fmt.Println("-f Format, accept { default / umfilename } only")
  157. fmt.Println("-m Conversion Mode, accept { file / folder / all} only")
  158. }else if (len(os.Args) == 2 && os.Args[1] == "-um"){
  159. //Convert all files and folder into um filenaming methods
  160. folders, files := scan_recursive(dir, []string{os.Args[0]})
  161. for i := 0; i < len(files); i++ {
  162. thisFilepath := strings.ReplaceAll(files[i], "\\", "/")
  163. filename := path.Base(thisFilepath)
  164. extension := filepath.Ext(filename)
  165. name := filename[0 : len(filename)-len(extension)]
  166. //Check if it has the inith prefix
  167. if len(name) > 5 && name[0:5] != "inith"{
  168. //This is not hex filename. Translate its name to um-filename method
  169. umfilename := "inith" + bin2hex(name)
  170. fmt.Println(filename + " -> " + umfilename + extension)
  171. err := os.Rename(files[i], path.Dir(thisFilepath) + "/" + umfilename + extension)
  172. if (err != nil){
  173. panic(err)
  174. }
  175. }
  176. }
  177. //Sort the array of folders by string length, hence deeper folder will be renamed first
  178. sort.Sort(ByLen(folders))
  179. applicationStartupPath, _ := Realpath(path.Dir(os.Args[0]))
  180. for j := 0; j < len(folders); j++{
  181. foldername := path.Base(folders[j])
  182. if (foldername != applicationStartupPath){
  183. //All subdirectories except the root
  184. if (!isHex(filepath.Base(foldername))){
  185. //This folder do not hex foldername. Convert it to hex-foldername
  186. convFoldername := bin2hex(filepath.Base(foldername));
  187. fmt.Println(filepath.Base(foldername) + " -> " + string(convFoldername))
  188. os.Rename(foldername,filepath.Dir(foldername) + "/" + string(convFoldername))
  189. }
  190. }
  191. }
  192. } else {
  193. //Given target directory with flags
  194. var recursive = flag.Bool("r",false,"Enable recursive filename translation.")
  195. var inputFile = flag.String("i","","Input filename.")
  196. var format = flag.String("f","default","Conversion target format. Accept {default/umfilename}.")
  197. var mode = flag.String("m","all","Conversion mode. Accept {file/folder/all}.")
  198. flag.Parse()
  199. fmt.Println("r:", *recursive)
  200. fmt.Println("i:", *inputFile)
  201. fmt.Println("f:", *format)
  202. fmt.Println("m:", *mode)
  203. }
  204. }
  205. func getSafeFilename(s string) string{
  206. replacer := strings.NewReplacer("/", "", "\\","", "@","-", "&","-", "*","-", "<","-", ">","-", "|","-", "?","-", ":","-")
  207. safeName := replacer.Replace(string(s))
  208. return safeName
  209. }
  210. func isHex(s string) bool{
  211. _, err := hex2bin(s)
  212. if err != nil {
  213. return false
  214. }
  215. return true
  216. }
  217. //Realpath from https://github.com/yookoala/realpath/blob/master/realpath.go
  218. // Realpath returns the real path of a given file in the os
  219. func Realpath(fpath string) (string, error) {
  220. if len(fpath) == 0 {
  221. return "", os.ErrInvalid
  222. }
  223. if !filepath.IsAbs(fpath) {
  224. pwd, err := os.Getwd()
  225. if err != nil {
  226. return "", err
  227. }
  228. fpath = filepath.Join(pwd, fpath)
  229. }
  230. path := []byte(fpath)
  231. nlinks := 0
  232. start := 1
  233. prev := 1
  234. for start < len(path) {
  235. c := nextComponent(path, start)
  236. cur := c[start:]
  237. switch {
  238. case len(cur) == 0:
  239. copy(path[start:], path[start+1:])
  240. path = path[0 : len(path)-1]
  241. case len(cur) == 1 && cur[0] == '.':
  242. if start+2 < len(path) {
  243. copy(path[start:], path[start+2:])
  244. }
  245. path = path[0 : len(path)-2]
  246. case len(cur) == 2 && cur[0] == '.' && cur[1] == '.':
  247. copy(path[prev:], path[start+2:])
  248. path = path[0 : len(path)+prev-(start+2)]
  249. prev = 1
  250. start = 1
  251. default:
  252. fi, err := os.Lstat(string(c))
  253. if err != nil {
  254. return "", err
  255. }
  256. if isSymlink(fi) {
  257. nlinks++
  258. if nlinks > 16 {
  259. return "", os.ErrInvalid
  260. }
  261. var link string
  262. link, err = os.Readlink(string(c))
  263. after := string(path[len(c):])
  264. // switch symlink component with its real path
  265. path = switchSymlinkCom(path, start, link, after)
  266. prev = 1
  267. start = 1
  268. } else {
  269. // Directories
  270. prev = start
  271. start = len(c) + 1
  272. }
  273. }
  274. }
  275. for len(path) > 1 && path[len(path)-1] == os.PathSeparator {
  276. path = path[0 : len(path)-1]
  277. }
  278. return string(path), nil
  279. }
  280. // test if a link is symbolic link
  281. func isSymlink(fi os.FileInfo) bool {
  282. return fi.Mode()&os.ModeSymlink == os.ModeSymlink
  283. }
  284. // switch a symbolic link component to its real path
  285. func switchSymlinkCom(path []byte, start int, link, after string) []byte {
  286. if link[0] == os.PathSeparator {
  287. // Absolute links
  288. return []byte(filepath.Join(link, after))
  289. }
  290. // Relative links
  291. return []byte(filepath.Join(string(path[0:start]), link, after))
  292. }
  293. // get the next component
  294. func nextComponent(path []byte, start int) []byte {
  295. v := bytes.IndexByte(path[start:], os.PathSeparator)
  296. if v < 0 {
  297. return path
  298. }
  299. return path[0 : start+v]
  300. }