main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 recursiveUTF8Conv(dir string, rf bool, rd bool){
  111. folders, files := scan_recursive(dir, []string{os.Args[0]})
  112. if (rf){
  113. for i := 0; i < len(files); i++ {
  114. thisFilepath := strings.ReplaceAll(files[i], "\\", "/")
  115. filename := path.Base(thisFilepath)
  116. extension := filepath.Ext(filename)
  117. name := filename[0 : len(filename)-len(extension)]
  118. //Check if it has the inith prefix
  119. if len(name) > 5 && name[0:5] == "inith"{
  120. //This is hex filename. Translate its name to normal filename
  121. originalName,_ := hex2bin(name[5:])
  122. safeName := getSafeFilename(string(originalName))
  123. fmt.Println(filename + " -> " + safeName + extension)
  124. err := os.Rename(files[i], path.Dir(thisFilepath) + "/" + safeName + extension)
  125. if (err != nil){
  126. panic(err)
  127. }
  128. }
  129. }
  130. }
  131. if (rd){
  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. }
  149. }
  150. func recursiveUMFNConv(dir string,rf bool, rd bool){
  151. folders, files := scan_recursive(dir, []string{os.Args[0]})
  152. if (rf){
  153. for i := 0; i < len(files); i++ {
  154. thisFilepath := strings.ReplaceAll(files[i], "\\", "/")
  155. filename := path.Base(thisFilepath)
  156. extension := filepath.Ext(filename)
  157. name := filename[0 : len(filename)-len(extension)]
  158. //Check if it has the inith prefix
  159. if len(name) > 5 && name[0:5] != "inith"{
  160. //This is not hex filename. Translate its name to um-filename method
  161. umfilename := "inith" + bin2hex(name)
  162. fmt.Println(filename + " -> " + umfilename + extension)
  163. err := os.Rename(files[i], path.Dir(thisFilepath) + "/" + umfilename + extension)
  164. if (err != nil){
  165. panic(err)
  166. }
  167. }
  168. }
  169. }
  170. if (rd){
  171. //Sort the array of folders by string length, hence deeper folder will be renamed first
  172. sort.Sort(ByLen(folders))
  173. applicationStartupPath, _ := Realpath(path.Dir(os.Args[0]))
  174. for j := 0; j < len(folders); j++{
  175. foldername := path.Base(folders[j])
  176. if (foldername != applicationStartupPath){
  177. //All subdirectories except the root
  178. if (!isHex(filepath.Base(foldername))){
  179. //This folder do not hex foldername. Convert it to hex-foldername
  180. convFoldername := bin2hex(filepath.Base(foldername));
  181. fmt.Println(filepath.Base(foldername) + " -> " + string(convFoldername))
  182. os.Rename(foldername,filepath.Dir(foldername) + "/" + string(convFoldername))
  183. }
  184. }
  185. }
  186. }
  187. }
  188. func isDir(path string) bool{
  189. fi, err := os.Stat(path)
  190. if err != nil {
  191. fmt.Println(err)
  192. return false
  193. }
  194. switch mode := fi.Mode(); {
  195. case mode.IsDir():
  196. // do directory stuff
  197. return true
  198. case mode.IsRegular():
  199. // do file stuff
  200. return false
  201. }
  202. return false
  203. }
  204. func getSafeFilename(s string) string{
  205. replacer := strings.NewReplacer("/", "", "\\","", "@","-", "&","-", "*","-", "<","-", ">","-", "|","-", "?","-", ":","-")
  206. safeName := replacer.Replace(string(s))
  207. return safeName
  208. }
  209. func isHex(s string) bool{
  210. _, err := hex2bin(s)
  211. if err != nil {
  212. return false
  213. }
  214. return true
  215. }
  216. //Realpath from https://github.com/yookoala/realpath/blob/master/realpath.go
  217. // Realpath returns the real path of a given file in the os
  218. func Realpath(fpath string) (string, error) {
  219. if len(fpath) == 0 {
  220. return "", os.ErrInvalid
  221. }
  222. if !filepath.IsAbs(fpath) {
  223. pwd, err := os.Getwd()
  224. if err != nil {
  225. return "", err
  226. }
  227. fpath = filepath.Join(pwd, fpath)
  228. }
  229. path := []byte(fpath)
  230. nlinks := 0
  231. start := 1
  232. prev := 1
  233. for start < len(path) {
  234. c := nextComponent(path, start)
  235. cur := c[start:]
  236. switch {
  237. case len(cur) == 0:
  238. copy(path[start:], path[start+1:])
  239. path = path[0 : len(path)-1]
  240. case len(cur) == 1 && cur[0] == '.':
  241. if start+2 < len(path) {
  242. copy(path[start:], path[start+2:])
  243. }
  244. path = path[0 : len(path)-2]
  245. case len(cur) == 2 && cur[0] == '.' && cur[1] == '.':
  246. copy(path[prev:], path[start+2:])
  247. path = path[0 : len(path)+prev-(start+2)]
  248. prev = 1
  249. start = 1
  250. default:
  251. fi, err := os.Lstat(string(c))
  252. if err != nil {
  253. return "", err
  254. }
  255. if isSymlink(fi) {
  256. nlinks++
  257. if nlinks > 16 {
  258. return "", os.ErrInvalid
  259. }
  260. var link string
  261. link, err = os.Readlink(string(c))
  262. after := string(path[len(c):])
  263. // switch symlink component with its real path
  264. path = switchSymlinkCom(path, start, link, after)
  265. prev = 1
  266. start = 1
  267. } else {
  268. // Directories
  269. prev = start
  270. start = len(c) + 1
  271. }
  272. }
  273. }
  274. for len(path) > 1 && path[len(path)-1] == os.PathSeparator {
  275. path = path[0 : len(path)-1]
  276. }
  277. return string(path), nil
  278. }
  279. // test if a link is symbolic link
  280. func isSymlink(fi os.FileInfo) bool {
  281. return fi.Mode()&os.ModeSymlink == os.ModeSymlink
  282. }
  283. // switch a symbolic link component to its real path
  284. func switchSymlinkCom(path []byte, start int, link, after string) []byte {
  285. if link[0] == os.PathSeparator {
  286. // Absolute links
  287. return []byte(filepath.Join(link, after))
  288. }
  289. // Relative links
  290. return []byte(filepath.Join(string(path[0:start]), link, after))
  291. }
  292. // get the next component
  293. func nextComponent(path []byte, start int) []byte {
  294. v := bytes.IndexByte(path[start:], os.PathSeparator)
  295. if v < 0 {
  296. return path
  297. }
  298. return path[0 : start+v]
  299. }
  300. func main() {
  301. dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  302. if len(os.Args) < 2 {
  303. //Default options, usually double click will start this process
  304. recursiveUTF8Conv(dir,true,true)
  305. }else if (len(os.Args) == 2 && os.Args[1] == "help"){
  306. //Show help message
  307. fmt.Println("ArOZ Online UM File Naming Method Converter")
  308. fmt.Println("Usage: \n./fsconv Convert all files under current directory and its sub-directories into UTF-8 file naming method.")
  309. fmt.Println("./fsconv -um Convert all files under current directory and its sub-directories into UM File Naming Method representation.")
  310. fmt.Println("Use ./fsconv -h for showing all usable flags for defined file / folder conversion")
  311. }else if (len(os.Args) == 2 && os.Args[1] == "-um"){
  312. //Convert all files and folder into um filenaming methods
  313. recursiveUMFNConv(dir,true,true);
  314. } else {
  315. //Given target directory with flags
  316. var recursive = flag.Bool("r",false,"Enable recursive filename translation.")
  317. var inputFile = flag.String("i","","Input filename.")
  318. var defaultFormat = flag.Bool("utf",false,"Convert to standard UTF-8 filename format")
  319. var umFormat = flag.Bool("um",false,"Convert to UMfilename format")
  320. var recursiveFileOnly = flag.Bool("rf",false,"Recursive rename file only.")
  321. var recursiveDirOnly = flag.Bool("rd",false,"Recursive rename directory only.")
  322. flag.Parse()
  323. //Check if the input file exists.
  324. if !file_exists(*inputFile){
  325. fmt.Println("ERROR. Input file not exists. Given: ", *inputFile);
  326. os.Exit(0);
  327. }
  328. //Check if setting logic correct
  329. if (*defaultFormat == *umFormat){
  330. //If not defined defaultFormat or umFormat, assume default Format
  331. *defaultFormat = true
  332. }
  333. fmt.Println("r:", *recursive)
  334. fmt.Println("i:", *inputFile)
  335. fmt.Println("utf:", *defaultFormat)
  336. fmt.Println("um:", *umFormat)
  337. fmt.Println("rf:", *recursiveFileOnly)
  338. fmt.Println("rd:", *recursiveDirOnly)
  339. //Perform translation process
  340. if (*recursive|| *recursiveFileOnly || *recursiveDirOnly){
  341. //Recursive mode
  342. if (*defaultFormat == true){
  343. //Convert everything in given directory into standard filename
  344. if (*recursiveFileOnly){
  345. recursiveUTF8Conv(*inputFile,true,false)
  346. }else if (*recursiveDirOnly){
  347. recursiveUTF8Conv(*inputFile,false,true)
  348. }else{
  349. recursiveUTF8Conv(*inputFile,true,true)
  350. }
  351. }else{
  352. //Convert everything in give ndirectory in umfilename
  353. if (*recursiveFileOnly){
  354. recursiveUMFNConv(*inputFile,true,false)
  355. }else if (*recursiveDirOnly){
  356. recursiveUMFNConv(*inputFile,false,true)
  357. }else{
  358. recursiveUMFNConv(*inputFile,true,true)
  359. }
  360. }
  361. }else{
  362. if (isDir(*inputFile)){
  363. //A folder
  364. if (*defaultFormat == true){
  365. if (isHex(filepath.Base(*inputFile))){
  366. //This folder use hex foldername. Convert it to UTF8 filename
  367. convFoldername, _ := hex2bin(filepath.Base(*inputFile));
  368. safeName := getSafeFilename(string(convFoldername))
  369. fmt.Println(filepath.Base(*inputFile) + " -> " + string(safeName))
  370. err := os.Rename(*inputFile,filepath.Dir(*inputFile) + "/" + string(safeName))
  371. if (err != nil){
  372. panic(err)
  373. }
  374. }
  375. }else{
  376. convFoldername := bin2hex(filepath.Base(*inputFile));
  377. fmt.Println(filepath.Base(*inputFile) + " -> " + string(convFoldername))
  378. os.Rename(*inputFile,filepath.Dir(*inputFile) + "/" + string(convFoldername))
  379. }
  380. }else{
  381. //A file
  382. if (*defaultFormat == true){
  383. thisFilepath := strings.ReplaceAll(*inputFile, "\\", "/")
  384. filename := path.Base(thisFilepath)
  385. extension := filepath.Ext(filename)
  386. name := filename[0 : len(filename)-len(extension)]
  387. //Check if it has the inith prefix
  388. if len(name) > 5 && name[0:5] == "inith"{
  389. //This is hex filename. Translate its name to normal filename
  390. originalName,_ := hex2bin(name[5:])
  391. safeName := getSafeFilename(string(originalName))
  392. fmt.Println(filename + " -> " + safeName + extension)
  393. err := os.Rename(*inputFile, path.Dir(thisFilepath) + "/" + safeName + extension)
  394. if (err != nil){
  395. panic(err)
  396. }
  397. }
  398. }else{
  399. thisFilepath := strings.ReplaceAll(*inputFile, "\\", "/")
  400. filename := path.Base(thisFilepath)
  401. extension := filepath.Ext(filename)
  402. name := filename[0 : len(filename)-len(extension)]
  403. //Check if it has the inith prefix
  404. if len(name) > 5 && name[0:5] != "inith"{
  405. //This is not hex filename. Translate its name to um-filename method
  406. umfilename := "inith" + bin2hex(name)
  407. fmt.Println(filename + " -> " + umfilename + extension)
  408. err := os.Rename(*inputFile, path.Dir(thisFilepath) + "/" + umfilename + extension)
  409. if (err != nil){
  410. panic(err)
  411. }
  412. }
  413. }
  414. }
  415. }
  416. }
  417. }