announcement-test/temp_file/app/controllers/admin/sites_controller.rb

366 lines
14 KiB
Ruby
Raw Normal View History

2020-02-17 13:23:26 +00:00
class Admin::SitesController < OrbitAdminController
before_filter :set_git_branch, :only=>[:check_updates, :update_orbit]
include Admin::GmailHelper
2022-10-04 05:27:32 +00:00
begin
include BundlerHelper
rescue
def bundler_with_clean_env
if block_given?
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env(&Proc.new)
else
Bundler.with_clean_env(&Proc.new)
end
end
end
end
helper_method :GeneratePermissionUrl
def get_all_databases
nginx_exe = %x[ps -o args -C nginx| grep 'daemon'| awk '{print $4}'].split("\n")[0]
if nginx_exe.nil?
render :json => {}
else
nginx_config = %x[#{nginx_exe} -V 2>&1 | grep -o '\\-\\-conf-path=\\(.*conf\\)' | cut -d '=' -f2].sub("\n",'')
include_paths = `grep include #{nginx_config}`.split("\n").map{|s| s.strip.split("#").first.match(/include\s+([^;]*)/)[1]}
include_paths = include_paths.select{|path| path.match(/(modules-enabled|mime\.types|conf\.d|sites-enabled)/).nil? }
database_info = {}
include_paths.each do |include_path|
root_paths = `grep root #{include_path}`.split("\n").map{|s| s.strip.split("#").first.match(/root\s+([^;]*)/)[1]}
root_paths = root_paths.map{|path| File.dirname(path)}
root_paths.each do |root_path|
mongoid_config = YAML.load(File.read("#{root_path}/config/mongoid.yml")) rescue nil
db = mongoid_config["development"]["sessions"]["default"]["database"] rescue nil
if db.present?
db = db.to_s
site_nginx_config = `grep -H #{root_path} #{include_path}`.split(':')[0] rescue ""
if site_nginx_config.present?
server_names = `grep server_name #{site_nginx_config}`.split("\n").map{|s| s.split('#').first.match(/server_name\s+([^;]*)/)[1].split(/\s/) rescue nil}
server_names = server_names.flatten.compact
server_names = server_names.select{|s| ip_match = s.match(/[\d\.]+/);ip_match.nil? ? true : (ip_match[0] != s)}
if server_names.count != 0
ports = `grep listen #{site_nginx_config}`.split("\n").map{|s| s.split('#').first.match(/\d+/)[0] rescue nil}.compact
if ports.include? "443"
database_info[db] = "https://#{server_names[0]}"
else
port = ports[0]
if port
database_info[db] = "http://#{server_names[0]}#{port == "80" ? '' : ":#{port}"}"
end
end
end
end
end
2020-02-17 13:23:26 +00:00
end
end
@site.update(:database_info=>database_info)
render :json => database_info
2020-02-17 13:23:26 +00:00
end
end
layout "structure"
2020-02-17 13:23:26 +00:00
def send_email
params_to_send = {'store_token' => @site.store_token}
uri = URI.parse(OrbitStore::URL)
http = Net::HTTP.new(uri.host,uri.port)
request = Net::HTTP::Get.new("/site/send_email")
request.body = params_to_send.to_query
2020-03-08 14:20:57 +00:00
http.open_timeout = 1 #set read_timeout to 1 second to avoid web die caused by no response
http.ssl_timeout = 1
begin
response = http.request(request)
rescue
response = ActionDispatch::Response.new
response.body = {'success'=>true}.to_json
end
data = JSON.parse(response.body)
%x(#{RESTART_CMD})
sleep 5
2020-02-17 13:23:26 +00:00
end
def index
@first_run = dashboard_is_first_run?
@registered = !@site.store_token.nil?
@store_permissions = check_store_permissions
if @store_permissions["error"] == "SITE_NOT_REGISTERED"
if @registered
@registered = false
@site.store_token = nil
@site.save
end
end
if @registered
network = ONetwork.new(OrbitStore::URL,"get")
response = network.request("/xhr/ticket/types",{"store_token" => @site.store_token})
data = JSON.parse(response.body) rescue {}
@types = []
locale = I18n.locale.to_s
if data["success"] == true
data["ticket_types"].each do |tt|
@types << [tt["title_translations"][locale],tt["id"]]
end
end
send_email if !@store_permissions["permission_granted"] rescue nil #Resend confirmation email if not confirmed
2020-02-17 13:23:26 +00:00
end
user_name = current_user.user_name rescue ''
network = ONetwork.new(OrbitStore::URL,"post")
response = network.request("/xhr/site/re_register_url",{"store_token" => @site.store_token, 'site_domain' => request.host_with_port,'user' => user_name})
2020-02-17 13:23:26 +00:00
@data = JSON.parse(response.body) rescue {}
end
def mail_setting
end
2020-02-17 13:23:26 +00:00
def site_info
2020-02-17 13:23:26 +00:00
@pages = Page.where(:module=>"page_content")
end
2020-02-17 13:23:26 +00:00
def responsive_setting
2020-02-17 13:23:26 +00:00
@module = ModuleApp.find_by_key("announcement")
end
2020-02-17 13:23:26 +00:00
def search_engine
end
def sitemap
end
def change_design
@site.template = params[:design_key]
@site.save
restart_server
end
def system_info
2022-10-24 08:38:47 +00:00
@disk_free = `df -h /`.rstrip()
@nginx_version = %x[/usr/sbin/nginx -v 2>&1].rstrip()
@mongo_version = (Mongoid.default_client.command(buildInfo: 1).first[:version] rescue '')
@linux_version = `lsb_release -ds`.rstrip()
if @linux_version.blank?
@linux_version = "Not Applicable"
end
if !params[:user_logs].nil?
@user_page = params[:page].to_i
@system_page = 0
@mongo_page = 0
@nginx_page = 0
elsif !params[:system_logs].nil?
@system_page = params[:page].to_i
@user_page = 0
@mongo_page = 0
@nginx_page = 0
elsif !params[:mongo_logs].nil?
@mongo_page = params[:page].to_i
@user_page = 0
@system_page = 0
@nginx_page = 0
elsif !params[:nginx_logs].nil?
@nginx_page = params[:page].to_i
@user_page = 0
@system_page = 0
@mongo_page = 0
else
@user_page = 1
@system_page = 1
@mongo_page = 1
@nginx_page = 1
end
@max_system_page = 1000
limit_num = 100
@user_actions = UserAction.all.desc(:created_at).page(@user_page).per(10) if @user_page != 0
@params = params
search_grep = params[:keywords].blank? ? nil : "|grep '#{params[:keywords]}'"
system_head = search_grep ? "-n #{@max_system_page*limit_num} #{search_grep} | head -n #{@system_page*limit_num||limit_num}" : "-n #{@system_page*limit_num}"
2022-10-04 05:27:32 +00:00
@system_logs = Kaminari.paginate_array(%x[journalctl -x --no-pager -r -o json #{system_head} | tail -#{limit_num}].encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '').split("\n").collect{|v| JSON.parse(v)}).page(1).per(limit_num) if @system_page != 0
@mongo_logs = Kaminari.paginate_array(%x[cat /var/log/mongodb/mongod.log*|grep error#{search_grep}|tac].encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '').split("\n").collect{|v| v.scan(/^((?:(?! ).)*) (.*)/)[0]}).page(@mongo_page).per(limit_num) if @mongo_page != 0
@nginx_logs = Kaminari.paginate_array(%x[cat /var/log/nginx/error.log#{search_grep}|tac].encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '').split("\n").collect{|v| v.scan(/^((?:(?!\[).)*)\[error\] (.*)/)[0]}.compact).page(@nginx_page).per(limit_num) if @nginx_page != 0
2020-02-17 13:23:26 +00:00
@mail_crons = Email.can_deliver.desc(:created_at)
@mail_cron_logs = EmailLog.desc(:created_at).page(params[:mail_log_page]).per(10)
respond_to do |format|
format.html
format.js
end
end
def delete_mail_log
if params[:ids]
EmailLog.any_in(:_id => params[:ids]).destroy
end
render :body => nil
2020-02-17 13:23:26 +00:00
end
def preference
@member_extra_db = File.read("config/member_extra_db.txt").strip rescue ""
if @member_extra_db.blank?
@member_extra_db = @site.member_extra_db
else
@site.update(:member_extra_db=>@member_extra_db)
end
@current_database = Site.collection.database.name
@database_info = @site.database_info.except(@current_database) rescue {}
2020-02-17 13:23:26 +00:00
end
def update_orbit
end
def update
@site.update_attributes(site_params)
tmp = params[:site]
if tmp[:enable_language_detection].eql?("0")
2020-02-17 13:23:26 +00:00
Site.update_all({:enable_language_detection => false})
elsif tmp[:enable_language_detection].eql?("1")
2020-07-23 08:17:22 +00:00
if @site.in_use_locales.include?(:en)
Site.update_all({:default_locale => nil})
else
Site.update_all({:enable_language_detection => false})
end
2020-02-17 13:23:26 +00:00
end
if !@site.in_use_locales.include? I18n.locale
2020-02-17 13:23:26 +00:00
I18n.locale = @site.in_use_locales.first
redirect_to admin_site_preference_path(@site)
2020-02-17 13:23:26 +00:00
else
begin
redirect_to :back
rescue
redirect_to admin_site_preference_path(@site)
end
2020-02-17 13:23:26 +00:00
end
Thread.new do
sleep 1
%x(#{RESTART_CMD})
end
2020-02-17 13:23:26 +00:00
end
def update_manager
@store_permissions = check_store_permissions
end
def get_update_history
2020-02-20 08:18:43 +00:00
update_log = %x{git log --pretty=format:"%H','%ad','%s" --date=short}.split("\n")
emergency_log = %x{git reflog --pretty=format:"%H','%ad','%s" --date=short}.split("\n")
@update_log = update_log.collect do |v|
if v.include? 'complete_update_'
tmp = emergency_log.select{|v1| v1.exclude?('complete_update_') && v1.include?(v.split(/complete_update_/)[-1])}[0] rescue []
[v,tmp]
else
v
end
end.flatten.map{|log| log.gsub("'","").split(",")}.to_json
2020-02-17 13:23:26 +00:00
render :json => @update_log
end
def check_updates
%x(git fetch origin)
@new_updates = %x(git log #{@branch}..origin/#{@branch} --pretty=format:"%ad','%s" --date=short).split("\n").map{|log| log.gsub("'","").split(",")}.to_json
render :json => @new_updates
end
2020-02-20 05:14:26 +00:00
def git_reset(commit,type)
mul = Multithread.where(key: 'update_manager').first
mul = Multithread.create(key: 'update_manager') if mul.nil?
mul.update_attributes(status: 'waiting')
Thread.new do
ubuntu_version = %x[lsb_release -a | grep Release].scan(/\d.*\d/)[0]
git = 'git'
if Float(ubuntu_version) <= 14.04 && Float(%x[git --version].scan(/\d.\d/)[0]) < 1.9
if %x[uname -m].scan('64').count !=0
cmd0 = system("wget https://ruling.digital/uploads/asset/git_1.9.1-1_amd64.deb && dpkg -x git_1.9.1-1_amd64.deb ./git_1.9.1")
else
cmd0 = system("wget https://ruling.digital/uploads/asset/git_1.9.1-1_i386.deb && dpkg -x git_1.9.1-1_i386.deb ./git_1.9.1")
end
git = 'git_1.9.1/usr/bin/git'
end
2020-03-16 08:25:50 +00:00
git_add_except_public = Dir['*'].select{|v| v!= 'public' && v!= 'log' && v != 'dump' && v != 'tmp'}.collect do |v|
"#{git} add -f --all --ignore-errors '#{v}'"
end.join(' ; ')
git_add_custom = (Dir['*'].select{|v| v !="config.ru" && v !='app' && v != 'lib' && v != 'config' && v != 'public' && v!= 'log' && v != 'dump' && v != 'tmp'} + ['app/templates','config/mongoid.yml','config/extra_lang.txt']).collect do |v|
"#{git} add -f --all --ignore-errors '#{v}'"
end.join(' ; ')
git_restore = "#{git} checkout -- `git ls-tree HEAD --name-only|sed 's/.ruby-version//g'|xargs`"
2020-02-20 05:14:26 +00:00
time_now = Time.now.strftime('%Y_%m_%d_%H_%M')
2020-02-26 08:11:03 +00:00
if %x[#{git} config user.name].empty?
%x[#{git} config --global user.name "rulingcom"]
end
2020-02-26 08:11:03 +00:00
if %x[#{git} config user.email].empty?
%x[#{git} config --global user.email "orbit@rulingcom.com"]
end
site = Site.first
bundler_with_clean_env{system("#{git_add_except_public} ; #{git} commit -m auto_backup_before_#{type}_#{time_now} --allow-empty && #{git} reset #{commit} --mixed ; #{git_add_custom} ; #{git_restore} ; #{git_add_except_public} ; #{git} clean -f -- app/models ; #{git} commit -m complete_#{type}_#{time_now} --allow-empty")}
site.update_attributes(update_flag: true) rescue nil
2020-02-20 05:14:26 +00:00
mul.update_attributes(status: 'finish')
end
end
2020-02-17 13:23:26 +00:00
def update_orbit
store_permissions = check_store_permissions
2020-02-20 05:14:26 +00:00
if params['type'] == 'update'
if store_permissions["permission_granted"]
git_reset('origin','update')
render :plain => 'waiting'
2020-02-17 13:23:26 +00:00
else
2020-02-20 05:14:26 +00:00
render :json => store_permissions.to_json
2020-02-17 13:23:26 +00:00
end
2020-02-20 05:14:26 +00:00
elsif params['type'] == 'restore'
git_reset(params['id'],'restore')
render :plain => 'waiting'
2020-02-20 05:14:26 +00:00
elsif params['type'] == 'get_result'
render :plain => Multithread.where(key: 'update_manager').first.status rescue 'running'
2020-02-17 13:23:26 +00:00
end
end
def bundle_install
bundler_with_clean_env{system("cd #{Rails.root} && bundle update") }
%x(#{RESTART_CMD})
2020-02-20 05:14:26 +00:00
sleep 2
render :body => nil
2020-02-17 13:23:26 +00:00
end
def restart_server
2020-02-20 05:14:26 +00:00
mode = Rails.env
unicorn_rails = %x[which unicorn_rails].sub("\n",'')
render :body => nil
bundler_with_clean_env{system("UNICORN_PID=\"`fuser tmp/pids/unicorn.sock tmp/sockets/unicorn.sock tmp/unicorn.sock` `cat tmp/pids/unicorn.pid `\" && kill -s TERM $UNICORN_PID ; while (kill -0 $UNICORN_PID > /dev/null 2>&1) ; do printf '.' && sleep 1 ; done ; unset UNICORN_FD; bundle exec unicorn_rails -c config/unicorn.rb -D -E #{mode}")}
2020-02-17 13:23:26 +00:00
end
private
2020-02-17 13:23:26 +00:00
def dashboard_is_first_run?
!current_user.is_tour_completed?("tickets")
end
def site_params
tmp = params[:site]
if tmp[:default_bar_color].present?
tmp[:mobile_bar_color] = []
2020-02-17 13:23:26 +00:00
end
# if tmp[:enable_language_detection]
2020-02-17 13:23:26 +00:00
# Site.update_all({:default_locale => nil})
# end
unless tmp[:in_use_locales].nil?
in_user_locales = []
I18n.available_locales.each do |locale|
in_user_locales << locale if tmp[:in_use_locales][locale].eql?("1")
end
tmp[:in_use_locales] = in_user_locales
2020-02-17 13:23:26 +00:00
end
if tmp[:phone_number].nil?
tmp[:phone_number] = []
# else
# tmp[:phone_number] = tmp[:phone_number]
end
tmp[:sign_up_roles] = [] if !tmp[:sign_up_roles].present?
if tmp[:privileged_ip].present?
tmp[:privileged_ip] = tmp[:privileged_ip].values rescue []
end
params.require(:site).permit!
2020-02-17 13:23:26 +00:00
end
def set_git_branch
@branch = %x(git rev-parse --abbrev-ref HEAD).gsub("\n","")
end
2020-02-17 13:23:26 +00:00
end