github.com/jamiefdhurst/journal@v0.9.2/internal/app/model/giphy.go (about) 1 package model 2 3 import ( 4 "regexp" 5 "strings" 6 7 "github.com/jamiefdhurst/journal/internal/app" 8 ) 9 10 type giphyContent struct { 11 IDs []string 12 searches []string 13 } 14 15 // GiphysExtractor Interface for extracting a Giphy search 16 type GiphysExtractor interface { 17 ExtractContentsAndSearchAPI(s string) string 18 } 19 20 // GiphyAdapter Get the correct adapter to use depending on wither an API key is available 21 func GiphyAdapter(c *app.Container) GiphysExtractor { 22 if c.Giphy == nil { 23 return &GiphysDisabled{Container: c} 24 } 25 return &Giphys{Container: c} 26 } 27 28 // GiphysDisabled Whne no API key available, perform no action 29 type GiphysDisabled struct { 30 Container *app.Container 31 } 32 33 // ExtractContentsAndSearchAPI Perform no action without an API key 34 func (gs *GiphysDisabled) ExtractContentsAndSearchAPI(s string) string { 35 return s 36 } 37 38 // Giphys Common resource link for Giphy actions 39 type Giphys struct { 40 Container *app.Container 41 } 42 43 // ConvertIDsToIframes Convert any IDs in the content into <iframe> embeds 44 func (gs *Giphys) ConvertIDsToIframes(s string) string { 45 content := gs.findTags(s) 46 if len(content.IDs) > 0 { 47 for _, i := range content.IDs { 48 s = strings.Replace(s, ":gif:id:"+i, "<iframe src=\"https://giphy.com/embed/"+i+"\"></iframe>", 1) 49 } 50 } 51 52 return s 53 } 54 55 // ExtractContentsAndSearchAPI Convert any searches, connecting to Giphy where required 56 func (gs *Giphys) ExtractContentsAndSearchAPI(s string) string { 57 content := gs.findTags(s) 58 if len(content.searches) > 0 { 59 for _, i := range content.searches { 60 id, err := gs.Container.Giphy.SearchForID(i) 61 if err == nil { 62 s = strings.Replace(s, ":gif:"+i, ":gif:id:"+id, 1) 63 } else { 64 s = strings.Replace(s, ":gif:"+i, "", 1) 65 } 66 } 67 } 68 69 return s 70 } 71 72 func (gs Giphys) findIds(s string) []string { 73 reIDs := regexp.MustCompile(":gif:id:(\\w+)") 74 onlyIDs := []string{} 75 IDs := reIDs.FindAllStringSubmatch(s, -1) 76 for _, i := range IDs { 77 onlyIDs = append(onlyIDs, i[1]) 78 } 79 80 return onlyIDs 81 } 82 83 func (gs Giphys) findSearches(s string) []string { 84 reSearches := regexp.MustCompile("gif:([\\w\\-]+)") 85 onlySearches := []string{} 86 searches := reSearches.FindAllStringSubmatch(s, -1) 87 for _, j := range searches { 88 if j[1] != "id" { 89 onlySearches = append(onlySearches, j[1]) 90 } 91 } 92 93 return onlySearches 94 } 95 96 func (gs Giphys) findTags(s string) giphyContent { 97 return giphyContent{gs.findIds(s), gs.findSearches(s)} 98 }