Kaynağa Gözat

basic implementation

TC 4 yıl önce
ebeveyn
işleme
371df414a5
11 değiştirilmiş dosya ile 1155 ekleme ve 751 silme
  1. 29 26
      .gitignore
  2. BIN
      ArSamba_darwin_amd64
  3. 8 8
      LICENSE
  4. 2 2
      README.md
  5. 126 126
      apt/apt.go
  6. 69 69
      aroz/aroz.go
  7. 0 31
      build.bat
  8. 221 221
      common.go
  9. 290 129
      main.go
  10. 263 0
      smb.conf
  11. 147 139
      web/index.html

+ 29 - 26
.gitignore

@@ -1,26 +1,29 @@
-# ---> Go
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
-*.prof
-
+# ---> Go
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+*.test
+*.prof
+
+#Project test files
+profiles/*
+ArSamba_linux_*

BIN
ArSamba_darwin_amd64


+ 8 - 8
LICENSE

@@ -1,8 +1,8 @@
-MIT License
-Copyright (c) <year> <copyright holders>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+MIT License
+Copyright (c) <year> <copyright holders>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 2 - 2
README.md

@@ -1,3 +1,3 @@
-# ArSamba
-
+# ArSamba
+
 The Samba subservice for arozos system 

+ 126 - 126
apt/apt.go

@@ -1,126 +1,126 @@
-package apt
-
-
-import (
-	"os/exec"
-	"runtime"
-	"net/http"
-	"errors"
-	"encoding/json"
-	"strings"
-	"log"
-	"os"
-)
-
-/*
-	Pacakge management tool for Linux OS with APT
-
-	ONLY USABLE under Linux environment
-*/
-
-type AptPackageManager struct{
-	AllowAutoInstall bool
-}
-
-func NewPackageManager(autoInstall bool) *AptPackageManager{
-	return &AptPackageManager{
-		AllowAutoInstall: autoInstall,
-	}
-}
-
-//Install the given package if not exists. Set mustComply to true for "panic on failed to install"
-func (a *AptPackageManager)InstallIfNotExists(pkgname string, mustComply bool) error{
-	//Clear the pkgname
-	pkgname = strings.ReplaceAll(pkgname, "&","")
-	pkgname = strings.ReplaceAll(pkgname, "|","")
-	
-	if runtime.GOOS == "windows" {
-		//Check if the command already exists in windows path paramters.
-		cmd := exec.Command("where", pkgname, "2>", "nul")
-		_, err := cmd.CombinedOutput()
-		if err != nil{
-			return errors.New("Package " + pkgname + " not found in Windows %PATH%.")
-		}
-		return nil
-	}
-
-	if (a.AllowAutoInstall == false){
-		return errors.New("Package auto install is disabled")
-	}
-
-	cmd := exec.Command("whereis", pkgname)
-	out, err := cmd.CombinedOutput()
-	if err != nil{
-		return err
-	}
-
-	packageInfo := strings.Split(strings.TrimSpace(string(out)), ":")
-	//log.Println(packageInfo)
-	if (len(packageInfo) > 1 && packageInfo[1] != ""){
-		return nil
-	}else{
-		//Package not installed. Install if now if running in sudo mode
-		log.Println("Installing package " + pkgname + "...")
-		cmd := exec.Command("apt-get", "install", "-y", pkgname)
-		cmd.Stdout = os.Stdout
-		cmd.Stderr = os.Stderr
-		err := cmd.Run()
-		if err != nil{
-			if (mustComply){
-				//Panic and terminate server process
-				log.Println("Installation failed on package: " + pkgname, string(out))
-				os.Exit(0)
-			}else{
-				log.Println("Installation failed on package: " + pkgname)
-				log.Println(string(out))
-			}
-			return err
-		}
-		return nil
-	}
-
-	return nil
-}
-
-
-func HandlePackageListRequest(w http.ResponseWriter, r *http.Request){
-	if runtime.GOOS == "windows" {
-		w.Header().Set("Content-Type", "application/json")
-		w.Write([]byte("{\"error\":\"" + "Function disabled on Windows" + "\"}"))
-		return
-	}
-	cmd := exec.Command("apt", "list", "--installed")
-	out, err := cmd.CombinedOutput()
-	if err != nil{
-		w.Header().Set("Content-Type", "application/json")
-		w.Write([]byte("{\"error\":\"" + err.Error() + "\"}"))
-		return
-	}
-
-	results := [][]string{}
-	//Parse the output string
-	installedPackages := strings.Split(string(out), "\n")
-	for _, thisPackage := range installedPackages{
-		if len(thisPackage) > 0{
-			packageInfo := strings.Split(thisPackage, "/")
-			packageName := packageInfo[0]
-			if len(packageInfo) >= 2{
-				packageVersion := strings.Split(packageInfo[1], ",")[1]
-				if (packageVersion[:3] == "now"){
-					packageVersion = packageVersion[4:]
-				}
-				if (strings.Contains(packageVersion, "[installed") && packageVersion[len(packageVersion) - 1:] != "]"){
-					packageVersion = packageVersion + ",automatic]"
-				}
-
-				results = append(results, []string{packageName, packageVersion})
-			}
-		}
-	}
-
-	jsonString, _ := json.Marshal(results);
-	w.Header().Set("Content-Type", "application/json")
-	w.Write(jsonString)
-	return
-}
-
+package apt
+
+
+import (
+	"os/exec"
+	"runtime"
+	"net/http"
+	"errors"
+	"encoding/json"
+	"strings"
+	"log"
+	"os"
+)
+
+/*
+	Pacakge management tool for Linux OS with APT
+
+	ONLY USABLE under Linux environment
+*/
+
+type AptPackageManager struct{
+	AllowAutoInstall bool
+}
+
+func NewPackageManager(autoInstall bool) *AptPackageManager{
+	return &AptPackageManager{
+		AllowAutoInstall: autoInstall,
+	}
+}
+
+//Install the given package if not exists. Set mustComply to true for "panic on failed to install"
+func (a *AptPackageManager)InstallIfNotExists(pkgname string, mustComply bool) error{
+	//Clear the pkgname
+	pkgname = strings.ReplaceAll(pkgname, "&","")
+	pkgname = strings.ReplaceAll(pkgname, "|","")
+	
+	if runtime.GOOS == "windows" {
+		//Check if the command already exists in windows path paramters.
+		cmd := exec.Command("where", pkgname, "2>", "nul")
+		_, err := cmd.CombinedOutput()
+		if err != nil{
+			return errors.New("Package " + pkgname + " not found in Windows %PATH%.")
+		}
+		return nil
+	}
+
+	if (a.AllowAutoInstall == false){
+		return errors.New("Package auto install is disabled")
+	}
+
+	cmd := exec.Command("whereis", pkgname)
+	out, err := cmd.CombinedOutput()
+	if err != nil{
+		return err
+	}
+
+	packageInfo := strings.Split(strings.TrimSpace(string(out)), ":")
+	//log.Println(packageInfo)
+	if (len(packageInfo) > 1 && packageInfo[1] != ""){
+		return nil
+	}else{
+		//Package not installed. Install if now if running in sudo mode
+		log.Println("Installing package " + pkgname + "...")
+		cmd := exec.Command("apt-get", "install", "-y", pkgname)
+		cmd.Stdout = os.Stdout
+		cmd.Stderr = os.Stderr
+		err := cmd.Run()
+		if err != nil{
+			if (mustComply){
+				//Panic and terminate server process
+				log.Println("Installation failed on package: " + pkgname, string(out))
+				os.Exit(0)
+			}else{
+				log.Println("Installation failed on package: " + pkgname)
+				log.Println(string(out))
+			}
+			return err
+		}
+		return nil
+	}
+
+	return nil
+}
+
+
+func HandlePackageListRequest(w http.ResponseWriter, r *http.Request){
+	if runtime.GOOS == "windows" {
+		w.Header().Set("Content-Type", "application/json")
+		w.Write([]byte("{\"error\":\"" + "Function disabled on Windows" + "\"}"))
+		return
+	}
+	cmd := exec.Command("apt", "list", "--installed")
+	out, err := cmd.CombinedOutput()
+	if err != nil{
+		w.Header().Set("Content-Type", "application/json")
+		w.Write([]byte("{\"error\":\"" + err.Error() + "\"}"))
+		return
+	}
+
+	results := [][]string{}
+	//Parse the output string
+	installedPackages := strings.Split(string(out), "\n")
+	for _, thisPackage := range installedPackages{
+		if len(thisPackage) > 0{
+			packageInfo := strings.Split(thisPackage, "/")
+			packageName := packageInfo[0]
+			if len(packageInfo) >= 2{
+				packageVersion := strings.Split(packageInfo[1], ",")[1]
+				if (packageVersion[:3] == "now"){
+					packageVersion = packageVersion[4:]
+				}
+				if (strings.Contains(packageVersion, "[installed") && packageVersion[len(packageVersion) - 1:] != "]"){
+					packageVersion = packageVersion + ",automatic]"
+				}
+
+				results = append(results, []string{packageName, packageVersion})
+			}
+		}
+	}
+
+	jsonString, _ := json.Marshal(results);
+	w.Header().Set("Content-Type", "application/json")
+	w.Write(jsonString)
+	return
+}
+

