github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/module_ottojs.go (about)

     1  /*
     2  *
     3  *	OttoJS Plugin Module
     4  *	Copyright Azareal 2016 - 2019
     5  *
     6   */
     7  package common
     8  
     9  import (
    10  	"errors"
    11  
    12  	"github.com/robertkrimen/otto"
    13  )
    14  
    15  type OttoPluginLang struct {
    16  	vm      *otto.Otto
    17  	plugins map[string]*otto.Script
    18  	vars    map[string]*otto.Object
    19  }
    20  
    21  func init() {
    22  	pluginLangs["ottojs"] = &OttoPluginLang{
    23  		plugins: make(map[string]*otto.Script),
    24  		vars:    make(map[string]*otto.Object),
    25  	}
    26  }
    27  
    28  func (js *OttoPluginLang) Init() (err error) {
    29  	js.vm = otto.New()
    30  	js.vars["current_page"], err = js.vm.Object(`var current_page = {}`)
    31  	return err
    32  }
    33  
    34  func (js *OttoPluginLang) GetName() string {
    35  	return "ottojs"
    36  }
    37  
    38  func (js *OttoPluginLang) GetExts() []string {
    39  	return []string{".js"}
    40  }
    41  
    42  func (js *OttoPluginLang) AddPlugin(meta PluginMeta) (plugin *Plugin, err error) {
    43  	script, err := js.vm.Compile("./extend/"+meta.UName+"/"+meta.Main, nil)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	var pluginInit = func(plugin *Plugin) error {
    49  		retValue, err := js.vm.Run(script)
    50  		if err != nil {
    51  			return err
    52  		}
    53  		if retValue.IsString() {
    54  			ret, err := retValue.ToString()
    55  			if err != nil {
    56  				return err
    57  			}
    58  			if ret != "" {
    59  				return errors.New(ret)
    60  			}
    61  		}
    62  		return nil
    63  	}
    64  
    65  	plugin = new(Plugin)
    66  	plugin.UName = meta.UName
    67  	plugin.Name = meta.Name
    68  	plugin.Author = meta.Author
    69  	plugin.URL = meta.URL
    70  	plugin.Settings = meta.Settings
    71  	plugin.Tag = meta.Tag
    72  	plugin.Type = "ottojs"
    73  	plugin.Init = pluginInit
    74  
    75  	// TODO: Implement plugin life cycle events
    76  
    77  	buildPlugin(plugin)
    78  
    79  	plugin.Data = script
    80  	return plugin, nil
    81  }
    82  
    83  /*func (js *OttoPluginLang) addHook(hook string, plugin string) {
    84  	hooks[hook] = func(data interface{}) interface{} {
    85  		switch d := data.(type) {
    86  		case Page:
    87  			currentPage := js.vars["current_page"]
    88  			currentPage.Set("Title", d.Title)
    89  		case TopicPage:
    90  
    91  		case ProfilePage:
    92  
    93  		case Reply:
    94  
    95  		default:
    96  			log.Print("Not a valid JS datatype")
    97  		}
    98  	}
    99  }*/