collection.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package seo
  2. import (
  3. "context"
  4. "net/http"
  5. "net/url"
  6. "path"
  7. "reflect"
  8. "regexp"
  9. "strings"
  10. "github.com/qor5/admin/l10n"
  11. h "github.com/theplant/htmlgo"
  12. "gorm.io/gorm"
  13. )
  14. var (
  15. GlobalSEO = "Global SEO"
  16. GlobalDB *gorm.DB
  17. DBContextKey contextKey = "DB"
  18. )
  19. type (
  20. contextKey string
  21. contextVariablesFunc func(interface{}, *Setting, *http.Request) string
  22. )
  23. // Create a SeoCollection instance
  24. func NewCollection() *Collection {
  25. collection := &Collection{
  26. settingModel: &QorSEOSetting{},
  27. dbContextKey: DBContextKey,
  28. globalName: GlobalSEO,
  29. inherited: true,
  30. }
  31. collection.RegisterSEO(GlobalSEO).RegisterSettingVaribles(struct{ SiteName string }{}).
  32. RegisterContextVariables(
  33. "og:url", func(_ interface{}, _ *Setting, req *http.Request) string {
  34. return req.URL.String()
  35. },
  36. )
  37. return collection
  38. }
  39. // Collection will hold registered seo configures and global setting definition and other configures
  40. // @snippet_begin(SeoCollectionDefinition)
  41. type Collection struct {
  42. registeredSEO []*SEO
  43. globalName string //default name is GlobalSEO
  44. inherited bool //default is true. the order is model seo setting, system seo setting, global seo setting
  45. dbContextKey interface{} // get db from context
  46. settingModel interface{} // db model
  47. }
  48. // @snippet_end
  49. // SEO represents a seo object for a page
  50. // @snippet_begin(SeoDefinition)
  51. type SEO struct {
  52. name string
  53. modelTyp reflect.Type
  54. contextVariables map[string]contextVariablesFunc // fetch context variables from request
  55. settingVariables interface{} // fetch setting variables from db
  56. }
  57. // @snippet_end
  58. // RegisterModel register a model to seo
  59. func (seo *SEO) SetModel(model interface{}) *SEO {
  60. seo.modelTyp = reflect.Indirect(reflect.ValueOf(model)).Type()
  61. return seo
  62. }
  63. // SetName set seo name
  64. func (seo *SEO) SetName(name string) *SEO {
  65. seo.name = name
  66. return seo
  67. }
  68. // RegisterContextVariables register context variables. the registered variables will be rendered to the page
  69. func (seo *SEO) RegisterContextVariables(key string, f contextVariablesFunc) *SEO {
  70. if seo.contextVariables == nil {
  71. seo.contextVariables = map[string]contextVariablesFunc{}
  72. }
  73. seo.contextVariables[key] = f
  74. return seo
  75. }
  76. // RegisterSettingVaribles register a setting variable
  77. func (seo *SEO) RegisterSettingVaribles(setting interface{}) *SEO {
  78. seo.settingVariables = setting
  79. return seo
  80. }
  81. func (collection *Collection) SetGlobalName(name string) *Collection {
  82. collection.globalName = name
  83. if globalSeo := collection.GetSEOByName(GlobalSEO); globalSeo != nil {
  84. globalSeo.SetName(name)
  85. }
  86. return collection
  87. }
  88. func (collection *Collection) NewSettingModelInstance() interface{} {
  89. return reflect.New(reflect.Indirect(reflect.ValueOf(collection.settingModel)).Type()).Interface()
  90. }
  91. func (collection *Collection) NewSettingModelSlice() interface{} {
  92. sliceType := reflect.SliceOf(reflect.PtrTo(reflect.Indirect(reflect.ValueOf(collection.settingModel)).Type()))
  93. slice := reflect.New(sliceType)
  94. slice.Elem().Set(reflect.MakeSlice(sliceType, 0, 0))
  95. return slice.Interface()
  96. }
  97. // RegisterVariblesSetting register variables setting
  98. func (collection *Collection) SetInherited(b bool) *Collection {
  99. collection.inherited = b
  100. return collection
  101. }
  102. // RegisterVariblesSetting register variables setting
  103. func (collection *Collection) SetSettingModel(s interface{}) *Collection {
  104. collection.settingModel = s
  105. return collection
  106. }
  107. // RegisterDBContextKey register a key to get db from context
  108. func (collection *Collection) SetDBContextKey(key interface{}) *Collection {
  109. collection.dbContextKey = key
  110. return collection
  111. }
  112. // RegisterSEOByNames register mutiple seo by names
  113. func (collection *Collection) RegisterSEOByNames(names ...string) *Collection {
  114. for index := range names {
  115. collection.registeredSEO = append(collection.registeredSEO, &SEO{name: names[index]})
  116. }
  117. return collection
  118. }
  119. // RegisterSEO register a seo
  120. func (collection *Collection) RegisterSEO(obj interface{}) (seo *SEO) {
  121. if name, ok := obj.(string); ok {
  122. seo = &SEO{name: name}
  123. } else {
  124. typ := reflect.Indirect(reflect.ValueOf(obj)).Type()
  125. seo = &SEO{name: typ.Name(), modelTyp: typ}
  126. }
  127. collection.registeredSEO = append(collection.registeredSEO, seo)
  128. return
  129. }
  130. // RegisterSEO remove a seo
  131. func (collection *Collection) RemoveSEO(obj interface{}) *Collection {
  132. var name string
  133. if n, ok := obj.(string); ok {
  134. name = n
  135. } else {
  136. name = reflect.Indirect(reflect.ValueOf(obj)).Type().Name()
  137. }
  138. for index, s := range collection.registeredSEO {
  139. if s.name == name {
  140. collection.registeredSEO = append(collection.registeredSEO[:index], collection.registeredSEO[index+1:]...)
  141. break
  142. }
  143. }
  144. return collection
  145. }
  146. // GetSEO get a Seo
  147. func (collection *Collection) GetSEO(obj interface{}) *SEO {
  148. if name, ok := obj.(string); ok {
  149. return collection.GetSEOByName(name)
  150. } else {
  151. return collection.GetSEOByModel(obj)
  152. }
  153. }
  154. // GetSEO get a Seo by name
  155. func (collection *Collection) GetSEOByName(name string) *SEO {
  156. for _, s := range collection.registeredSEO {
  157. if s.name == name {
  158. return s
  159. }
  160. }
  161. return nil
  162. }
  163. // GetSEOByModel get a seo by model
  164. func (collection *Collection) GetSEOByModel(model interface{}) *SEO {
  165. for _, s := range collection.registeredSEO {
  166. if reflect.Indirect(reflect.ValueOf(model)).Type() == s.modelTyp {
  167. return s
  168. }
  169. }
  170. return nil
  171. }
  172. // RenderGlobal render global seo
  173. func (collection Collection) RenderGlobal(req *http.Request) h.HTMLComponent {
  174. return collection.Render(collection.globalName, req)
  175. }
  176. // Render render seo tags
  177. func (collection Collection) Render(obj interface{}, req *http.Request) h.HTMLComponent {
  178. var (
  179. db = collection.getDBFromContext(req.Context())
  180. sortedSEOs []*SEO
  181. sortedSeoNames []string
  182. sortedDBSettings []QorSEOSettingInterface
  183. sortedSettings []Setting
  184. setting Setting
  185. locale string
  186. )
  187. // sort all SEOs
  188. globalSeo := collection.GetSEO(collection.globalName)
  189. if globalSeo == nil {
  190. return h.RawHTML("")
  191. }
  192. sortedSEOs = append(sortedSEOs, globalSeo)
  193. if name, ok := obj.(string); !ok || name != collection.globalName {
  194. if seo := collection.GetSEO(obj); seo != nil {
  195. sortedSeoNames = append(sortedSeoNames, seo.name)
  196. sortedSEOs = append(sortedSEOs, seo)
  197. }
  198. }
  199. sortedSeoNames = append(sortedSeoNames, globalSeo.name)
  200. if v, ok := obj.(l10n.L10nInterface); ok {
  201. locale = v.GetLocale()
  202. }
  203. // sort all QorSEOSettingInterface
  204. var settingModelSlice = collection.NewSettingModelSlice()
  205. if db.Find(settingModelSlice, "name in (?) AND locale_code = ?", sortedSeoNames, locale).Error != nil {
  206. return h.RawHTML("")
  207. }
  208. reflectVlaue := reflect.Indirect(reflect.ValueOf(settingModelSlice))
  209. for _, name := range sortedSeoNames {
  210. for i := 0; i < reflectVlaue.Len(); i++ {
  211. if modelSetting, ok := reflectVlaue.Index(i).Interface().(QorSEOSettingInterface); ok && modelSetting.GetName() == name {
  212. sortedDBSettings = append(sortedDBSettings, modelSetting)
  213. }
  214. }
  215. }
  216. // sort all settings
  217. if _, ok := obj.(string); !ok {
  218. if value := reflect.Indirect(reflect.ValueOf(obj)); value.IsValid() && value.Kind() == reflect.Struct {
  219. for i := 0; i < value.NumField(); i++ {
  220. if value.Field(i).Type() == reflect.TypeOf(Setting{}) {
  221. if setting := value.Field(i).Interface().(Setting); setting.EnabledCustomize {
  222. sortedSettings = append(sortedSettings, setting)
  223. }
  224. break
  225. }
  226. }
  227. }
  228. }
  229. for _, s := range sortedDBSettings {
  230. sortedSettings = append(sortedSettings, s.GetSEOSetting())
  231. }
  232. // get the final setting from sortedSettings
  233. for i, s := range sortedSettings {
  234. if !collection.inherited && i >= 1 {
  235. break
  236. }
  237. if s.Title != "" && setting.Title == "" {
  238. setting.Title = s.Title
  239. }
  240. if s.Description != "" && setting.Description == "" {
  241. setting.Description = s.Description
  242. }
  243. if s.Keywords != "" && setting.Keywords == "" {
  244. setting.Keywords = s.Keywords
  245. }
  246. if s.OpenGraphURL != "" && setting.OpenGraphURL == "" {
  247. setting.OpenGraphURL = s.OpenGraphURL
  248. }
  249. if s.OpenGraphType != "" && setting.OpenGraphType == "" {
  250. setting.OpenGraphType = s.OpenGraphType
  251. }
  252. if s.OpenGraphImageURL != "" && setting.OpenGraphImageURL == "" {
  253. setting.OpenGraphImageURL = s.OpenGraphImageURL
  254. }
  255. if s.OpenGraphImageFromMediaLibrary.URL("og") != "" && setting.OpenGraphImageURL == "" {
  256. setting.OpenGraphImageURL = s.OpenGraphImageFromMediaLibrary.URL("og")
  257. }
  258. if len(s.OpenGraphMetadata) > 0 && len(setting.OpenGraphMetadata) == 0 {
  259. setting.OpenGraphMetadata = s.OpenGraphMetadata
  260. }
  261. }
  262. if setting.OpenGraphURL != "" && !isAbsoluteURL(setting.OpenGraphURL) {
  263. var u url.URL
  264. u.Host = req.Host
  265. if req.URL.Scheme != "" {
  266. u.Scheme = req.URL.Scheme
  267. } else {
  268. u.Scheme = "http"
  269. }
  270. setting.OpenGraphURL = path.Join(u.String(), setting.OpenGraphURL)
  271. }
  272. // fetch all variables and tags from context
  273. var (
  274. variables = map[string]string{}
  275. tags = map[string]string{}
  276. )
  277. for _, s := range sortedDBSettings {
  278. for key, val := range s.GetVariables() {
  279. variables[key] = val
  280. }
  281. }
  282. for i, seo := range sortedSEOs {
  283. for key, f := range seo.contextVariables {
  284. value := f(obj, &setting, req)
  285. if strings.Contains(key, ":") && collection.inherited {
  286. tags[key] = value
  287. } else if strings.Contains(key, ":") && !collection.inherited && i == 0 {
  288. tags[key] = value
  289. } else {
  290. variables[key] = f(obj, &setting, req)
  291. }
  292. }
  293. }
  294. setting = replaceVariables(setting, variables)
  295. return setting.HTMLComponent(tags)
  296. }
  297. // GetDB get db from context
  298. func (collection Collection) getDBFromContext(ctx context.Context) *gorm.DB {
  299. if contextdb := ctx.Value(collection.dbContextKey); contextdb != nil {
  300. return contextdb.(*gorm.DB)
  301. }
  302. return GlobalDB
  303. }
  304. var regex = regexp.MustCompile("{{([a-zA-Z0-9]*)}}")
  305. func replaceVariables(setting Setting, values map[string]string) Setting {
  306. replace := func(str string) string {
  307. matches := regex.FindAllStringSubmatch(str, -1)
  308. for _, match := range matches {
  309. str = strings.Replace(str, match[0], values[match[1]], 1)
  310. }
  311. return str
  312. }
  313. setting.Title = replace(setting.Title)
  314. setting.Description = replace(setting.Description)
  315. setting.Keywords = replace(setting.Keywords)
  316. return setting
  317. }
  318. func isAbsoluteURL(str string) bool {
  319. if u, err := url.Parse(str); err == nil && u.IsAbs() {
  320. return true
  321. }
  322. return false
  323. }
  324. func ContextWithDB(ctx context.Context, db *gorm.DB) context.Context {
  325. return context.WithValue(ctx, DBContextKey, db)
  326. }