Completed
Branch v2.4-alpha (b4736b)
by Ahmad
05:54
created

RoomsController   F

Complexity

Total Complexity 75

Size/Duplication

Total Lines 345
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 345
rs 2.4
c 1
b 0
f 0
wmc 75

12 Methods

Rating   Name   Duplication   Size   Complexity  
A show() 0 35 4
A room_params() 0 4 1
A verify_user_not_admin() 0 3 2
A room_limit_exceeded() 0 9 3
A login() 0 7 2
B create() 0 26 5
A destroy() 0 9 3
A auth_required() 0 3 1
A default_meeting_options() 0 11 1
A update() 0 9 3
A join_specific_room() 0 11 2
B join_room() 0 27 5

How to fix   Complexity   

Complex Class

Complex classes like RoomsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# frozen_string_literal: true
2
3
# BigBlueButton open source conferencing system - http://www.bigbluebutton.org/.
4
#
5
# Copyright (c) 2018 BigBlueButton Inc. and by respective authors (see below).
6
#
7
# This program is free software; you can redistribute it and/or modify it under the
8
# terms of the GNU Lesser General Public License as published by the Free Software
9
# Foundation; either version 3.0 of the License, or (at your option) any later
10
# version.
11
#
12
# BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY
13
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
14
# PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
15
#
16
# You should have received a copy of the GNU Lesser General Public License along
17
# with BigBlueButton; if not, see <http://www.gnu.org/licenses/>.
18
19
class RoomsController < ApplicationController
20
  include Pagy::Backend
21
  include Recorder
22
23
  before_action :validate_accepted_terms, unless: -> { !Rails.configuration.terms }
24
  before_action :validate_verified_email, except: [:show, :join],
25
                unless: -> { !Rails.configuration.enable_email_verification }
26
  before_action :find_room, except: [:create, :join_specific_room]
27
  before_action :verify_room_ownership, except: [:create, :show, :join, :logout, :login, :join_specific_room]
28
  before_action :verify_room_owner_verified, only: [:show, :join],
29
                unless: -> { !Rails.configuration.enable_email_verification }
30
  before_action :verify_user_not_admin, only: [:show]
31
32
  # POST /
33
  def create
34
    # Return to root if user is not signed in
35
    return redirect_to root_path unless current_user
36
37
    # Check if the user has not exceeded the room limit
38
    return redirect_to current_user.main_room, flash: { alert: I18n.t("room.room_limit") } if room_limit_exceeded
39
40
    # Create room
41
    @room = Room.new(name: room_params[:name], access_code: room_params[:access_code])
42
    @room.owner = current_user
43
    @room.room_settings = create_room_settings_string(room_params)
44
45
    # Save the room
46
    if @room.save
47
      logger.info "Support: #{current_user.email} has created a new room #{@room.uid}."
48
49
      # Start the room if auto join was turned on
50
      if room_params[:auto_join] == "1"
51
        start
52
      else
53
        redirect_to @room, flash: { success: I18n.t("room.create_room_success") }
54
      end
55
    else
56
      redirect_to current_user.main_room, flash: { alert: I18n.t("room.create_room_error") }
57
    end
58
  end
59
60
  # GET /:room_uid
61
  def show
62
    @anyone_can_start = JSON.parse(@room[:room_settings])["anyoneCanStart"]
63
    @room_running = room_running?(@room.bbb_id)
64
65
    # If its the current user's room
66
    if current_user && @room.owned_by?(current_user)
67
      if current_user.highest_priority_role.can_create_rooms
68
        # User is allowed to have rooms
69
        @search, @order_column, @order_direction, recs =
70
          recordings(@room.bbb_id, params.permit(:search, :column, :direction), true)
71
72
        @pagy, @recordings = pagy_array(recs)
73
      else
74
        # Render view for users that cant create rooms
75
        @recent_rooms = Room.where(id: cookies.encrypted["#{current_user.uid}_recently_joined_rooms"])
76
        render :cant_create_rooms
77
      end
78
    else
79
      # Get users name
80
      @name = if current_user
81
        current_user.name
82
      elsif cookies.encrypted[:greenlight_name]
83
        cookies.encrypted[:greenlight_name]
84
      else
85
        ""
86
      end
87
88
      @search, @order_column, @order_direction, pub_recs =
89
        public_recordings(@room.bbb_id, params.permit(:search, :column, :direction), true)
90
91
      @pagy, @public_recordings = pagy_array(pub_recs)
92
93
      render :join
94
    end
95
  end
96
97
  # PATCH /:room_uid
98
  def update
99
    if params[:setting] == "rename_header"
100
      update_room_attributes("name")
101
    elsif params[:setting] == "rename_recording"
102
      update_recording(params[:record_id], "meta_name" => params[:record_name])
103
    end
104
105
    redirect_back fallback_location: room_path