+ 69 - 69
aroz/aroz.go

@@ -1,70 +1,70 @@
-package aroz
-
-import (
-	"flag"
-	"fmt"
-	"net/http"
-	"net/url"
-	"encoding/json"
-	"os"
-)
-
-type ArozHandler struct{
-	Port string
-	restfulEndpoint string
-}
-
-//Information required for registering this subservice to arozos
-type ServiceInfo struct{
-	Name string				//Name of this module. e.g. "Audio"
-	Desc string				//Description for this module
-	Group string			//Group of the module, e.g. "system" / "media" etc
-	IconPath string			//Module icon image path e.g. "Audio/img/function_icon.png"
-	Version string			//Version of the module. Format: [0-9]*.[0-9][0-9].[0-9]
-	StartDir string 		//Default starting dir, e.g. "Audio/index.html"
-	SupportFW bool 			//Support floatWindow. If yes, floatWindow dir will be loaded
-	LaunchFWDir string 		//This link will be launched instead of 'StartDir' if fw mode
-	SupportEmb bool			//Support embedded mode
-	LaunchEmb string 		//This link will be launched instead of StartDir / Fw if a file is opened with this module
-	InitFWSize []int 		//Floatwindow init size. [0] => Width, [1] => Height
-	InitEmbSize []int		//Embedded mode init size. [0] => Width, [1] => Height
-	SupportedExt []string 	//Supported File Extensions. e.g. ".mp3", ".flac", ".wav"
-}
-
-//This function will request the required flag from the startup paramters and parse it to the need of the arozos.
-func HandleFlagParse(info ServiceInfo) *ArozHandler{
-	var infoRequestMode = flag.Bool("info", false, "Show information about this subservice")
-	var port = flag.String("port", ":80", "The default listening endpoint for this subservice")
-	var restful = flag.String("rpt", "http://localhost:8080/api/ajgi/interface", "The RESTFUL Endpoint of the parent")
-	//Parse the flags
-	flag.Parse();
-	if (*infoRequestMode == true){
-		//Information request mode
-		jsonString, _ := json.Marshal(info);
-		fmt.Println(string(jsonString))
-		os.Exit(0);
-	}
-	return &ArozHandler{
-		Port: *port,
-		restfulEndpoint: *restful,
-	};
-}
-
-//Get the username and resources access token from the request, return username, token
-func (a *ArozHandler)GetUserInfoFromRequest(w http.ResponseWriter, r *http.Request)(string, string){
-	username := r.Header.Get("aouser")
-	token := r.Header.Get("aotoken")
-
-	return username, token
-}
-
-func (a *ArozHandler)RequestGatewayInterface(token string, script string)(*http.Response, error){
-	resp, err := http.PostForm(a.restfulEndpoint,
-		url.Values{"token":{token}, "script":{script}})
-    if err != nil {
-		// handle error
-		return nil, err
-	}
-	
-	return resp, nil
+package aroz
+
+import (
+	"flag"
+	"fmt"
+	"net/http"
+	"net/url"
+	"encoding/json"
+	"os"
+)
+
+type ArozHandler struct{
+	Port string
+	restfulEndpoint string
+}
+
+//Information required for registering this subservice to arozos
+type ServiceInfo struct{
+	Name string				//Name of this module. e.g. "Audio"
+	Desc string				//Description for this module
+	Group string			//Group of the module, e.g. "system" / "media" etc
+	IconPath string			//Module icon image path e.g. "Audio/img/function_icon.png"
+	Version string			//Version of the module. Format: [0-9]*.[0-9][0-9].[0-9]
+	StartDir string 		//Default starting dir, e.g. "Audio/index.html"
+	SupportFW bool 			//Support floatWindow. If yes, floatWindow dir will be loaded
+	LaunchFWDir string 		//This link will be launched instead of 'StartDir' if fw mode
+	SupportEmb bool			//Support embedded mode
+	LaunchEmb string 		//This link will be launched instead of StartDir / Fw if a file is opened with this module
+	InitFWSize []int 		//Floatwindow init size. [0] => Width, [1] => Height
+	InitEmbSize []int		//Embedded mode init size. [0] => Width, [1] => Height
+	SupportedExt []string 	//Supported File Extensions. e.g. ".mp3", ".flac", ".wav"
+}
+
+//This function will request the required flag from the startup paramters and parse it to the need of the arozos.
+func HandleFlagParse(info ServiceInfo) *ArozHandler{
+	var infoRequestMode = flag.Bool("info", false, "Show information about this subservice")
+	var port = flag.String("port", ":80", "The default listening endpoint for this subservice")
+	var restful = flag.String("rpt", "http://localhost:8080/api/ajgi/interface", "The RESTFUL Endpoint of the parent")
+	//Parse the flags
+	flag.Parse();
+	if (*infoRequestMode == true){
+		//Information request mode
+		jsonString, _ := json.Marshal(info);
+		fmt.Println(string(jsonString))
+		os.Exit(0);
+	}
+	return &ArozHandler{
+		Port: *port,
+		restfulEndpoint: *restful,
+	};
+}
+
+//Get the username and resources access token from the request, return username, token
+func (a *ArozHandler)GetUserInfoFromRequest(w http.ResponseWriter, r *http.Request)(string, string){
+	username := r.Header.Get("aouser")
+	token := r.Header.Get("aotoken")
+
+	return username, token
+}
+
+func (a *ArozHandler)RequestGatewayInterface(token string, script string)(*http.Response, error){
+	resp, err := http.PostForm(a.restfulEndpoint,
+		url.Values{"token":{token}, "script":{script}})
+    if err != nil {
+		// handle error
+		return nil, err
+	}
+	
+	return resp, nil
 }

+ 0 - 31
build.bat

@@ -1,31 +0,0 @@
-echo "Building darwin"
-set GOOS=darwin
-set GOARCH=amd64
-
-for %%I in (.) do SET EXENAME=%%~nxI
-
-go build
-MOVE "%EXENAME%" "%EXENAME%_darwin_amd64"
-
-echo "Building linux"
-set GOOS=linux
-set GOARCH=amd64
-go build
-MOVE "%EXENAME%" "%EXENAME%_linux_amd64"
-
-set GOOS=linux
-set GOARCH=arm
-go build
-MOVE "%EXENAME%" "%EXENAME%_linux_arm"
-
-set GOOS=linux
-set GOARCH=arm64
-go build
-MOVE "%EXENAME%" "%EXENAME%_linux_arm64"
-
-echo "Building windows"
-set GOOS=windows
-set GOARCH=amd64
-go build
-
-echo "Completed"

+ 221 - 221
common.go

@@ -1,222 +1,222 @@
-package main
-
-import (
-	"os"
-    "log"
-	"net/http"
-	"strconv"
-	"strings"
-	"errors"
-	"encoding/base64"
-	"bufio"
-	"io/ioutil"
-	"time"
-)
-
-/*
-	SYSTEM COMMON FUNCTIONS
-
-	This is a system function that put those we usually use function but not belongs to
-	any module / system.
-
-	E.g. fileExists / IsDir etc
-
-*/
-
-/*
-	Basic Response Functions
-
-	Send response with ease
-*/
-//Send text response with given w and message as string
-func sendTextResponse(w http.ResponseWriter, msg string) {
-	w.Write([]byte(msg))
-}
-
-//Send JSON response, with an extra json header
-func sendJSONResponse(w http.ResponseWriter, json string) {
-	w.Header().Set("Content-Type", "application/json")
-	w.Write([]byte(json))
-}
-
-func sendErrorResponse(w http.ResponseWriter, errMsg string) {
-	w.Header().Set("Content-Type", "application/json")
-	w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
-}
-
-func sendOK(w http.ResponseWriter) {
-	w.Header().Set("Content-Type", "application/json")
-	w.Write([]byte("\"OK\""))
-}
-/*
-	The paramter move function (mv)
-
-	You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
-	r (HTTP Request Object)
-	getParamter (string, aka $_GET['This string])
-
-	Will return
-	Paramter string (if any)
-	Error (if error)
-
-*/
-func mv(r *http.Request, getParamter string, postMode bool) (string, error) {
-	if postMode == false {
-		//Access the paramter via GET
-		keys, ok := r.URL.Query()[getParamter]
-
-		if !ok || len(keys[0]) < 1 {
-			//log.Println("Url Param " + getParamter +" is missing")
-			return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
-		}
-
-		// Query()["key"] will return an array of items,
-		// we only want the single item.
-		key := keys[0]
-		return string(key), nil
-	} else {
-		//Access the parameter via POST
-		r.ParseForm()
-		x := r.Form.Get(getParamter)
-		if len(x) == 0 || x == "" {
-			return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
-		}
-		return string(x), nil
-	}
-
-}
-
-func stringInSlice(a string, list []string) bool {
-    for _, b := range list {
-        if b == a {
-            return true
-        }
-    }
-    return false
-}
-
-
-func fileExists(filename string) bool {
-    _, err := os.Stat(filename)
-    if os.IsNotExist(err) {
-        return false
-    }
-    return true
-}
-
-
-func IsDir(path string) bool{
-	if (fileExists(path) == false){
-		return false
-	}
-	fi, err := os.Stat(path)
-    if err != nil {
-        log.Fatal(err)
-        return false
-    }
-    switch mode := fi.Mode(); {
-    case mode.IsDir():
-        return true
-    case mode.IsRegular():
-        return false
-	}
-	return false
-}
-
-func inArray(arr []string, str string) bool {
-	for _, a := range arr {
-	   if a == str {
-		  return true
-	   }
-	}
-	return false
- }
-
- func timeToString(targetTime time.Time) string{
-	 return targetTime.Format("2006-01-02 15:04:05")
- }
-
- func IntToString(number int) string{
-	return strconv.Itoa(number)
- }
-
- func StringToInt(number string) (int, error){
-	return strconv.Atoi(number)
- }
-
- func StringToInt64(number string) (int64, error){
-	i, err := strconv.ParseInt(number, 10, 64)
-	if err != nil {
-		return -1, err
-	}
-	return i, nil
- }
-
- func Int64ToString(number int64) string{
-	convedNumber:=strconv.FormatInt(number,10)
-	return convedNumber
- }
-
- func GetUnixTime() int64{
-	return time.Now().Unix()
- }
-
- func LoadImageAsBase64(filepath string) (string, error){
-	if !fileExists(filepath){
-		return "", errors.New("File not exists")
-	}
-	f, _ := os.Open(filepath)
-    reader := bufio.NewReader(f)
-    content, _ := ioutil.ReadAll(reader)
-	encoded := base64.StdEncoding.EncodeToString(content)
-	return string(encoded), nil
- }
-
- func PushToSliceIfNotExist(slice []string, newItem string) []string {
-	itemExists := false
-	for _, item := range slice{
-		if item == newItem{
-			itemExists = true
-		}
-	}
-
-	if !itemExists{
-		slice = append(slice, newItem)
-	}
-
-	return slice
- }
-
- func RemoveFromSliceIfExists(slice []string, target string) []string {
-	 newSlice := []string{}
-	 for _, item := range slice{
-		 if item != target{
-			newSlice = append(newSlice, item)
-		 }
-	 }
-
-	 return newSlice;
- }
-
- //Get the IP address of the current authentication user
-func ReflectUserIP(w http.ResponseWriter, r *http.Request) {
-    requestPort,_ :=  mv(r, "port", false)
-    showPort := false;
-    if (requestPort == "true"){
-        //Show port as well
-        showPort = true;
-    }
-    IPAddress := r.Header.Get("X-Real-Ip")
-    if IPAddress == "" {
-        IPAddress = r.Header.Get("X-Forwarded-For")
-    }
-    if IPAddress == "" {
-        IPAddress = r.RemoteAddr
-    }
-    if (!showPort){
-        IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
-
-    }
-    w.Write([]byte(IPAddress))
-    return;
+package main
+
+import (
+	"os"
+    "log"
+	"net/http"
+	"strconv"
+	"strings"
+	"errors"
+	"encoding/base64"
+	"bufio"
+	"io/ioutil"
+	"time"
+)
+
+/*
+	SYSTEM COMMON FUNCTIONS
+
+	This is a system function that put those we usually use function but not belongs to
+	any module / system.
+
+	E.g. fileExists / IsDir etc
+
+*/
+
+/*
+	Basic Response Functions
+
+	Send response with ease
+*/
+//Send text response with given w and message as string
+func sendTextResponse(w http.ResponseWriter, msg string) {
+	w.Write([]byte(msg))
+}
+
+//Send JSON response, with an extra json header
+func sendJSONResponse(w http.ResponseWriter, json string) {
+	w.Header().Set("Content-Type", "application/json")
+	w.Write([]byte(json))
+}
+
+func sendErrorResponse(w http.ResponseWriter, errMsg string) {
+	w.Header().Set("Content-Type", "application/json")
+	w.Write([]byte("{\"error\":\"" + errMsg + "\"}"))
+}
+
+func sendOK(w http.ResponseWriter) {
+	w.Header().Set("Content-Type", "application/json")
+	w.Write([]byte("\"OK\""))
+}
+/*
+	The paramter move function (mv)
+
+	You can find similar things in the PHP version of ArOZ Online Beta. You need to pass in
+	r (HTTP Request Object)
+	getParamter (string, aka $_GET['This string])
+
+	Will return
+	Paramter string (if any)
+	Error (if error)
+
+*/
+func mv(r *http.Request, getParamter string, postMode bool) (string, error) {
+	if postMode == false {
+		//Access the paramter via GET
+		keys, ok := r.URL.Query()[getParamter]
+
+		if !ok || len(keys[0]) < 1 {
+			//log.Println("Url Param " + getParamter +" is missing")
+			return "", errors.New("GET paramter " + getParamter + " not found or it is empty")
+		}
+
+		// Query()["key"] will return an array of items,
+		// we only want the single item.
+		key := keys[0]
+		return string(key), nil
+	} else {
+		//Access the parameter via POST
+		r.ParseForm()
+		x := r.Form.Get(getParamter)
+		if len(x) == 0 || x == "" {
+			return "", errors.New("POST paramter " + getParamter + " not found or it is empty")
+		}
+		return string(x), nil
+	}
+
+}
+
+func stringInSlice(a string, list []string) bool {
+    for _, b := range list {
+        if b == a {
+            return true
+        }
+    }
+    return false
+}
+
+
+func fileExists(filename string) bool {
+    _, err := os.Stat(filename)
+    if os.IsNotExist(err) {
+        return false
+    }
+    return true
+}
+
+
+func IsDir(path string) bool{
+	if (fileExists(path) == false){
+		return false
+	}
+	fi, err := os.Stat(path)
+    if err != nil {
+        log.Fatal(err)
+        return false
+    }
+    switch mode := fi.Mode(); {
+    case mode.IsDir():
+        return true
+    case mode.IsRegular():
+        return false
+	}
+	return false
+}
+
+func inArray(arr []string, str string) bool {
+	for _, a := range arr {
+	   if a == str {
+		  return true
+	   }
+	}
+	return false
+ }
+
+ func timeToString(targetTime time.Time) string{
+	 return targetTime.Format("2006-01-02 15:04:05")
+ }
+
+ func IntToString(number int) string{
+	return strconv.Itoa(number)
+ }
+
+ func StringToInt(number string) (int, error){
+	return strconv.Atoi(number)
+ }
+
+ func StringToInt64(number string) (int64, error){
+	i, err := strconv.ParseInt(number, 10, 64)
+	if err != nil {
+		return -1, err
+	}
+	return i, nil
+ }
+
+ func Int64ToString(number int64) string{
+	convedNumber:=strconv.FormatInt(number,10)
+	return convedNumber
+ }
+
+ func GetUnixTime() int64{
+	return time.Now().Unix()
+ }
+
+ func LoadImageAsBase64(filepath string) (string, error){
+	if !fileExists(filepath){
+		return "", errors.New("File not exists")
+	}
+	f, _ := os.Open(filepath)
+    reader := bufio.NewReader(f)
+    content, _ := ioutil.ReadAll(reader)
+	encoded := base64.StdEncoding.EncodeToString(content)
+	return string(encoded), nil
+ }
+
+ func PushToSliceIfNotExist(slice []string, newItem string) []string {
+	itemExists := false
+	for _, item := range slice{
+		if item == newItem{
+			itemExists = true
+		}
+	}
+
+	if !itemExists{
+		slice = append(slice, newItem)
+	}
+
+	return slice
+ }
+
+ func RemoveFromSliceIfExists(slice []string, target string) []string {
+	 newSlice := []string{}
+	 for _, item := range slice{
+		 if item != target{
+			newSlice = append(newSlice, item)
+		 }
+	 }
+
+	 return newSlice;
+ }
+
+ //Get the IP address of the current authentication user
+func ReflectUserIP(w http.ResponseWriter, r *http.Request) {
+    requestPort,_ :=  mv(r, "port", false)
+    showPort := false;
+    if (requestPort == "true"){
+        //Show port as well
+        showPort = true;
+    }
+    IPAddress := r.Header.Get("X-Real-Ip")
+    if IPAddress == "" {
+        IPAddress = r.Header.Get("X-Forwarded-For")
+    }
+    if IPAddress == "" {
+        IPAddress = r.RemoteAddr
+    }
+    if (!showPort){
+        IPAddress = IPAddress[:strings.LastIndex(IPAddress, ":")]
+
+    }
+    w.Write([]byte(IPAddress))
+    return;
 }

+ 290 - 129
main.go

@@ -1,129 +1,290 @@
-package main
-
-import (
-	"encoding/json"
-	"log"
-	"net/http"
-	"os"
-	"os/signal"
-	"syscall"
-
-	"git.arozos.com/ArSamba/apt"
-
-	"git.arozos.com/ArSamba/aroz"
-)
-
-var (
-	handler *aroz.ArozHandler
-)
-
-func SetupCloseHandler() {
-	c := make(chan os.Signal, 2)
-	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
-	go func() {
-		<-c
-		log.Println("\r- Shutting down ArSamba module.")
-
-		os.Exit(0)
-	}()
-}
-
-func main() {
-	//If you have other flags, please add them here
-
-	//Start the aoModule pipeline (which will parse the flags as well). Pass in the module launch information
-	handler = aroz.HandleFlagParse(aroz.ServiceInfo{
-		Name:        "ArSamba",
-		Desc:        "arozos Samba Setting Subservice",
-		Group:       "System Settings",
-		IconPath:    "arsamba/img/icon.png",
-		Version:     "1.0",
-		StartDir:    "arsamba/index.html",
-		SupportFW:   true,
-		LaunchFWDir: "arsamba/index.html",
-		InitFWSize:  []int{350, 560},
-	})
-
-	//Install samba if it is not installed
-	pm := apt.NewPackageManager(true)
-	pm.InstallIfNotExists("samba", true)
-
-	//Register the standard web services urls
-	fs := http.FileServer(http.Dir("./web"))
-	http.HandleFunc("/create", handleNewUser)
-	http.HandleFunc("/remove", handleUserRemove)
-	http.HandleFunc("/getStatus", handleGetStatus)
-	http.Handle("/", fs)
-
-	SetupCloseHandler()
-
-	log.Println("ArSamba subservice started. Listening on " + handler.Port)
-	err := http.ListenAndServe(handler.Port, nil)
-	if err != nil {
-		log.Fatal(err)
-	}
-
-}
-
-func handleGetStatus(w http.ResponseWriter, r *http.Request) {
-	//Get username from request
-	username, _ := handler.GetUserInfoFromRequest(w, r)
-
-	//Check if the user has already in samba user
-	log.Println("Checking User Status", username)
-
-	//Send the results
-	js, _ := json.Marshal(true)
-	sendJSONResponse(w, string(js))
-}
-
-func handleNewUser(w http.ResponseWriter, r *http.Request) {
-	//Get the required information
-	username, err := mv(r, "username", true)
-	if err != nil {
-		sendErrorResponse(w, "Invalid username given")
-		return
-	}
-
-	//Match the session username
-	proxyUser, _ := handler.GetUserInfoFromRequest(w, r)
-	if username != proxyUser {
-		sendErrorResponse(w, "User not logged in")
-		return
-	}
-
-	password, err := mv(r, "password", true)
-	if err != nil {
-		sendErrorResponse(w, "Invalid password given")
-		return
-	}
-
-	//Add the user to samba
-	log.Println("Adding User", username, password)
-
-	//Return ok
-	sendOK(w)
-
-}
-
-func handleUserRemove(w http.ResponseWriter, r *http.Request) {
-	//Get the required information
-	username, err := mv(r, "username", true)
-	if err != nil {
-		sendErrorResponse(w, "Invalid username given")
-		return
-	}
-
-	//Match the session username
-	proxyUser, _ := handler.GetUserInfoFromRequest(w, r)
-	if username != proxyUser {
-		sendErrorResponse(w, "User not logged in")
-		return
-	}
-
-	//OK! Remove user
-	log.Println("Remove user", username)
-
-	//Return OK
-	sendOK(w)
-}
+package main
+
+import (
+	"encoding/json"
+	"io/ioutil"
+	"log"
+	"net/http"
+	"os"
+	"os/exec"
+	"os/signal"
+	"path/filepath"
+	"strings"
+	"syscall"
+
+	"git.arozos.com/ArSamba/apt"
+
+	"git.arozos.com/ArSamba/aroz"
+)
+
+var (
+	handler *aroz.ArozHandler
+)
+
+func SetupCloseHandler() {
+	c := make(chan os.Signal, 2)
+	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
+	go func() {
+		<-c
+		log.Println("\r- Shutting down ArSamba module.")
+
+		os.Exit(0)
+	}()
+}
+
+func main() {
+	//If you have other flags, please add them here
+
+	//Start the aoModule pipeline (which will parse the flags as well). Pass in the module launch information
+	handler = aroz.HandleFlagParse(aroz.ServiceInfo{
+		Name:        "ArSamba",
+		Desc:        "arozos Samba Setting Subservice",
+		Group:       "System Settings",
+		IconPath:    "arsamba/img/icon.png",
+		Version:     "1.0",
+		StartDir:    "arsamba/index.html",
+		SupportFW:   true,
+		LaunchFWDir: "arsamba/index.html",
+		InitFWSize:  []int{350, 560},
+	})
+
+	//Register the standard web services urls
+	fs := http.FileServer(http.Dir("./web"))
+	http.HandleFunc("/create", handleNewUser)
+	http.HandleFunc("/remove", handleUserRemove)
+	http.HandleFunc("/getStatus", handleGetStatus)
+	http.Handle("/", fs)
+
+	SetupCloseHandler()
+
+	go func(port string) {
+		log.Println("ArSamba subservice started. Listening on " + handler.Port)
+		err := http.ListenAndServe(port, nil)
+		if err != nil {
+			log.Fatal(err)
+		}
+	}(handler.Port)
+
+	//Mkdir for user samba profile
+	os.MkdirAll("./profiles", 0755)
+
+	//Install samba if it is not installed
+	pm := apt.NewPackageManager(true)
+	err := pm.InstallIfNotExists("samba", true)
+	if err != nil {
+		panic(err)
+	}
+
+	//Do a blocking loop
+	select {}
+}
+
+func handleGetStatus(w http.ResponseWriter, r *http.Request) {
+	//Get username from request
+	username, _ := handler.GetUserInfoFromRequest(w, r)
+
+	//Check if the user has already in samba user
+	log.Println("Checking User Status", username)
+	userExists := false
+	out, err := execute("pdbedit -L | grep " + username)
+	if err != nil {
+		userExists = false
+	}
+
+	if strings.TrimSpace(string(out)) != "" {
+		userExists = true
+	}
+
+	//Send the results
+	js, _ := json.Marshal(userExists)
+	sendJSONResponse(w, string(js))
+}
+
+func handleNewUser(w http.ResponseWriter, r *http.Request) {
+	//Get the required information
+	username, err := mv(r, "username", true)
+	if err != nil {
+		sendErrorResponse(w, "Invalid username given")
+		return
+	}
+
+	//Match the session username
+	proxyUser, token := handler.GetUserInfoFromRequest(w, r)
+	if username != proxyUser {
+		sendErrorResponse(w, "User not logged in")
+		return
+	}
+
+	password, err := mv(r, "password", true)
+	if err != nil {
+		sendErrorResponse(w, "Invalid password given")
+		return
+	}
+
+	//Add the user to samba
+	log.Println("Adding User", username)
+	//Add user to linux
+	out, _ := execute("useradd -m \"" + username + "\"")
+	log.Println(string(out))
+
+	//Set password for the new user
+	out, _ = execute(`(echo "` + password + `"; sleep 1; echo "` + password + `";) | passwd "` + username + `"`)
+	log.Println(string(out))
+
+	//Add it to samba user
+	out, _ = execute(`(echo "` + password + `"; sleep 1; echo "` + password + `" ) | sudo smbpasswd -s -a "` + username + `"`)
+	log.Println(string(out))
+
+	//Create an AGI Call that get the user's storage directories files
+	script := `
+	requirelib("filelib");
+	//Get the roots of this user
+	var roots = filelib.glob("/");
+	var userdirs = [];
+	for (var i = 0; i < roots.length; i++){
+		//Translate all these roots to realpath
+		userdirs.push([roots[i].split(":").shift(), decodeAbsoluteVirtualPath(roots[i]), pathCanWrite(roots[i])])
+	}
+	
+	sendJSONResp(JSON.stringify(userdirs))
+	`
+
+	userProfile := []string{}
+
+	//Execute the AGI request on server side
+	resp, err := handler.RequestGatewayInterface(token, script)
+	if err != nil {
+		//Something went wrong when performing POST request
+		log.Println(err)
+	} else {
+		//Try to read the resp body
+		bodyBytes, err := ioutil.ReadAll(resp.Body)
+		if err != nil {
+			log.Println(err)
+			w.Write([]byte(err.Error()))
+			return
+		}
+		resp.Body.Close()
+
+		log.Println(string(bodyBytes))
+
+		//Decode the json
+		type Results [][]interface{}
+		results := new(Results)
+		err = json.Unmarshal(bodyBytes, &results)
+		if err != nil {
+			log.Println(err)
+			return
+		}
+
+		log.Println(results)
+
+		//Generate user root folders
+		for _, r := range *results {
+			if len(r) == 3 {
+				pathname := r[0].(string)
+				if pathname == "tmp" {
+					//Do not expose tmp folder
+					continue
+				}
+				rpath := r[1].(string)
+				canWrite := r[2].(bool)
+				uuidOfStorage := username + " (" + pathname + ")"
+				if canWrite {
+					userProfile = append(userProfile, `[`+uuidOfStorage+`]
+	comment=`+username+"'s "+pathname+`
+	path=`+rpath+`
+	read only=no
+	valid users = `+username+`
+	guest ok=no
+	browseable=yes
+	create mask=0777
+	directory mask=0777`)
+				} else {
+					userProfile = append(userProfile, `[`+uuidOfStorage+`]
+	comment=`+username+"'s "+pathname+`
+	path=`+rpath+`
+	read only=yes
+	valid users = `+username+`
+	guest ok=no
+	browseable=yes
+	create mask=0777
+	directory mask=0777`)
+				}
+			}
+		}
+
+	}
+
+	log.Println(strings.Join(userProfile, "\n\n"))
+
+	//Write the user profiles to file
+	ioutil.WriteFile("./profiles/"+username+".conf", []byte(strings.Join(userProfile, "\n\n")), 0755)
+
+	updateSmbConfig()
+	//Return ok
+	sendOK(w)
+}
+
+func handleUserRemove(w http.ResponseWriter, r *http.Request) {
+	//Get the required information
+	username, err := mv(r, "username", true)
+	if err != nil {
+		sendErrorResponse(w, "Invalid username given")
+		return
+	}
+
+	//Match the session username
+	proxyUser, _ := handler.GetUserInfoFromRequest(w, r)
+	if username != proxyUser {
+		sendErrorResponse(w, "User not logged in")
+		return
+	}
+
+	//OK! Remove user
+	log.Println("Remove user", username)
+
+	//Remove user from samba
+	out, _ := execute("smbpasswd -x \"" + username + "\"")
+	log.Println(string(out))
+
+	//Remove user from linux as well
+	out, _ = execute("userdel -r  \"" + username + "\"")
+	log.Println(string(out))
+
+	//Remove user profiles
+	if fileExists("./profiles/" + username + ".conf") {
+		os.Remove("./profiles/" + username + ".conf")
+	}
+	updateSmbConfig()
+
+	//Return OK
+	sendOK(w)
+}
+
+func updateSmbConfig() {
+	//Update the system config
+	profiles, _ := filepath.Glob("./profiles/*.conf")
+	base, _ := ioutil.ReadFile("smb.conf")
+	additionalProfiles := []string{}
+	for _, profile := range profiles {
+		thisProfileContent, _ := ioutil.ReadFile(profile)
+		additionalProfiles = append(additionalProfiles, string(thisProfileContent))
+	}
+
+	finalConfigFile := string(base) + strings.Join(additionalProfiles, "\n\n")
+
+	ioutil.WriteFile("/etc/samba/smb.conf", []byte(finalConfigFile), 0777)
+
+	out, err := execute("systemctl restart smbd.service")
+	log.Println("Samba restarted: ", string(out), err)
+}
+
+func execute(command string) (string, error) {
+	cmd := exec.Command("bash", "-c", command)
+	out, err := cmd.CombinedOutput()
+	if err != nil {
+		return string(out), err
+	}
+	return string(out), nil
+}

+ 263 - 0
smb.conf

@@ -0,0 +1,263 @@
+#
+# Sample configuration file for the Samba suite for Debian GNU/Linux.
+#
+#
+# This is the main Samba configuration file. You should read the
+# smb.conf(5) manual page in order to understand the options listed
+# here. Samba has a huge number of configurable options most of which 
+# are not shown in this example
+#
+# Some options that are often worth tuning have been included as
+# commented-out examples in this file.
+#  - When such options are commented with ";", the proposed setting
+#    differs from the default Samba behaviour
+#  - When commented with "#", the proposed setting is the default
+#    behaviour of Samba but the option is considered important
+#    enough to be mentioned here
+#
+# NOTE: Whenever you modify this file you should run the command
+# "testparm" to check that you have not made any basic syntactic 
+# errors. 
+
+#======================= Global Settings =======================
+
+[global]
+
+## Browsing/Identification ###
+
+# Change this to the workgroup/NT-domain name your Samba server will part of
+   workgroup = WORKGROUP
+
+# Windows Internet Name Serving Support Section:
+# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
+#   wins support = no
+
+# WINS Server - Tells the NMBD components of Samba to be a WINS Client
+# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
+;   wins server = w.x.y.z
+
+# This will prevent nmbd to search for NetBIOS names through DNS.
+   dns proxy = no
+
+#### Networking ####
+
+# The specific set of interfaces / networks to bind to
+# This can be either the interface name or an IP address/netmask;
+# interface names are normally preferred
+;   interfaces = 127.0.0.0/8 eth0
+
+# Only bind to the named interfaces and/or networks; you must use the
+# 'interfaces' option above to use this.
+# It is recommended that you enable this feature if your Samba machine is
+# not protected by a firewall or is a firewall itself.  However, this
+# option cannot handle dynamic or non-broadcast interfaces correctly.
+;   bind interfaces only = yes
+
+
+
+#### Debugging/Accounting ####
+
+# This tells Samba to use a separate log file for each machine
+# that connects
+   log file = /var/log/samba/log.%m
+
+# Cap the size of the individual log files (in KiB).
+   max log size = 1000
+
+# If you want Samba to only log through syslog then set the following
+# parameter to 'yes'.
+#   syslog only = no
+
+# We want Samba to log a minimum amount of information to syslog. Everything
+# should go to /var/log/samba/log.{smbd,nmbd} instead. If you want to log
+# through syslog you should set the following parameter to something higher.
+   syslog = 0
+
+# Do something sensible when Samba crashes: mail the admin a backtrace
+   panic action = /usr/share/samba/panic-action %d
+
+
+####### Authentication #######
+
+# Server role. Defines in which mode Samba will operate. Possible
+# values are "standalone server", "member server", "classic primary
+# domain controller", "classic backup domain controller", "active
+# directory domain controller". 
+#
+# Most people will want "standalone sever" or "member server".
+# Running as "active directory domain controller" will require first
+# running "samba-tool domain provision" to wipe databases and create a
+# new domain.
+   server role = standalone server
+
+# If you are using encrypted passwords, Samba will need to know what
+# password database type you are using.  
+   passdb backend = tdbsam
+
+   obey pam restrictions = yes
+
+# This boolean parameter controls whether Samba attempts to sync the Unix
+# password with the SMB password when the encrypted SMB password in the
+# passdb is changed.
+   unix password sync = yes
+
+# For Unix password sync to work on a Debian GNU/Linux system, the following
+# parameters must be set (thanks to Ian Kahan <<kahan@informatik.tu-muenchen.de> for
+# sending the correct chat script for the passwd program in Debian Sarge).
+   passwd program = /usr/bin/passwd %u
+   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
+
+# This boolean controls whether PAM will be used for password changes
+# when requested by an SMB client instead of the program listed in
+# 'passwd program'. The default is 'no'.
+   pam password change = yes
+
+# This option controls how unsuccessful authentication attempts are mapped
+# to anonymous connections
+   map to guest = bad user
+
+########## Domains ###########
+
+#
+# The following settings only takes effect if 'server role = primary
+# classic domain controller', 'server role = backup domain controller'
+# or 'domain logons' is set 
+#
+
+# It specifies the location of the user's
+# profile directory from the client point of view) The following
+# required a [profiles] share to be setup on the samba server (see
+# below)
+;   logon path = \\%N\profiles\%U
+# Another common choice is storing the profile in the user's home directory
+# (this is Samba's default)
+#   logon path = \\%N\%U\profile
+
+# The following setting only takes effect if 'domain logons' is set
+# It specifies the location of a user's home directory (from the client
+# point of view)
+;   logon drive = H:
+#   logon home = \\%N\%U
+
+# The following setting only takes effect if 'domain logons' is set
+# It specifies the script to run during logon. The script must be stored
+# in the [netlogon] share
+# NOTE: Must be store in 'DOS' file format convention
+;   logon script = logon.cmd
+
+# This allows Unix users to be created on the domain controller via the SAMR
+# RPC pipe.  The example command creates a user account with a disabled Unix
+# password; please adapt to your needs
+; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u
+
+# This allows machine accounts to be created on the domain controller via the 
+# SAMR RPC pipe.  
+# The following assumes a "machines" group exists on the system
+; add machine script  = /usr/sbin/useradd -g machines -c "%u machine account" -d /var/lib/samba -s /bin/false %u
+
+# This allows Unix groups to be created on the domain controller via the SAMR
+# RPC pipe.  
+; add group script = /usr/sbin/addgroup --force-badname %g
+
+############ Misc ############
+
+# Using the following line enables you to customise your configuration
+# on a per machine basis. The %m gets replaced with the netbios name
+# of the machine that is connecting
+;   include = /home/samba/etc/smb.conf.%m
+
+# Some defaults for winbind (make sure you're not using the ranges
+# for something else.)
+;   idmap uid = 10000-20000
+;   idmap gid = 10000-20000
+;   template shell = /bin/bash
+
+# Setup usershare options to enable non-root users to share folders
+# with the net usershare command.
+
+# Maximum number of usershare. 0 (default) means that usershare is disabled.
+;   usershare max shares = 100
+
+# Allow users who've been granted usershare privileges to create
+# public shares, not just authenticated ones
+   usershare allow guests = yes
+
+#======================= Share Definitions =======================
+
+[homes]
+   comment = Home Directories
+   browseable = no
+
+# By default, the home directories are exported read-only. Change the
+# next parameter to 'no' if you want to be able to write to them.
+   read only = yes
+
+# File creation mask is set to 0700 for security reasons. If you want to
+# create files with group=rw permissions, set next parameter to 0775.
+   create mask = 0700
+
+# Directory creation mask is set to 0700 for security reasons. If you want to
+# create dirs. with group=rw permissions, set next parameter to 0775.
+   directory mask = 0700
+
+# By default, \\server\username shares can be connected to by anyone
+# with access to the samba server.
+# The following parameter makes sure that only "username" can connect
+# to \\server\username
+# This might need tweaking when using external authentication schemes
+   valid users = %S
+
+# Un-comment the following and create the netlogon directory for Domain Logons
+# (you need to configure Samba to act as a domain controller too.)
+;[netlogon]
+;   comment = Network Logon Service
+;   path = /home/samba/netlogon
+;   guest ok = yes
+;   read only = yes
+
+# Un-comment the following and create the profiles directory to store
+# users profiles (see the "logon path" option above)
+# (you need to configure Samba to act as a domain controller too.)
+# The path below should be writable by all users so that their
+# profile directory may be created the first time they log on
+;[profiles]
+;   comment = Users profiles
+;   path = /home/samba/profiles
+;   guest ok = no
+;   browseable = no
+;   create mask = 0600
+;   directory mask = 0700
+
+[printers]
+   comment = All Printers
+   browseable = no
+   path = /var/spool/samba
+   printable = yes
+   guest ok = no
+   read only = yes
+   create mask = 0700
+
+# Windows clients look for this share name as a source of downloadable
+# printer drivers
+[print$]
+   comment = Printer Drivers
+   path = /var/lib/samba/printers
+   browseable = yes
+   read only = yes
+   guest ok = no
+# Uncomment to allow remote administration of Windows print drivers.
+# You may need to replace 'lpadmin' with the name of the group your
+# admin users are members of.
+# Please note that you also need to set appropriate Unix permissions
+# to the drivers directory for these users to have write rights in it
+;   write list = root, @lpadmin
+
+[pi]
+  comment=pi home
+  path=/home/pi
+  read only=no
+  guest ok=no
+  browseable=yes
+  create mask=0777
+  directory mask=0777
+

+ 147 - 139
web/index.html

@@ -1,140 +1,148 @@
-<!DOCTYPE html>
-<html>
-    <head>
-        <meta name="apple-mobile-web-app-capable" content="yes" />
-        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
-        <meta charset="UTF-8">
-        <meta name="theme-color" content="#4b75ff">
-        <link rel="stylesheet" href="../script/semantic/semantic.min.css">
-        <script src="../script/jquery.min.js"></script>
-        <script src="../script/ao_module.js"></script>
-        <script src="../script/semantic/semantic.min.js"></script>
-        <title>ArSamba Settings</title>
-        <style>
-            body{
-                background-color:white;
-            }
-
-            .success{
-                color: #20c942;
-            }
-
-            .failed{
-                color: #eb4034;
-            }
-        </style>
-    </head>
-    <body>
-        <br>
-		<div class="ui text container">
-            <div class="ui header">
-                <i class="windows icon"></i>
-                <div class="content">
-                    Samba Settings
-                    <div class="sub header">for arozos systems</div>
-                </div>
-            </div>
-            <p>Account Status: <span id="acstatus" class="failed">Disabled</span></p>
-            <div id="enableAccount">
-                <h3>Enable My Samba Account</h3>
-                <form class="ui form" onsubmit="createAccount(event);">
-                <div class="fluid field">
-                    <label>Username (Read Only)</label>
-                    <input type="text" id="username" readonly="true">
-                </div>
-                <div class="field">
-                    <label>Password</label>
-                    <input type="password" id="pw">
-                </div>
-                <div class="field">
-                    <label>Confirm Password</label>
-                    <input type="password" id="rpw">
-                </div>
-                <button class="ui green button" type="submit">Create</button>
-                </form>
-            </div>
-            <div id="disableAccount" style="display:none;">
-                <h3>Disable My Samba Account</h3>
-                <p>This operation will remove your samba user account from the system</p>
-                <button class="ui red button" onclick="removeUser(event)">Disable</button>
-            </div>
-            
-        <br><br>
-        <script>
-            //Do not allow window resize
-            ao_module_setFixedWindowSize();
-
-            //Get username from system
-            $.get("../system/users/userinfo", function(data){
-                var username = data.Username;
-                $("#username").val(username);
-
-                //Get the account status
-                $.get("./getStatus?username=" + username, function(data){
-                    if (data == true){
-                        $("#acstatus").text("Enabled");
-                        $("#acstatus").attr("class","success");
-                        $("#enableAccount").hide();
-                        $("#disableAccount").show();
-                    } else{
-                        $("#acstatus").text("Disabled");
-                        $("#acstatus").attr("class","failed");
-                        $("#enableAccount").show();
-                        $("#disableAccount").hide();
-                    }
-                });
-            });
-
-            function removeUser(e){
-                 //Process the user creation process
-                 $.get("../system/users/userinfo", function(data){
-                    //Get the username
-                    var username = data.Username;
-                    $.ajax({
-                        url: "./remove",
-                        method: "POST",
-                        data: {username: username},
-                        success: function(data){
-                            //Creation succeed. Reload this page
-                            window.location.reload();
-                        }
-                    });
-                 });
-                
-            }
-            
-
-            function createAccount(e){
-                e.preventDefault();
-                //Get the userinfo again in case the user has changed name during the setting period
-                $.get("../system/users/userinfo", function(data){
-                    //Get the username
-                    var username = data.Username;
-                    
-                    //Check if the password match
-                    var pw = $("#pw").val();
-                    var rpw = $("#rpw").val();
-                    if (pw != rpw){
-                        //Password not match
-                        $("#rpw").parent().addClass("error");
-                        return
-                    }else{
-                        $("#rpw").parent().removeClass("error");
-                    }
-
-                    //Process the user creation process
-                    $.ajax({
-                        url: "./create",
-                        method: "POST",
-                        data: {username: username, password: pw},
-                        success: function(data){
-                            //Creation succeed. Reload this page
-                            window.location.reload();
-                        }
-                    });
-
-                });
-            }
-        </script>
-    </body>
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta name="apple-mobile-web-app-capable" content="yes" />
+        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"/>
+        <meta charset="UTF-8">
+        <meta name="theme-color" content="#4b75ff">
+        <link rel="stylesheet" href="../script/semantic/semantic.min.css">
+        <script src="../script/jquery.min.js"></script>
+        <script src="../script/ao_module.js"></script>
+        <script src="../script/semantic/semantic.min.js"></script>
+        <title>ArSamba Settings</title>
+        <style>
+            body{
+                background-color:white;
+            }
+
+            .success{
+                color: #20c942;
+            }
+
+            .failed{
+                color: #eb4034;
+            }
+        </style>
+    </head>
+    <body>
+        <br>
+		<div class="ui text container">
+            <div class="ui header">
+                <i class="windows icon"></i>
+                <div class="content">
+                    Samba Settings
+                    <div class="sub header">for arozos systems</div>
+                </div>
+            </div>
+            <p>Account Status: <span id="acstatus" class="failed">Disabled</span></p>
+            <div id="enableAccount">
+                <h3>Enable My Samba Account</h3>
+                <form class="ui form" onsubmit="createAccount(event);">
+                <div class="fluid field">
+                    <label>Username (Read Only)</label>
+                    <input type="text" id="username" readonly="true">
+                </div>
+                <div class="field">
+                    <label>Password</label>
+                    <input type="password" id="pw">
+                </div>
+                <div class="field">
+                    <label>Confirm Password</label>
+                    <input type="password" id="rpw">
+                </div>
+                <button id="createbtn" class="ui green button" type="submit">Create</button>
+                </form>
+            </div>
+            <div id="disableAccount" style="display:none;">
+                <h3>Disable My Samba Account</h3>
+                <p>This operation will remove your samba user account from the system</p>
+                <button class="ui red button" onclick="removeUser(event)">Disable</button>
+            </div>
+            
+        <br><br>
+        <script>
+            //Do not allow window resize
+            ao_module_setFixedWindowSize();
+
+            //Get username from system
+            $.get("../system/users/userinfo", function(data){
+                var username = data.Username;
+                $("#username").val(username);
+
+                //Get the account status
+                $.get("./getStatus?username=" + username, function(data){
+                    if (data == true){
+                        $("#acstatus").text("Enabled");
+                        $("#acstatus").attr("class","success");
+                        $("#enableAccount").hide();
+                        $("#disableAccount").show();
+                    } else{
+                        $("#acstatus").text("Disabled");
+                        $("#acstatus").attr("class","failed");
+                        $("#enableAccount").show();
+                        $("#disableAccount").hide();
+                    }
+                });
+            });
+
+            function removeUser(e){
+                 //Process the user creation process
+                 $.get("../system/users/userinfo", function(data){
+                    //Get the username
+                    var username = data.Username;
+                    $.ajax({
+                        url: "./remove",
+                        method: "POST",
+                        data: {username: username},
+                        success: function(data){
+                            //Creation succeed. Reload this page
+                            window.location.reload();
+                        }
+                    });
+                 });
+                
+            }
+            
+
+            function createAccount(e){
+                e.preventDefault();
+                //Get the userinfo again in case the user has changed name during the setting period
+                $.get("../system/users/userinfo", function(data){
+                    //Get the username
+                    var username = data.Username;
+                    
+                    //Check if the password match
+                    var pw = $("#pw").val();
+                    var rpw = $("#rpw").val();
+                    if (pw == "" || rpw == ""){
+                        alert("Password cannot be empty")
+                        return
+                    }
+
+                    if (pw != rpw){
+                        //Password not match
+                        $("#rpw").parent().addClass("error");
+                        return
+                    }else{
+                        $("#rpw").parent().removeClass("error");
+                    }
+
+                    //Process the user creation process
+                    $("#createbtn").addClass("loading");
+                    $.ajax({
+                        url: "./create",
+                        method: "POST",
+                        data: {username: username, password: pw},
+                        success: function(data){
+                            //Creation succeed. Reload this page
+                            $("#createbtn").removeClass("loading");
+                            window.location.reload();
+                            
+                        }
+                    });
+
+                });
+            }
+        </script>
+    </body>
 </html>