plugin_core.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. package core
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "reflect"
  10. "regexp"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/cdle/sillyplus/core/common"
  15. "github.com/cdle/sillyplus/core/storage"
  16. "github.com/cdle/sillyplus/utils"
  17. "github.com/dop251/goja"
  18. "github.com/dop251/goja/parser"
  19. "github.com/dop251/goja_nodejs/eventloop"
  20. "github.com/robfig/cron/v3"
  21. )
  22. var pluginLock = new(sync.Mutex)
  23. type myFieldNameMapper struct{}
  24. var mutexMap = make(map[string]*sync.Mutex)
  25. var mutexMapMutex sync.Mutex
  26. func GetMutex(uuid string) *sync.Mutex {
  27. mutexMapMutex.Lock()
  28. defer mutexMapMutex.Unlock()
  29. if mutex, ok := mutexMap[uuid]; ok {
  30. return mutex
  31. }
  32. mutex := &sync.Mutex{}
  33. mutexMap[uuid] = mutex
  34. return mutex
  35. }
  36. func (tfm myFieldNameMapper) FieldName(_ reflect.Type, f reflect.StructField) string {
  37. tag := f.Tag.Get(`json`)
  38. if idx := strings.IndexByte(tag, ','); idx != -1 {
  39. tag = tag[:idx]
  40. }
  41. if parser.IsIdentifier(tag) {
  42. return tag
  43. }
  44. return uncapitalize(f.Name)
  45. }
  46. func uncapitalize(s string) string {
  47. return strings.ToLower(s[0:1]) + s[1:]
  48. }
  49. func (tfm myFieldNameMapper) MethodName(_ reflect.Type, m reflect.Method) string {
  50. return uncapitalize(m.Name)
  51. }
  52. var RegistFuncs = map[string]interface{}{}
  53. var plugins = MakeBucket("plugins")
  54. type Route struct {
  55. Path string `json:"path"`
  56. Name string `json:"name"`
  57. Component string `json:"component,omitempty"`
  58. Routes []Route `json:"routes,omitempty"`
  59. // Key string `json:"key,omitempty"`
  60. CreateAt string `json:"create_at"`
  61. }
  62. func CancelPluginlistening(uuid string) {
  63. // logs.Info(`k, c.Function, c.Function.Rules`)
  64. for _, wait := range waits {
  65. wait.Foreach(func(k int64, c *Carry) bool {
  66. if uuid == c.UUID {
  67. c.Chan <- errors.New("uinstall")
  68. }
  69. return true
  70. })
  71. }
  72. }
  73. var debug = sillyGirl.GetBool("debug", false)
  74. func initPlugins() {
  75. storage.Watch(sillyGirl, "debug", func(old, new, key string) *storage.Final {
  76. debug = new == "true"
  77. return nil
  78. })
  79. plugins.Foreach(func(key, data []byte) error {
  80. uuid := string(key)
  81. if isNameUuid(uuid) {
  82. return nil
  83. }
  84. pluginLock.Lock()
  85. defer pluginLock.Unlock()
  86. f, cbs, err := initPlugin(string(data), uuid, "")
  87. if err != nil {
  88. console.Error("初始化插件%s错误: %v", key, err)
  89. }
  90. for _, cb := range cbs {
  91. cb()
  92. }
  93. AddCommand([]*common.Function{f})
  94. // os.WriteFile(fmt.Sprintf("%s/%s.js", pluginPath, f.Title), data, 0600)
  95. return nil
  96. })
  97. storage.Watch(plugins, nil, func(old, new, key string) (fin *storage.Final) {
  98. pluginLock.Lock()
  99. defer pluginLock.Unlock()
  100. if new == "uninstall" {
  101. new = ""
  102. fin = &storage.Final{
  103. Now: storage.EMPTY,
  104. }
  105. }
  106. if isNameUuid(key) {
  107. if new == "install" {
  108. for _, p := range plugin_list {
  109. if p.UUID != key {
  110. continue
  111. }
  112. var prefix = "?uuid=" + p.UUID
  113. address := p.Address
  114. if !strings.HasSuffix(address, "list.json") {
  115. address = address + "/api/plugins/download" + prefix
  116. } else {
  117. address = strings.ReplaceAll(address, "list.json", "download"+prefix)
  118. }
  119. resp, err := http.Get(address)
  120. if err != nil {
  121. return &storage.Final{
  122. Error: errors.New("插件源异常!"),
  123. }
  124. }
  125. zipfile := plugin_dir + "/" + utils.GenUUID() + ".zip"
  126. err = func() error {
  127. defer resp.Body.Close()
  128. f, err := os.OpenFile(zipfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
  129. if err != nil {
  130. return errors.New("打开文件异常:" + err.Error())
  131. }
  132. defer f.Close()
  133. _, err = io.Copy(f, resp.Body)
  134. if err != nil {
  135. return errors.New("文件写入异常:" + err.Error())
  136. }
  137. return nil
  138. }()
  139. if err != nil {
  140. return &storage.Final{
  141. Error: err,
  142. }
  143. }
  144. defer os.Remove(zipfile)
  145. if err := unzip(zipfile, 0755, true); err != nil {
  146. return &storage.Final{
  147. Error: errors.New("安装异常!" + err.Error()),
  148. }
  149. }
  150. return &storage.Final{
  151. Now: "",
  152. }
  153. }
  154. }
  155. {
  156. for _, f := range Functions {
  157. if f.UUID == key {
  158. filename := f.Path
  159. if new == "reload" { //重载
  160. go f.Reload()
  161. } else if new == "" {
  162. // fmt.Println("new", new)
  163. ss := strings.Split(filename, "/")
  164. processes.Range(func(key, value any) bool { //先停止脚本,避免windows锁定文件
  165. p := key.(*exec.Cmd)
  166. s := value.(common.Sender)
  167. if s.GetPluginID() == f.UUID {
  168. console.Log("已终止 % s", f.Title)
  169. func() {
  170. defer func() {
  171. recover()
  172. }()
  173. if p.Process.Kill() == nil {
  174. processes.Delete(key)
  175. }
  176. }()
  177. }
  178. return true
  179. })
  180. os.RemoveAll(filepath.Dir(filename))
  181. // fmt.Println(strings.Join(ss, " "))
  182. l := len(ss)
  183. if l > 2 {
  184. go AddNodePlugin(filename, ss[l-1], f.Type)
  185. }
  186. } else {
  187. err := os.WriteFile(filename, []byte(new), 0755)
  188. if err != nil {
  189. return &storage.Final{
  190. Error: err,
  191. }
  192. }
  193. }
  194. }
  195. }
  196. }
  197. if fin != nil {
  198. return fin
  199. }
  200. return &storage.Final{
  201. Now: "",
  202. }
  203. // }
  204. // return &storage.Final{
  205. // Error: errors.New("安装失败!!!"),
  206. // }
  207. }
  208. if new == "install" {
  209. for _, p := range plugin_list {
  210. // fmt.Println(p.UUID, p.UUID == key, p.Title)
  211. if p.UUID != key {
  212. continue
  213. }
  214. // fmt.Println("(p.Type", p.Type)
  215. script := string(fetchScript(p.Address, key))
  216. if f, _, _ := initPlugin(script, p.UUID, ""); f.CreateAt != "" {
  217. fin = &storage.Final{
  218. Now: script,
  219. }
  220. fin = &storage.Final{}
  221. su := &ScriptUtils{script: script}
  222. su.SetValue("origin", p.Organization)
  223. new = su.script
  224. break
  225. } else {
  226. return &storage.Final{
  227. Error: errors.New("订阅源异常"),
  228. }
  229. }
  230. }
  231. }
  232. if new != "" {
  233. if new == "reload" {
  234. new = old
  235. }
  236. fin = &storage.Final{}
  237. su := &ScriptUtils{script: new}
  238. if version := su.GetValue("version"); version == "" || regexp.MustCompile(`v\d+\.\d+\.\d`).FindString(version) != version {
  239. su.SetValue("version", "v1.0.0")
  240. }
  241. if auhtor := su.GetValue("author"); auhtor == "" {
  242. su.SetValue("author", "佚名")
  243. }
  244. if su.GetValue("description") == "" {
  245. su.SetValue("description", "🐒这个人很懒什么都没有留下")
  246. } //module
  247. title := su.GetValue("title")
  248. if title == "" {
  249. su.SetValue("title", "无名脚本")
  250. }
  251. if message := GetMessageByUUID(key); message != "" {
  252. su.SetValue("message", message)
  253. }
  254. if title != "无名脚本" && title != "" {
  255. onStart := su.GetValue("on_start")
  256. if onStart != "true" {
  257. module := su.GetValue("module")
  258. if module != "true" {
  259. if module != "" {
  260. su.DeleteValue("module")
  261. }
  262. web := su.GetValue("web")
  263. if web != "true" {
  264. if web != "" {
  265. su.DeleteValue("web")
  266. }
  267. // rule := su.GetValue("rule")
  268. // if rule == "" {
  269. // su.SetValue("rule", title)
  270. // }
  271. } else {
  272. su.DeleteValue("rule")
  273. su.DeleteValue("cron")
  274. // su.DeleteValue("admin")
  275. su.DeleteValue("priority")
  276. su.DeleteValue("platform")
  277. }
  278. } else {
  279. su.DeleteValue("rule")
  280. su.DeleteValue("cron")
  281. su.DeleteValue("web")
  282. // su.DeleteValue("admin")
  283. su.DeleteValue("priority")
  284. su.DeleteValue("platform")
  285. }
  286. } else {
  287. // su.DeleteValue("rule")
  288. // su.DeleteValue("cron")
  289. su.DeleteValue("web")
  290. // su.DeleteValue("admin")
  291. su.DeleteValue("priority")
  292. su.DeleteValue("platform")
  293. su.DeleteValue("module")
  294. }
  295. }
  296. create_at := su.GetValue("create_at")
  297. if _, err := time.Parse("2006-01-02 15:04:05", create_at); err != nil {
  298. su.SetValue("create_at", time.Now().Format("2006-01-02 15:04:05"))
  299. }
  300. fin.Now = su.script
  301. if su.script != new {
  302. fin.Message = su.script
  303. } else if title != (&ScriptUtils{script: old}).GetValue("title") {
  304. fin.Message = "标题变更。"
  305. }
  306. new = su.script
  307. }
  308. f, cbs, err := initPlugin(new, key, "")
  309. if err != nil && new != "" {
  310. pluginConsole(key).Error(err)
  311. }
  312. apd := false
  313. for i := range Functions {
  314. if Functions[i].UUID == key {
  315. DestroyAdapterByUUID(key)
  316. Functions[i].Running = false
  317. if len(Functions[i].CronIds) != 0 {
  318. for _, id := range Functions[i].CronIds {
  319. CRON.Remove(cron.EntryID(id))
  320. }
  321. }
  322. Functions = append(Functions[:i], Functions[i+1:]...)
  323. CancelPluginCrons(key)
  324. CancelPluginWebs(key)
  325. CancelPluginlistening(key)
  326. CancelHttpListen(key)
  327. remStatic(key)
  328. storage.DisableHandle(key)
  329. if new != "" {
  330. AddCommand([]*common.Function{f})
  331. if !f.Disable {
  332. if old == "" {
  333. // console.Log("已加载 %s%s", f.Title, f.Suffix)
  334. } else { //if !f.OnStart
  335. console.Log("已重载 %s%s", f.Title, f.Suffix)
  336. }
  337. }
  338. } else {
  339. of, _, _ := initPlugin(old, key, "")
  340. console.Log("已卸载 %s%s", of.Title, of.Suffix)
  341. }
  342. apd = true
  343. break
  344. }
  345. }
  346. for _, cb := range cbs {
  347. cb()
  348. }
  349. if !apd {
  350. AddCommand([]*common.Function{f})
  351. }
  352. // if f.UUID != "" && f.Public {
  353. // go func() {
  354. // os.WriteFile(fmt.Sprintf("%s/%s.js", plugin_download_file, f.UUID), []byte(publicScript(plugins.GetString(f.UUID))), 0666)
  355. // os.WriteFile(plugin_path+"list.json", utils.JsonMarshal(GetPublicResponse()), 0666)
  356. // }()
  357. // }
  358. return
  359. })
  360. }
  361. func initPlugin(data string, uuid string, scriptType string) (*common.Function, []func(), error) {
  362. f, cbs := pluginParse(data, uuid)
  363. f.Suffix = ".js"
  364. f.Type = "goja"
  365. script := ""
  366. if f.Encrypt {
  367. script = DecryptPlugin(string(data))
  368. } else {
  369. script = string(data)
  370. }
  371. script = halfDeEct(script)
  372. script = strings.ReplaceAll(script, "new Sender", "Sender")
  373. script = strings.ReplaceAll(script, "new Bucket", "Bucket")
  374. // script = regexp.MustCompile(`import\s+\{\s*([^\}]+)\s*\}\s*from\s*['"]([^'"]+)['"]\s*;`).ReplaceAllString(script, "const {$1} = require('$2');")
  375. // script = regexp.MustCompile(`import\s+\s*([^\}]+)\s*\s*from\s*['"]([^'"]+)['"]\s*;`).ReplaceAllString(script, "const $1 = require('$2');")
  376. var err error
  377. prg, err2 := goja.Compile(f.Title+".js", script, false)
  378. if err == nil && err2 != nil {
  379. err = err2
  380. }
  381. // if err == nil && len(rules) == 0 && cron != "" {
  382. // err = fmt.Errorf("无效的脚本%s", title)
  383. // }
  384. // if icon == "" {
  385. // icon = "https://joeschmoe.io/api/v1/random?t=" + fmt.Sprint(time.Now().Nanosecond())
  386. // }
  387. var running func() bool
  388. f.Handle = func(s common.Sender, set func(vm *goja.Runtime)) interface{} {
  389. if !debug {
  390. defer func() {
  391. err := recover()
  392. if err != nil {
  393. pluginConsole(uuid).Error(err)
  394. // s.Reply(fmt.Sprint(err))
  395. }
  396. }()
  397. }
  398. if err2 != nil {
  399. panic(err2)
  400. }
  401. loop := eventloop.NewEventLoop()
  402. loop.Run(func(vm *goja.Runtime) {
  403. SetPluginMethod(vm, uuid, f.OnStart, running)
  404. ss := &SenderJsIplm{
  405. Message: s,
  406. Vm: vm,
  407. Private: "private",
  408. Group: "group",
  409. Routine: "routine",
  410. Persistent: "persistent",
  411. UUID: uuid,
  412. }
  413. vm.Set("msg", goja.Undefined())
  414. vm.Set("message", goja.Undefined())
  415. vm.Set("res", goja.Undefined())
  416. vm.Set("req", goja.Undefined())
  417. vm.Set("action", goja.Undefined())
  418. vm.Set("sender", ss)
  419. vm.Set("run", func(uuid string) bool { //执行子脚本
  420. fs := Functions
  421. for i := range fs {
  422. if fs[i].UUID == uuid {
  423. fs[i].Handle(s, nil)
  424. return true
  425. }
  426. }
  427. return false
  428. })
  429. vm.Set("s", ss)
  430. vm.Set("InitAdapter", func(plt, botid string, params map[string]interface{}) *Factory {
  431. f := &Factory{
  432. uuid: uuid,
  433. vm: vm,
  434. }
  435. f.Init(plt, botid, params)
  436. return f
  437. })
  438. vm.Set("initAdapter", func(plt, botid string, params map[string]interface{}) *Factory {
  439. f := &Factory{
  440. uuid: uuid,
  441. vm: vm,
  442. }
  443. f.Init(plt, botid, params)
  444. return f
  445. })
  446. getAdapter := func(plt, botid string) map[string]interface{} {
  447. adapter, err := GetAdapter(plt, botid)
  448. errstr := ""
  449. if err != nil {
  450. errstr = err.Error()
  451. }
  452. return map[string]interface{}{
  453. "error": errstr,
  454. "adapter": adapter,
  455. }
  456. }
  457. vm.Set("GetAdapter", getAdapter)
  458. vm.Set("getAdapter", getAdapter)
  459. vm.Set("getAdapterBotsID", GetAdapterBotsID)
  460. vm.Set("getAdapterBotPlts", GetAdapterBotPlts)
  461. vm.Set("GetAdapterBotsID", GetAdapterBotsID)
  462. vm.Set("GetAdapterBotPlts", GetAdapterBotPlts)
  463. vm.Set("running", running)
  464. vm.Set("Running", running)
  465. vm.Set("uuid", func() string {
  466. return uuid
  467. })
  468. vm.Set("genUuid", func() string {
  469. return utils.GenUUID()
  470. })
  471. vm.Set("genUUID", func() string {
  472. return utils.GenUUID()
  473. })
  474. vm.Set("UUID", func() string {
  475. return uuid
  476. })
  477. if set != nil {
  478. set(vm)
  479. }
  480. _, err := vm.RunProgram(prg)
  481. if err != nil {
  482. pluginConsole(uuid).Error(strings.ReplaceAll(strings.ReplaceAll(err.Error(), "node_modules/", ""), "github.com/dop251/goja_nodejs/require", ""))
  483. }
  484. })
  485. return nil
  486. }
  487. running = func() bool {
  488. return f.Running
  489. }
  490. return f, cbs, err
  491. }
  492. func GetFunctionByUUID(uuid string) *common.Function {
  493. for _, f := range Functions {
  494. if f.UUID == uuid {
  495. return f
  496. }
  497. }
  498. return nil
  499. }
  500. func ChatID(p interface{}) string {
  501. switch p := p.(type) {
  502. case int:
  503. if p == 0 {
  504. return ""
  505. } else {
  506. return utils.Itoa(p)
  507. }
  508. case string:
  509. return p
  510. case nil:
  511. return ""
  512. default:
  513. return utils.Itoa(p)
  514. }
  515. }