106
  end
107
108
  # POST /:room_uid
109
  def join
110
    return redirect_to root_path,
111
      flash: { alert: I18n.t("administrator.site_settings.authentication.user-info") } if auth_required
112
113
    unless @room.owned_by?(current_user)
114
      # Don't allow users to join unless they have a valid access code or the room doesn't have an access code
115
      if @room.access_code && [email protected]_code.empty? && @room.access_code != session[:access_code]
116
        return redirect_to room_path(room_uid: params[:room_uid]), flash: { alert: I18n.t("room.access_code_required") }
117
      end
118
119
      # Assign join name if passed.
120
      if params[@room.invite_path]
121
        @join_name = params[@room.invite_path][:join_name]
122
      elsif !params[:join_name]
123
        # Join name not passed.
124
        return
125
      end
126
    end
127
128
    # create or update cookie with join name
129
    cookies.encrypted[:greenlight_name] = @join_name unless cookies.encrypted[:greenlight_name] == @join_name
130
131
    if current_user
132
      # create or update cookie to track the three most recent rooms a user joined
133
      recently_joined_rooms = cookies.encrypted["#{current_user.uid}_recently_joined_rooms"].to_a
134
      cookies.encrypted["#{current_user.uid}_recently_joined_rooms"] =
135
        recently_joined_rooms.prepend(@room.id).uniq[0..2]
136
    end
137
138
    logger.info "Support: #{current_user.present? ? current_user.email : @join_name} is joining room #{@room.uid}"
139
    join_room(default_meeting_options)
140
  end
141
142
  # DELETE /:room_uid
143
  def destroy
144
    # Don't delete the users home room.
145
    if @room.owned_by?(current_user) && @room != current_user.main_room
146
      @room.destroy
147
      delete_all_recordings(@room.bbb_id)
148
    end
149
150
    redirect_to current_user.main_room
151
  end
152
153
  # POST /room/join
154
  def join_specific_room
155
    room_uid = params[:join_room][:url].split('/').last
156
157
    begin
158
      @room = Room.find_by!(uid: room_uid)
159
    rescue ActiveRecord::RecordNotFound
160
      return redirect_to current_user.main_room, alert: I18n.t("room.no_room.invalid_room_uid")
161
    end
162
163
    redirect_to room_path(@room)
164
  end
165
166
  # POST /:room_uid/start
167
  def start
168
    logger.info "Support: #{current_user.email} is starting room #{@room.uid}"
169
170
    # Join the user in and start the meeting.
171
    opts = default_meeting_options
172
    opts[:user_is_moderator] = true
173
174
    # Include the user's choices for the room settings
175
    room_settings = JSON.parse(@room[:room_settings])
176
    opts[:mute_on_start] = room_settings["muteOnStart"] if room_settings["muteOnStart"]
177
    opts[:require_moderator_approval] = room_settings["requireModeratorApproval"]
178
179
    begin
180
      redirect_to join_path(@room, current_user.name, opts, current_user.uid)
181
    rescue BigBlueButton::BigBlueButtonException => e
182
      logger.error("Support: #{@room.uid} start failed: #{e}")
183
184
      redirect_to room_path, alert: I18n.t(e.key.to_s.underscore, default: I18n.t("bigbluebutton_exception"))
185
    end
186
187
    # Notify users that the room has started.
188
    # Delay 5 seconds to allow for server start, although the request will retry until it succeeds.
189
    NotifyUserWaitingJob.set(wait: 5.seconds).perform_later(@room)
190
  end
191
192
  # POST /:room_uid/update_settings
193
  def update_settings
194
    begin
195
      raise "Room name can't be blank" if room_params[:name].empty?
196
197
      @room = Room.find_by!(uid: params[:room_uid])
198
      # Update the rooms settings
199
      update_room_attributes("settings")
200
      # Update the rooms name if it has been changed
201
      update_room_attributes("name") if @room.name != room_params[:name]
202
      # Update the room's access code if it has changed
203
      update_room_attributes("access_code") if @room.access_code != room_params[:access_code]
204
    rescue => e
205
      logger.error "Error in updating room settings: #{e}"
206
      flash[:alert] = I18n.t("room.update_settings_error")
207
    else
208
      flash[:success] = I18n.t("room.update_settings_success")
209
    end
210
    redirect_to room_path
211
  end
212
213
  # GET /:room_uid/logout
214
  def logout
215
    logger.info "Support: #{current_user.present? ? current_user.email : 'Guest'} has left room #{@room.uid}"
216
217
    # Redirect the correct page.
218
    redirect_to @room
219
  end
220
221
  # POST /:room_uid/login
222
  def login
223
    session[:access_code] = room_params[:access_code]
224
225
    flash[:alert] = I18n.t("room.access_code_required") if session[:access_code] != @room.access_code
