require 'active_record' require 'rubypitaya/core/handler_base' module RubyPitaya class HandlerRouter INVALID_ACTION_NAMES = ['initialize', 'set_attributes'] def initialize(is_cheats_enabled) @is_cheats_enabled = is_cheats_enabled routes_path = Path::ROUTES_FILE_PATH handler_folder_paths = Path::Plugins::HANDLERS_FOLDER_PATHS + [Path::HANDLERS_FOLDER_PATH] import_routes_file(routes_path) handler_folder_paths.each do |handler_folder_path| import_handler_files(handler_folder_path) end import_routes_class import_handler_classes end def import_routes_file(routes_path) require routes_path end def import_routes_class routes_classes = ObjectSpace.each_object(RoutesBase.singleton_class).select do |klass| klass != RoutesBase end @routes = routes_classes.first.new end def import_handler_files(handler_folder_path) handler_files = Gem.find_files("#{handler_folder_path}/*.rb") handler_files = handler_files.select { |a| !a[/.+_cheats.rb/] && !a[/.+_cheat.rb/] } unless @is_cheats_enabled handler_files.each { |path| require path } end def import_handler_classes handler_classes = ObjectSpace.each_object(HandlerBase.singleton_class).select do |klass| class_name = klass.to_s.downcase is_cheat_class = class_name.end_with?('cheat') || class_name.end_with?('cheats') klass != HandlerBase && (@is_cheats_enabled || !is_cheat_class) end @handlers = handler_classes.map { |handler_class| handler_class.new } @handler_name_map = @handlers.map do |handler| handler_name = handler.class.to_s handler_name = @routes.get_new_handler_name(handler_name) handler_name = handler_name.split('::').last handler_name = handler_name[0].downcase + handler_name[1..-1] [handler_name, handler] end @handler_name_map = @handler_name_map.to_h end def call(handler_name, action_name, session, postman, services, setup, config, log, params) unless @handler_name_map.include?(handler_name) return { code: StatusCodes::CODE_HANDLER_NOT_FOUND, message: "Handler #{handler_name} not found" } end if INVALID_ACTION_NAMES.include?(action_name) || !@handler_name_map[handler_name].public_methods(false).include?(action_name.to_sym) return { code: StatusCodes::CODE_ACTION_NOT_FOUND, message: "Handler #{handler_name} action #{action_name} not found" } end handler = @handler_name_map[handler_name] if !handler.class.authenticated_action_name?(action_name) handler.set_attributes(log, services, setup, config, params, session, postman) handler.send(action_name) else if session.authenticated? handler.set_attributes(log, services, setup, config, params, session, postman) handler.send(action_name) else return { code: StatusCodes::CODE_NOT_AUTHENTICATED, message: 'Not authenticated', } end end end end end