dkforest

A forum and chat platform (onion)
git clone https://git.dasho.dev/n0tr1v/dkforest.git
Log | Files | Refs | LICENSE

snippetInterceptor.go (1597B)


      1 package interceptors
      2 
      3 import (
      4 	"dkforest/pkg/database"
      5 	"dkforest/pkg/managers"
      6 	"dkforest/pkg/web/handlers/interceptors/command"
      7 	"strings"
      8 )
      9 
     10 type SnippetInterceptor struct{}
     11 
     12 func (i SnippetInterceptor) InterceptMsg(cmd *command.Command) {
     13 	// Snippets actually mutate the original message,
     14 	// to simulate that the user actually typed the text
     15 	cmd.OrigMessage = snippets(cmd.DB, cmd.AuthUser.ID, cmd.OrigMessage)
     16 
     17 	cmd.OrigMessage = autocompleteTags(cmd.OrigMessage)
     18 
     19 	cmd.Message = cmd.OrigMessage
     20 }
     21 
     22 func snippets(db *database.DkfDB, authUserID database.UserID, html string) string {
     23 	if snippetRgx.MatchString(html) {
     24 		userSnippets, _ := db.GetUserSnippets(authUserID)
     25 		if len(userSnippets) > 0 {
     26 			// Build hashmap for fast lookup
     27 			m := make(map[string]string)
     28 			for _, snippet := range userSnippets {
     29 				m["!"+snippet.Name] = snippet.Text
     30 			}
     31 			html = snippetRgx.ReplaceAllStringFunc(html, func(s string) string {
     32 				// If snippet name exists, use the mapped value
     33 				if v, ok := m[s]; ok {
     34 					return v
     35 				}
     36 				return s
     37 			})
     38 		}
     39 	}
     40 	return html
     41 }
     42 
     43 func autocompleteTags(html string) string {
     44 	activeUsers := managers.ActiveUsers.GetActiveUsers()
     45 	html = autoTagRgx.ReplaceAllStringFunc(html, func(s string) string {
     46 		if strings.HasPrefix(s, `\`) {
     47 			return strings.TrimPrefix(s, `\`)
     48 		}
     49 		s1 := strings.TrimPrefix(s, "@")
     50 		s1 = strings.TrimSuffix(s1, "*")
     51 		s1 = strings.ToLower(s1)
     52 		for _, au := range activeUsers {
     53 			l := strings.ToLower(string(au.Username))
     54 			if strings.HasPrefix(l, s1) {
     55 				return au.Username.AtStr()
     56 			}
     57 		}
     58 		return s
     59 	})
     60 	return html
     61 }