226
227
    redirect_to room_path(@room.uid)
228
  end
229
230
  private
231
232
  def update_room_attributes(update_type)
233
    if @room.owned_by?(current_user) && @room != current_user.main_room
234
      if update_type.eql? "name"
235
        @room.update_attributes(name: params[:room_name] || room_params[:name])
236
      elsif update_type.eql? "settings"
237
        room_settings_string = create_room_settings_string(room_params)
238
        @room.update_attributes(room_settings: room_settings_string)
239
      elsif update_type.eql? "access_code"
240
        @room.update_attributes(access_code: room_params[:access_code])
241
      end
242
    end
243
  end
244
245
  def create_room_settings_string(options)
246
    room_settings = {}
247
    room_settings["muteOnStart"] = options[:mute_on_join] == "1"
248
249
    room_settings["requireModeratorApproval"] = options[:require_moderator_approval] == "1"
250
251
    room_settings["anyoneCanStart"] = options[:anyone_can_start] == "1"
252
253
    room_settings["joinModerator"] = options[:all_join_moderator] == "1"
254
255
    room_settings.to_json
256
  end
257
258
  def room_params
259
    params.require(:room).permit(:name, :auto_join, :mute_on_join, :access_code,
260
      :require_moderator_approval, :anyone_can_start, :all_join_moderator)
261
  end
262
263
  # Find the room from the uid.
264
  def find_room
265
    @room = Room.find_by!(uid: params[:room_uid])
266
  end
267
268
  # Ensure the user is logged into the room they are accessing.
269
  def verify_room_ownership
270
    bring_to_room unless @room.owned_by?(current_user)
271
  end
272
273
  # Redirects a user to their room.
274
  def bring_to_room
275
    if current_user
276
      # Redirect authenticated users to their room.
277
      redirect_to room_path(current_user.main_room)
278
    else
279
      # Redirect unauthenticated users to root.
280
      redirect_to root_path
281
    end
282
  end
283
284
  def validate_accepted_terms
285
    redirect_to terms_path if current_user && !current_user&.accepted_terms
286
  end
287
288
  def validate_verified_email
289
    redirect_to account_activation_path(current_user) if current_user && !current_user&.activated?
290
  end
291
292
  def verify_room_owner_verified
293
    unless @room.owner.activated?
294
      flash[:alert] = t("room.unavailable")
295
296
      if current_user && [email protected]_by?(current_user)
297
        redirect_to current_user.main_room
298
      else
299
        redirect_to root_path
300
      end
301
    end
302
  end
303
304
  def verify_user_not_admin
305
    redirect_to admins_path if current_user&.has_role?(:super_admin)
306
  end
307
308
  def auth_required
309
    @settings.get_value("Room Authentication") == "true" && current_user.nil?
310
  end
311
312
  def room_limit_exceeded
313
    limit = @settings.get_value("Room Limit").to_i
314
315
    # Does not apply to admin or users that aren't signed in
316
    # 15+ option is used as unlimited
317
    return false if current_user&.has_role?(:admin) || limit == 15
318
319
    current_user.rooms.length >= limit
320
  end
321
  helper_method :room_limit_exceeded
322
323
  def join_room(opts)
324
    room_settings = JSON.parse(@room[:room_settings])
325
326
    if room_running?(@room.bbb_id) || @room.owned_by?(current_user) || room_settings["anyoneCanStart"]
327
328
      # Determine if the user needs to join as a moderator.
329
      opts[:user_is_moderator] = @room.owned_by?(current_user) || room_settings["joinModerator"]
330
331
      opts[:require_moderator_approval] = room_settings["requireModeratorApproval"]
332
333
      if current_user
334
        redirect_to join_path(@room, current_user.name, opts, current_user.uid)
335
      else
336
        join_name = params[:join_name] || params[@room.invite_path][:join_name]
337
        redirect_to join_path(@room, join_name, opts)
338
      end
339
    else
340
      search_params = params[@room.invite_path] || params
341
      @search, @order_column, @order_direction, pub_recs =
342
        public_recordings(@room.bbb_id, search_params.permit(:search, :column, :direction), true)
343
344
      @pagy, @public_recordings = pagy_array(pub_recs)
345
346
      # They need to wait until the meeting begins.
347
      render :wait
348
    end
349
  end
350
351
  # Default, unconfigured meeting options.
352
  def default_meeting_options
353
    invite_msg = I18n.t("invite_message")
354
    {
355
      user_is_moderator: false,
356
      meeting_logout_url: request.base_url + logout_room_path(@room),
357
      meeting_recorded: true,
358
      moderator_message: "#{invite_msg}\n\n#{request.base_url + room_path(@room)}",
359
      host: request.host,
360
      recording_default_visibility: @settings.get_value("Default Recording Visibility") == "public"
361
    }
362
  end
363
end
364