Class: Site

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Serialization
Defined in:
app/models/site.rb

Overview

A class we can use to serialize the site data

Constant Summary collapse

SITE_JSON_CHANNEL =
"/site_json"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(guardian) ⇒ Site

Returns a new instance of Site.



36
37
38
# File 'app/models/site.rb', line 36

def initialize(guardian)
  @guardian = guardian
end

Class Method Details

.add_categories_callbacks(&block) ⇒ Object



28
29
30
# File 'app/models/site.rb', line 28

def self.add_categories_callbacks(&block)
  categories_callbacks << block
end

.all_categories_cacheObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'app/models/site.rb', line 64

def self.all_categories_cache
  # Categories do not change often so there is no need for us to run the
  # same query and spend time creating ActiveRecord objects for every requests.
  #
  # Do note that any new association added to the eager loading needs a
  # corresponding ActiveRecord callback to clear the categories cache.
  Discourse
    .cache
    .fetch(categories_cache_key, expires_in: 30.minutes) do
      categories =
        begin
          query =
            Category
              .includes(
                :uploaded_logo,
                :uploaded_logo_dark,
                :uploaded_background,
                :uploaded_background_dark,
                :tags,
                :tag_groups,
                :form_templates,
                category_required_tag_groups: :tag_group,
              )
              .joins("LEFT JOIN topics t on t.id = categories.topic_id")
              .select("categories.*, t.slug topic_slug")
              .order(:position)

          query =
            DiscoursePluginRegistry.apply_modifier(:site_all_categories_cache_query, query, self)

          query.to_a
        end

      if preloaded_category_custom_fields.present?
        Category.preload_custom_fields(categories, preloaded_category_custom_fields)
      end

      ActiveModel::ArraySerializer.new(
        categories,
        each_serializer: SiteCategorySerializer,
      ).as_json
    end
end

.categories_cache_keyObject



56
57
58
# File 'app/models/site.rb', line 56

def self.categories_cache_key
  "site_categories_#{Discourse.git_version}"
end

.categories_callbacksObject



32
33
34
# File 'app/models/site.rb', line 32

def self.categories_callbacks
  @categories_callbacks ||= []
end

.clear_anon_cache!Object



250
251
252
253
254
# File 'app/models/site.rb', line 250

def self.clear_anon_cache!
  # publishing forces the sequence up
  # the cache is validated based on the sequence
  MessageBus.publish(SITE_JSON_CHANNEL, "")
end

.clear_cacheObject



60
61
62
# File 'app/models/site.rb', line 60

def self.clear_cache
  Discourse.cache.delete(categories_cache_key)
end

.json_for(guardian) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'app/models/site.rb', line 201

def self.json_for(guardian)
  if guardian.anonymous? && SiteSetting.
    return(
      {
        periods: TopTopic.periods.map(&:to_s),
        filters: Discourse.filters.map(&:to_s),
        user_fields:
          UserField
            .includes(:user_field_options)
            .order(:position)
            .all
            .map { |userfield| UserFieldSerializer.new(userfield, root: false, scope: guardian) },
        auth_providers:
          Discourse.enabled_auth_providers.map do |provider|
            AuthProviderSerializer.new(provider, root: false, scope: guardian)
          end,
      }.to_json
    )
  end

  seq = nil

  if guardian.anonymous?
    seq = MessageBus.last_id("/site_json")

    cached_json, cached_seq, cached_version =
      Discourse.redis.mget("site_json", "site_json_seq", "site_json_version")

    if cached_json && seq == cached_seq.to_i && Discourse.git_version == cached_version
      return cached_json
    end
  end

  site = Site.new(guardian)
  json = MultiJson.dump(SiteSerializer.new(site, root: false, scope: guardian))

  if guardian.anonymous?
    Discourse.redis.multi do |transaction|
      transaction.setex "site_json", 1800, json
      transaction.set "site_json_seq", seq
      transaction.set "site_json_version", Discourse.git_version
    end
  end

  json
end

.reset_preloaded_category_custom_fieldsObject



9
10
11
# File 'app/models/site.rb', line 9

def self.reset_preloaded_category_custom_fields
  self.preloaded_category_custom_fields = Set.new
end

Instance Method Details

#anonymous_sidebar_sectionsObject



186
187
188
189
190
191
# File 'app/models/site.rb', line 186

def anonymous_sidebar_sections
  SidebarSection
    .public_sections
    .includes(:sidebar_urls)
    .order("(section_type IS NOT NULL) DESC, (public IS TRUE) DESC")
end

#archetypesObject



193
194
195
# File 'app/models/site.rb', line 193

def archetypes
  Archetype.list.reject { |t| t.id == Archetype.private_message }
end

#auth_providersObject



197
198
199
# File 'app/models/site.rb', line 197

def auth_providers
  Discourse.enabled_auth_providers
end

#categoriesObject



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'app/models/site.rb', line 108

def categories
  if @guardian.can_lazy_load_categories?
    preloaded_category_ids = []
    if @guardian.authenticated?
      sidebar_category_ids = @guardian.user.secured_sidebar_category_ids(@guardian)
      preloaded_category_ids.concat(
        Category.secured(@guardian).ancestors_of(sidebar_category_ids).pluck(:id),
      )
      preloaded_category_ids.concat(sidebar_category_ids)
    end
  end

  @categories ||=
    begin
      categories = []

      self.class.all_categories_cache.each do |category|
        if (
             !@guardian.can_lazy_load_categories? ||
               preloaded_category_ids.include?(category[:id])
           ) &&
             @guardian.can_see_serialized_category?(
               category_id: category[:id],
               read_restricted: category[:read_restricted],
             )
          categories << category
        end
      end

      with_children = Set.new
      categories.each { |c| with_children << c[:parent_category_id] if c[:parent_category_id] }

      allowed_topic_create = nil
      unless @guardian.is_admin?
        allowed_topic_create_ids =
          @guardian.anonymous? ? [] : Category.topic_create_allowed(@guardian).pluck(:id)
        allowed_topic_create = Set.new(allowed_topic_create_ids)
      end

      by_id = {}

      notification_levels = CategoryUser.notification_levels_for(@guardian.user)
      default_notification_level = CategoryUser.default_notification_level

      categories.each do |category|
        category[:notification_level] = notification_levels[category[:id]] ||
          default_notification_level
        category[:permission] = CategoryGroup.permission_types[
          :full
        ] if allowed_topic_create&.include?(category[:id]) || @guardian.is_admin?
        category[:has_children] = with_children.include?(category[:id])

        category[:can_edit] = @guardian.can_edit_serialized_category?(
          category_id: category[:id],
          read_restricted: category[:read_restricted],
        )

        by_id[category[:id]] = category
      end

      categories.reject! { |c| c[:parent_category_id] && !by_id[c[:parent_category_id]] }

      self.class.categories_callbacks.each { |callback| callback.call(categories, @guardian) }

      categories
    end
end

#groupsObject



176
177
178
179
180
181
182
183
184
# File 'app/models/site.rb', line 176

def groups
  query =
    Group.visible_groups(@guardian.user, "groups.name ASC", include_everyone: true).includes(
      :flair_upload,
    )
  query = DiscoursePluginRegistry.apply_modifier(:site_groups_query, query, self)

  query
end

#markdown_additional_optionsObject

Sometimes plugins need to have additional data or options available when rendering custom markdown features/rules that are not available on the default opts.discourse object. These additional options should be namespaced to the plugin adding them.

“‘ Site.markdown_additional_options = { limited_pretty_text_markdown_rules: [] } “`

These are passed down to markdown rules on opts.discourse.additionalOptions.



25
# File 'app/models/site.rb', line 25

cattr_accessor :markdown_additional_options

#notification_typesObject



44
45
46
# File 'app/models/site.rb', line 44

def notification_types
  Notification.types
end

#site_settingObject



40
41
42
# File 'app/models/site.rb', line 40

def site_setting
  SiteSetting
end

#trust_levelsObject



48
49
50
# File 'app/models/site.rb', line 48

def trust_levels
  TrustLevel.levels
end

#user_fieldsObject



52
53
54
# File 'app/models/site.rb', line 52

def user_fields
  UserField.includes(:user_field_options).order(:position).all
end