Fix feed bug.

This commit is contained in:
BoHung Chiu 2020-07-31 14:52:33 +08:00
parent eda547fcb3
commit d97ea7e255
16 changed files with 44 additions and 1822 deletions

View File

@ -171,9 +171,9 @@ class EventNewsController < ApplicationController
else
feeds_event_news = get_feed_event_news("widget")
top_event_news = top_event_news + feeds_event_news.select{|v| v['is_top']}
top_event_news = top_event_news.sort{|v1,v2| v2["event_date"]<=>v1["event_date"]}
top_event_news = top_event_news.sort{|v1,v2| date_transform(v2["event_date"]) <=> date_transform(v1["event_date"])}
rest_all_event_news = feeds_event_news.select{|v| v['is_top'] != true} + not_top_event_news.take(rest_count)
rest_event_news = rest_all_event_news.sort{|v1,v2| v2["event_date"]<=>v1["event_date"]}.take(rest_count)
rest_event_news = rest_all_event_news.sort{|v1,v2| date_transform(v2["event_date"]) <=> date_transform(v1["event_date"])}.take(rest_count)
event_news = (top_event_news + rest_event_news).take(widget_data_count)
end
end
@ -267,7 +267,7 @@ class EventNewsController < ApplicationController
"title" => event_news.title,
"subtitle_ann" => subtitle_ann,
"update_user" => update_user,
"updated_at" => event_news.event_date.strftime('%Y-%m-%d %H:%M'),
"updated_at" => (event_news.event_date.strftime('%Y-%m-%d %H:%M') rescue ""),
"body" =>event_news.text,
"image" => event_news.image.url,
"img_src" => img_src,
@ -321,19 +321,23 @@ class EventNewsController < ApplicationController
OrbitHelper.render_meta_tags([{"property" => "og:title", "content" => event_news["title_translations"][locale]},{"property" => "og:site_name", "content" => Site.first.title},{"property" => "og:url", "content" => request.original_url.split("?").first},{"property" => "og:description", "content" => meta_desc},{"property" => "og:image", "content" => event_news["image"]["original"]},{"property" => "og:type", "content" => "Article"}])
datetime = DateTime.parse(event_news["event_date"])
datetime = DateTime.parse(event_news["event_date"].to_s) rescue ""
{
"tags" => tags,
"event_news_files" => files,
"event_news_links" => links,
"data" => {
"speaker" => event_news["speaker"],
"host" => event_news["host"],
"notes" => event_news["notes"],
"speaker-head" => t('event_news.speaker'),
"host-head" => t('event_news.host'),
"notes-head" => t('event_news.notes'),
"event_date-head" => t('date_'),
"speaker" => (event_news["speaker_translations"][locale].to_s rescue ""),
"host" => (event_news["host_translations"][locale].to_s rescue ""),
"notes" => (event_news["notes_translations"][locale].to_s rescue ""),
"title" => event_news["title_translations"][locale],
"update_user" => update_user,
"updated_at" => datetime.strftime('%Y-%m-%d %H:%M'),
"updated_at" => (datetime.strftime('%Y-%m-%d %H:%M') rescue ""),
"body" => event_news["text_translations"][locale],
"image" => event_news["image"]["original"],
"alt_title" => desc

View File

@ -114,12 +114,13 @@ class EventNewsFeedsController < ApplicationController
a["text_translations"]["en"] = smart_convertor(anns.text_translations["en"]) if !anns.text_translations["en"].blank?
a["text_translations"]["zh_tw"] = smart_convertor(anns.text_translations["zh_tw"]) if !anns.text_translations["zh_tw"].blank?
a["event_date"] = anns.event_date
a["postdate"] = anns.postdate
a["postdate"] = anns.event_date#anns.postdate
a["image_description_translations"] = anns.image_description_translations
a["image"] = {}
a["image"]["original"] = ("#{request.base_url}" + anns.image.url rescue "")
a["image"]["thumb"] = ("#{request.base_url}" + anns.image.thumb.url rescue "")
a["image"]["mobile"] = ("#{request.base_url}" + anns.image.mobile.url rescue "")
a["img_src"] = a["image"]["thumb"] || "/assets/announcement-default.jpg"
a["tags"] = []
a["author"] = author
a["params"] = anns.to_param
@ -136,6 +137,8 @@ class EventNewsFeedsController < ApplicationController
b = {}
b["url"] = bl.url
b["title_translations"] = bl.title_translations
b["link_url"] = b["url"]
b["link_title_translations"] = bl.title_translations.map{|k,v| [k,(v.blank? ? File.basename(b["url"]) : v rescue '')]}.to_h
a["event_news_links"] << b
end
anns.event_news_files.each do |bf|
@ -143,6 +146,8 @@ class EventNewsFeedsController < ApplicationController
b["description_translations"] = bf.description_translations
b["title_translations"] = bf.title_translations
b["url"] = ("#{request.base_url}" + bf.file.url rescue "")
b["file_url"] = b["url"]
b["file_title_translations"] = bf.title_translations.map{|k,v| [k,(v.blank? ? File.basename(b["url"]) : v rescue '')]}.to_h
a["event_news_files"] << b
end
all_anns << a

View File

@ -23,6 +23,13 @@ module EventNewsHelper
end
end
end
def date_transform(variable)
if variable.class != DateTime
return (DateTime.parse(variable) rescue DateTime.new)
else
return variable
end
end
def data_to_human_type(a)
statuses = a.statuses_with_classname.collect do |status|
{
@ -57,12 +64,13 @@ module EventNewsHelper
"source-site-link" => "",
"subtitle" => a.subtitle,
"statuses" => statuses,
"category" => a.category.title,
"category" => (a.category.title rescue ""),
"postdate" => a.event_date,
"event_date" => a.event_date,
"author" => author,
"link_to_show" => link_to_show,
"target" => target,
"img_src" => image_url || "/assets/event_news-default.jpg",
"img_src" => image_url || "/assets/announcement-default.jpg",
"img_description" => desc
}
end
@ -111,10 +119,14 @@ module EventNewsHelper
"event_news_links" => links,
"event_news_files" => files,
"title" => fa["title_translations"][locale],
"speaker" => (fa["speaker_translations"][locale].to_s rescue ""),
"host" => (fa["host_translations"][locale].to_s rescue ""),
"notes" => (fa["notes_translations"][locale].to_s rescue ""),
"subtitle" => fa["subtitle_translations"][locale],
"statuses" => [status],
"category" => fa["category"],
"postdate" => fa["postdate"],
"postdate" => (DateTime.parse(fa["event_date"]) rescue DateTime.now),
"event_date" => (DateTime.parse(fa["event_date"]) rescue DateTime.now),
"author" => fa["author"],
"source-site" => "<a href='#{fa["source-site"]}' target='_blank' class='feed-source'>#{fa["source-site-title"]}</a>",
"source-site-title" => fa["source-site-title"],
@ -218,10 +230,10 @@ module EventNewsHelper
if event_news.count != 0
top_anns = event_news.select{|v| v.is_top} + feeds_anns.select{|v| v['is_top']}
rest_all_anns = feeds_anns.select{|v| v['is_top'] != true} + event_news.select{|v| !v.is_top}
rest_anns = rest_all_anns.sort{|v1,v2| v2["event_date"]<=>v1["event_date"]}
all_sorted = top_anns.sort{|v1,v2| v2["event_date"]<=>v1["event_date"]} + rest_anns
rest_anns = rest_all_anns.sort{|v1,v2| date_transform(v2["event_date"]) <=> date_transform(v1["event_date"])}
all_sorted = top_anns.sort{|v1,v2| date_transform(v2["event_date"]) <=> date_transform(v1["event_date"])} + rest_anns
else
all_sorted = feeds_anns.select{|v| v['is_top']}.sort{|v1,v2| v2["event_date"]<=>v1["event_date"]} + feeds_anns.select{|v| v['is_top'] != true}.sort{|v1,v2| v2["event_date"]<=>v1["event_date"]}
all_sorted = feeds_anns.select{|v| v['is_top']}.sort{|v1,v2| date_transform(v2["event_date"]) <=> date_transform(v1["event_date"])} + feeds_anns.select{|v| v['is_top'] != true}.sort{|v1,v2| (DateTime.parse(v2["event_date"].to_s) rescue DateTime.new)<=>(DateTime.parse(v1["event_date"].to_s) rescue DateTime.new)}
end
all_filter = filter_by_keywords(all_sorted,params[:keywords],params[:stime],params[:etime])
else

View File

@ -1,8 +0,0 @@
desc 'Remove duplicated bulletins (announcements) created by preview'
namespace :bulletin do
task :remove_preview_bulletins => [:environment] do
bulletins = Bulletin.where(is_preview: true)
bulletins.destroy_all
end
end

View File

@ -0,0 +1,8 @@
desc 'Remove duplicated EventNews created by preview'
namespace :event_news do
task :remove_preview_event_news => [:environment] do
event_news = EventNews.where(is_preview: true)
event_news.destroy_all
end
end

View File

@ -1,105 +0,0 @@
source 'https://rubygems.org'
#update all site!!!!!!!!
#social gems
gem "omniauth-google-oauth2"
#rails gem
gem 'rake','~> 12.3.3'
gem 'sassc-rails', '~>1.3.0'
gem 'rails', '~> 4.1.16'
gem 'sanitize', '~> 4.6.6'
gem 'faraday', '~>0.15.4'
#assets and templates
#gem 'sass-rails', '~> 4.0.2'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'jquery-ui-rails', "5.0.0"
gem 'turbolinks'
gem 'normalize-rails', '~> 3.0.1'
#password
gem 'bcrypt-ruby', '~> 3.1.5'
#json
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'spring', '~> 1.7.2', group: :development
gem 'active_model_serializers'
#parser
gem 'nokogiri', '~> 1.7.0.1'
#store api
gem 'httparty'
#database
# gem 'mongoid', github: "mongoid/mongoid"
gem 'mongoid', '~> 4.0.2'
# sockets
# gem "websocket-rails"
#file uploading and carrierwave
gem "mini_magick", "3.5.0"
gem 'carrierwave'
gem 'carrierwave-mongoid','~> 0.10.0', :require => 'carrierwave/mongoid'
gem 'zip-zip'
gem 'kaminari', '~> 1.0.1'
gem 'kaminari-mongoid', '~> 0.1.0'
gem 'impressionist', '~> 1.5.2'
gem 'chartkick', '~> 2.3.5'
gem 'usagewatch_ext'
gem 'ckeditor', '~> 4.2.4'
gem 'unicorn', '~> 5.4.0'
gem 'zhconv'
gem 'time_difference'
gem 'execjs'
gem 'therubyracer'
#excel
gem 'axlsx_rails'
gem 'spreadsheet'
gem 'rubyXL'
#form helpers
gem 'dynamic_form'
#built in modules
eval(File.read(File.dirname(__FILE__) + '/built_in_extensions.rb'))
#modules installed from the store
eval(File.read(File.dirname(__FILE__) + '/downloaded_extensions.rb'))
if File.exists?(File.dirname(__FILE__) + '/extra_gems.rb')
eval(File.read(File.dirname(__FILE__) + '/extra_gems.rb'))
end
#development related gems
group :development do
gem 'better_errors'
# gem 'guard-bundler'
# gem 'guard-rails'
gem 'rails_layout'
gem 'rb-fchange', :require=>false
gem 'rb-fsevent', :require=>false
gem 'rb-inotify', '~> 0.9.10', :require=>false
gem 'byebug', '~> 9.0.6'
gem "binding_of_caller"
end
#testing gems
group :test do
gem "minitest", '~>5.11.3'
gem 'minitest-spec-rails'
end
#ask
gem 'rucaptcha',git: 'http://gitlab.tp.rulingcom.com/chiu/rucaptcha.git'
gem 'repost',git: 'http://gitlab.tp.rulingcom.com/chiu/repost-master.git'
gem 'payment_settup',git: 'http://gitlab.tp.rulingcom.com/chiu/payment_settup.git'
#caching observers
# gem 'mongoid-observers'
#desktop
# gem 'angularjs-rails', '~> 1.2.20'
# gem 'angular-ui-bootstrap-rails', '~> 0.11.0'
# gem 'jquery_mousewheel_rails', '~> 3.1.11.3'

View File

@ -1,184 +0,0 @@
require "open3"
class Admin::PlaygroundController < OrbitAdminController
before_filter :check_for_testers, :only => "index"
layout "structure"
include Admin::PlaygroundHelper
before_action :clean_multithread_model, :only => :command
def index
modules = ["announcement", "faq", "ad_banner", "archive", "gallery", "web_resource"]
@default_modules = modules.collect do |mod|
ma = ModuleApp.where(:key => mod).first
[ma.title,mod]
end
end
def clean_multithread_model
mul = Multithread.where(key: 'playground').first
mul.destroy if !mul.nil?
end
def generatefakedata
ma = ModuleApp.where(:key => params[:module]).first rescue nil
if !ma.nil?
case ma.key
when "announcement"
make_announcement_fake_data(ma, params[:number].to_i)
when "faq"
make_faq_fake_data(ma, params[:number].to_i)
when "ad_banner"
make_ad_banner_fake_data(ma, params[:number].to_i)
when "archive"
make_archive_fake_data(ma, params[:number].to_i)
when "gallery"
make_gallery_fake_data(ma, params[:number].to_i)
when "web_resource"
make_web_resource_fake_data(ma, params[:number].to_i)
end
end
render :json => {"success" => true}.to_json
end
def deletefakedata
ma = params[:module]
fd = FakeData.where(:module => ma).first rescue nil
if !fd.nil?
case ma
when "announcement"
delete_announcement_fake_data(ma)
when "faq"
delete_faq_fake_data(ma)
when "ad_banner"
delete_ad_banner_fake_data(ma)
when "archive"
delete_archive_fake_data(ma)
when "gallery"
delete_gallery_fake_data(ma)
when "web_resource"
delete_web_resource_fake_data(ma)
end
else
render :json => {"success" => false}.to_json and return
end
render :json => {"success" => true}.to_json
end
def command
response = {}
Multithread.create(key: 'playground',status: {output: [],error: false,alive:true})
case params[:command]
when "clean"
clean_assets
response["success"] = true
when "precompile"
precompile
response["success"] = true
when "bundle"
bundle_update
response["success"] = true
when "restart_server"
restart_server
response["success"] = true
when "restart_unicorn"
restart_unicorn(Rails.env)
response["success"] = true
when "switch_to_production"
restart_unicorn("production")
response["success"] = true
when "switch_to_development"
restart_unicorn("development")
response["success"] = true
else
exec_other_command(params[:command])
response["success"] = true
end
render :json => response.to_json
end
def console_output
if params[:type] == "restart"
render :json => {"success" => true}.to_json
file = File.join(Rails.root,"tmp","restart_unicorn.sh")
File.delete(file) if File.exists?(file)
else
mul = Multithread.where(key: 'playground').first
if !mul.nil?
render :json => {"alive" => mul.status['alive'], "response" => mul.status['output'][params[:count].to_i..-1], "error" => mul.status['error']}.to_json
if !mul.status['alive']
mul.status['output'] = []
mul.status['error'] = false
mul.save
end
else
render :json => {"alive" => true, "response" => "finish", "error" => false}.to_json
end
end
end
private
def precompile
cmd = "RAILS_ENV=production bundle exec rake assets:precompile"
exec_other_command(cmd)
end
def exec_other_command(command)
mul = Multithread.where(key: 'playground').first
Thread.new do
begin
Bundler.with_clean_env do
IO.popen(command,:err=>[:child, :out]) do |stdout|
stdout.each do |line|
l = line.chomp
mul.status['output'] << l
if l == "rake aborted!"
mul.status['error'] = true
end
mul.save
end
end
mul.status['alive'] = false
mul.save
if command == 'bundle update'
system('sleep 2')
Bundler.with_clean_env{system("kill -s USR2 `cat tmp/pids/unicorn.pid`")}
end
end
rescue => e
mul.status['alive'] = false
mul.status['output'] << e.inspect
mul.status['error'] = true
mul.save
end
end
end
def bundle_update
cmd = "bundle update"
exec_other_command(cmd)
end
def restart_server
cmd ="kill -s USR2 `cat tmp/pids/unicorn.pid`"
exec_other_command(cmd)
end
def clean_assets
cmd = "rm -r public/assets"
exec_other_command(cmd)
end
def restart_unicorn(mode)
mode = Rails.env if mode.nil?
unicorn_rails = %x[which unicorn_rails].sub("\n",'')
content = "kill -s TERM `cat tmp/pids/unicorn.pid` && unset UNICORN_FD && sleep 1 && bundle exec #{unicorn_rails} -c config/unicorn.rb -D -E #{mode} | at now"
Thread.new do
Bundler.with_clean_env{system(content)}
end
end
def check_for_testers
render_401 if !current_user.beta_tester && current_user.user_name != "rulingcom"
end
end

View File

@ -1,265 +0,0 @@
class Admin::SitesController < OrbitAdminController
before_filter :get_site
before_filter :set_git_branch, :only=>[:check_updates, :update_orbit]
before_action :create_page_set
def create_page_set
@site = @current_site.nil? ? Site.first : @current_site
if( @site.page_sets.count==0 rescue false)
@site.page_sets.create()
elsif @site.page_sets.count>1
@site.page_sets.each_with_index do |i,v|
if i!=0
v.delete
end
end
end
end
layout "structure"
def send_email
params_to_send = {'store_token' => current_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
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(kill -s USR2 `cat tmp/pids/unicorn.pid`)
sleep 5
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
end
user_name = current_user.user_name rescue ''
network = ONetwork.new(OrbitStore::URL,"post")
response = network.request("/xhr/site/re_register_url",{"store_token" => current_site.store_token, 'site_domain' => request.host_with_port,'user' => user_name})
@data = JSON.parse(response.body) rescue {}
end
def mail_setting
end
def site_info
@pages = Page.where(:module=>"page_content")
end
def responsive_setting
@module = ModuleApp.find_by_key("announcement")
end
def search_engine
end
def sitemap
end
def change_design
@site.template = params[:design_key]
@site.save
restart_server
end
def system_info
@disk_free = `df -h /`.gsub("\n","<br/>").html_safe
@nginx_version = %x[/usr/sbin/nginx -v 2>&1].gsub("\n","<br/>").html_safe
@mongo_version = `mongod --version`.split("\n")[0].html_safe
@linux_version = `lsb_release -d`.split(":")[1].html_safe rescue "Not Applicable"
@user_actions = UserAction.all.desc(:created_at).page(params[:page]).per(10)
@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 :nothing => true
end
def preference
end
def update_orbit
end
def update
@site.update_attributes(site_params)
if params[:site][:enable_language_detection].eql?("0")
Site.update_all({:enable_language_detection => false})
elsif params[:site][:enable_language_detection].eql?("1")
Site.update_all({:default_locale => nil})
end
if !@site.in_use_locales.include?I18n.locale
I18n.locale = @site.in_use_locales.first
redirect_to admin_site_preference_path(current_site)
else
redirect_to :back
end
%x(kill -s USR2 `cat tmp/pids/unicorn.pid`)
sleep 5
end
def update_manager
@store_permissions = check_store_permissions
end
def get_update_history
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
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
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
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 !='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 ."
time_now = Time.now.strftime('%Y_%m_%d_%H_%M')
if %x[#{git} config user.name].empty?
%x[#{git} config --global user.name "rulingcom"]
end
if %x[#{git} config user.email].empty?
%x[#{git} config --global user.email "orbit@rulingcom.com"]
end
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} commit -m complete_#{type}_#{time_now} --allow-empty")}
mul.update_attributes(status: 'finish')
end
end
def update_orbit
store_permissions = check_store_permissions
if params['type'] == 'update'
if store_permissions["permission_granted"]
git_reset('origin','update')
render :text => 'waiting'
else
render :json => store_permissions.to_json
end
elsif params['type'] == 'restore'
git_reset(params['id'],'restore')
render :text => 'waiting'
elsif params['type'] == 'get_result'
render :text => Multithread.where(key: 'update_manager').first.status rescue 'running'
end
end
def bundle_install
Bundler.with_clean_env { system("cd #{Rails.root} && bundle update") }
%x(kill -s USR2 `cat tmp/pids/unicorn.pid`)
sleep 2
render :nothing => true
end
def restart_server
mode = Rails.env
unicorn_rails = %x[which unicorn_rails].sub("\n",'')
render :nothing => true
Bundler.with_clean_env{system("kill -s TERM `cat tmp/pids/unicorn.pid` && unset UNICORN_FD && sleep 1 && bundle exec #{unicorn_rails} -c config/unicorn.rb -D -E #{mode}")}
end
private
def get_site
@site = @current_site.nil? ? Site.first : @current_site
end
def dashboard_is_first_run?
!current_user.is_tour_completed?("tickets")
end
def site_params
if params[:site][:default_bar_color]
params[:site][:mobile_bar_color] = []
end
# if params[:site][:enable_language_detection]
# Site.update_all({:default_locale => nil})
# end
unless params[:site][:in_use_locales].nil?
in_user_locales = []
I18n.available_locales.each do |locale|
in_user_locales << locale if params[:site][:in_use_locales][locale].eql?("1")
end
params[:site][:in_use_locales] = in_user_locales
end
if params[:site][:phone_number].nil?
params[:site][:phone_number] = []
# else
# params[:site][:phone_number] = params[:site][:phone_number]
end
params[:site][:sign_up_roles] = [] if !params[:site][:sign_up_roles].present?
params.require(:site).permit!
end
def set_git_branch
@branch = %x(git rev-parse --abbrev-ref HEAD).gsub("\n","")
end
end

View File

@ -1,366 +0,0 @@
module Admin::PlaygroundHelper
def make_announcement_fake_data(ma, total_count=5)
page = Page.Where(:module => ma.key).first rescue nil
if page.nil?
page = Page.new(:module => ma.key, :page_id => "announcements", :layout => "annc_index1", :name_translations => {"en" => "Announcement", "zh_tw" => "公告"}, :url => "/announcements", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
page.save
end
if ma.categories.empty?
cat = Category.new
cat.title_translations = {"en" => "Announcement", "zh_tw" => "公告"}
cat.module_app = ma
cat.save
else
cat = ma.categories.first
end
if ma.tags.empty?
tag = Tag.new
tag.name_translations = {"en" => "Announcement", "zh_tw" => "公告"}
tag.module_app_ids << ma.id
tag.save
else
tag = ma.tags.first
end
fake_ids = []
(1..total_count).each do |i|
bulletin = Bulletin.new(:title_translations => get_random_title, :subtitle_translations => get_random_subtitle, :text_translations => get_random_content, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :deadline => get_fake_date, :approved => true, :image_description_translations => get_random_title)
bulletin.category = cat
bulletin.tags=tag
bulletin.is_top = get_random_status
bulletin.is_hot = get_random_status
bulletin.remote_image_url = get_fake_image_url(ma.key)
bulletin.save
fake_ids << bulletin.id
(1..rand(1..5)).each do |x|
bf = BulletinFile.new(:title_translations => get_random_title, :description_translations => get_random_title)
bf.remote_file_url = get_fake_file_url(ma.key)
bf.bulletin = bulletin
bf.save
end
(1..rand(1..5)).each do |x|
bl = BulletinLink.new(:title_translations => get_random_title, :url => get_fake_link)
bl.bulletin = bulletin
bl.save
end
end
commit_fake_data(ma, fake_ids)
end
def delete_announcement_fake_data(ma)
fd = FakeData.where(:module => ma).first rescue nil
bulletins = Bulletin.where(:id.in => fd.ids)
bulletins.destroy_all
fd.destroy
end
def make_ad_banner_fake_data(ma, total_count=5)
if ma.categories.empty?
cat = Category.new
cat.title_translations = {"en" => "Home Banners", "zh_tw" => "家庭橫幅"}
cat.module_app = ma
cat.save
else
cat = ma.categories.first
end
fake_ids = []
fds = FakeData.where(:module => "ad_banner").first.ids.count rescue 0
(1..total_count).each do |i|
banner = Banner.new(:title => "Home banner #{i + fds}", :ad_fx => "fade", :height => 300, :width => 800, :timeout => 5, :base_image => 1, :speed => 200)
banner.category = cat
banner.save
fake_ids << banner.id
(1..rand(2..4)).each do |x|
image = AdImage.new(:title_translations => get_random_title, :context_translations => get_random_title, :out_link => get_fake_link, :deadline => get_fake_date, :sort_number => x, :link_open => AdImage::LINK_OPEN_TYPES.sample)
image.remote_file_url = get_fake_image_url(ma.key)
image.banner = banner
image.save
end
end
commit_fake_data(ma, fake_ids)
end
def delete_ad_banner_fake_data(ma)
fd = FakeData.where(:module => ma).first rescue nil
banners = Banner.where(:id.in => fd.ids)
banners.destroy_all
fd.destroy
end
def make_faq_fake_data(ma, total_count=5)
page = Page.Where(:module => ma.key).first rescue nil
if page.nil?
page = Page.new(:module => ma.key, :page_id => "faqs", :layout => "faq_index1", :name_translations => {"en" => "FAQs", "zh_tw" => "FAQs"}, :url => "/faqs", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
page.save
end
if ma.categories.empty?
cat = Category.new
cat.title_translations = {"en" => "FAQ", "zh_tw" => "FAQ"}
cat.module_app = ma
cat.save
else
cat = ma.categories.first
end
if ma.tags.empty?
tag = Tag.new
tag.name_translations = {"en" => "FAQ", "zh_tw" => "FAQ"}
tag.module_app_ids << ma.id
tag.save
else
tag = ma.tags.first
end
fake_ids = []
(1..total_count).each do |i|
qa = Qa.new(:title_translations => get_random_title, :answer_translations => get_random_subtitle, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :is_hot => get_random_status, :is_top => get_random_status)
qa.category = cat
qa.tags=tag
qa.save
fake_ids << qa.id
(1..rand(1..5)).each do |x|
qf = QaFile.new(:title_translations => get_random_title, :description_translations => get_random_title)
qf.remote_file_url = get_fake_file_url(ma.key)
qf.qa = qa
qf.save
end
(1..rand(1..5)).each do |x|
ql = QaLink.new(:title_translations => get_random_title, :url => get_fake_link)
ql.qa = qa
ql.save
end
end
commit_fake_data(ma, fake_ids)
end
def delete_faq_fake_data(ma)
fd = FakeData.where(:module => ma).first rescue nil
faqs = Qa.where(:id.in => fd.ids)
faqs.destroy_all
fd.destroy
end
def make_archive_fake_data(ma, total_count=5)
page = Page.Where(:module => ma.key).first rescue nil
if page.nil?
page = Page.new(:module => ma.key, :page_id => "archive", :layout => "archive_index1", :name_translations => {"en" => "Archive", "zh_tw" => "檔案"}, :url => "/archive", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
page.save
end
if ma.categories.empty?
cat = Category.new
cat.title_translations = {"en" => "Archive", "zh_tw" => "檔案"}
cat.module_app = ma
cat.save
else
cat = ma.categories.first
end
if ma.tags.empty?
tag = Tag.new
tag.name_translations = {"en" => "Archive", "zh_tw" => "檔案"}
tag.module_app_ids << ma.id
tag.save
else
tag = ma.tags.first
end
fake_ids = []
(1..total_count).each do |i|
archive = ArchiveFile.new(:title_translations => get_random_title, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :deadline => get_fake_date, :is_top => get_random_status, :is_hot => get_random_status)
archive.category = cat
archive.tags=tag
archive.save
fake_ids << archive.id
(1..rand(1..5)).each do |x|
afm = ArchiveFileMultiple.new(:file_title_translations => get_random_title, :sort_number => x)
afm.remote_file_url = get_fake_file_url(ma.key)
afm.archive_file = archive
afm.save
end
end
commit_fake_data(ma, fake_ids)
end
def delete_archive_fake_data(ma)
fd = FakeData.where(:module => ma).first rescue nil
archives = ArchiveFile.where(:id.in => fd.ids)
archives.destroy_all
fd.destroy
end
def make_gallery_fake_data(ma, total_count=5)
page = Page.Where(:module => ma.key).first rescue nil
if page.nil?
page = Page.new(:module => ma.key, :page_id => "gallery", :layout => "gallery_index1", :name_translations => {"en" => "Gallery", "zh_tw" => "相簿"}, :url => "/gallery", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
page.save
end
if ma.categories.empty?
cat = Category.new
cat.title_translations = {"en" => "Gallery", "zh_tw" => "相簿"}
cat.module_app = ma
cat.save
else
cat = ma.categories.first
end
if ma.tags.empty?
tag = Tag.new
tag.name_translations = {"en" => "Gallery", "zh_tw" => "相簿"}
tag.module_app_ids << ma.id
tag.save
else
tag = ma.tags.first
end
fake_ids = []
(1..total_count).each do |i|
album = Album.new(:name_translations => get_random_title, :description_translations => get_random_subtitle)
album.tags=tag
album.category = cat
album.save
fake_ids << album.id
(1..rand(5..10)).each do |x|
image = AlbumImage.new(:title => get_random_title["zh_tw"], :description_translations => get_random_title, :order => x)
image.remote_file_url = get_fake_image_url(ma.key)
image.album = album
image.save
end
end
commit_fake_data(ma, fake_ids)
end
def delete_gallery_fake_data(ma)
fd = FakeData.where(:module => ma).first rescue nil
albums = Album.where(:id.in => fd.ids)
albums.destroy_all
fd.destroy
end
def make_web_resource_fake_data(ma, total_count=5)
page = Page.Where(:module => ma.key).first rescue nil
if page.nil?
page = Page.new(:module => ma.key, :page_id => "links", :layout => "web_res_index1", :name_translations => {"en" => "Links", "zh_tw" => "連結"}, :url => "/links", :enabled_for => ["en", "zh_tw"], :menu_enabled_for => ["en", "zh_tw"], :categories => ["all"], :tags => ["all"], :enabled_for_sitemap => ["en", "zh_tw"], :parent_page => Page.root)
page.save
end
if ma.categories.empty?
cat = Category.new
cat.title_translations = {"en" => "Links", "zh_tw" => "連結"}
cat.module_app = ma
cat.save
else
cat = ma.categories.first
end
if ma.tags.empty?
tag = Tag.new
tag.name_translations = {"en" => "Links", "zh_tw" => "連結"}
tag.module_app_ids << ma.id
tag.save
else
tag = ma.tags.first
end
fake_ids = []
(1..total_count).each do |i|
link = WebLink.new(:title_translations => get_random_title, :context_translations => get_random_subtitle, :url_translations => {"en" => get_fake_link, "zh_tw" => get_fake_link}, :create_user_id => current_user.id.to_s, :update_user_id => current_user.id.to_s, :link_open => WebLink::LINK_OPEN_TYPES.sample, :is_top => get_random_status, :is_hot => get_random_status)
link.category = cat
link.tags=tag
link.save
fake_ids << link.id
end
commit_fake_data(ma, fake_ids)
end
def delete_web_resource_fake_data(ma)
fd = FakeData.where(:module => ma).first rescue nil
links = WebLink.where(:id.in => fd.ids)
links.destroy_all
fd.destroy
end
def get_fake_date(no=100)
Time.now + rand(1..no).days
end
def get_fake_link
["http://www.google.com", "http://www.rulingcom.com", "http://www.yahoo.com", "http://www.9gag.com", "http://www.youtube.com", "http://www.linkedin.com","http://www.imdb.com", "http://www.github.com", "http://www.google.co.in", "https://en.wikipedia.org/wiki/Wikipedia"].sample
end
def commit_fake_data(ma, fake_ids)
fd = FakeData.where(:module => ma.key).first rescue nil
if fd.nil?
FakeData.create(:module => ma.key, :ids => fake_ids)
else
fd.ids = fd.ids.concat(fake_ids)
fd.save
end
end
def get_fake_file_url(key)
OrbitStore::URL + "/fake_data/#{key}/files/" + rand(1..5).to_s + ".txt"
end
def get_fake_image_url(key)
OrbitStore::URL + "/fake_data/#{key}/images/" + rand(1..15).to_s + ".jpg"
end
def get_random_status
[true,false,true,true,false,false,false,false,false,false,false,true,false,true,false,true,false,false,true,false,true,false,true,false,false,false,false,false,true,false,true,false].sample
end
def get_random_title
[
{
"en" => "Lorem ipsum Quis deserunt culpa velit ea enim do labore ex.",
"zh_tw" => "廣州百萬招聘往往角色所有爆炸後面自從本站慢慢插件,一批研發雙手變成漸漸出去將在先生她們清楚寂寞降,功夫女性線路才能設置之家好處朋友警方放心連載有的創意教。"
},
{
"en" => "Lorem ipsum Voluptate consectetur labore sed nisi Duis Duis in ut sit.",
"zh_tw" => "確實姓名走出被人相對壓縮生活關注培訓紡織有所裡面房,是有能源威脅他是文本上帝印刷年輕,深圳科技有限公司類別廣播我家機制我說加入接收執行時間,求購人物轉讓大聲相當運行中心,恢復據說資本人物專欄房屋記得感受謝謝市委用戶"
},
{
"en" => "Lorem ipsum Ut adipisicing laboris tempor cillum eu tempor est minim ut deserunt elit sit.",
"zh_tw" => "對外購買創新發現跟著欣賞掌握第二天,最初結構投資體系招生髮表不滿請點擊手,那些結果警察一下回事可用其中避免贏得大學還是按照利潤。"
},
{
"en" => "Chinese Lorem Ipsum includes the most common kanji chars and punctuation. Suggestions for improvements or alternatives are welcome.",
"zh_tw" => "速牧摘藤請能攜針紹掲式盤談。報厚勝月注揚件岡視申邊幅念七屬年。頼疑観小章的談集演選容善為真北上左。"
},
{
"en" => "Lorem ipsum is a pseudo-Latin text used in web design, typography, layout, and printing in place of English to emphasise design elements over content.",
"zh_tw" => "側經意責家方家閉討店暖育田載社轉線宇。得君新術治溫抗添代話考振投員毆大北裁。"
},
{
"en" => "Lorem ipsum Officia sed cillum aute magna consectetur nulla adipisicing magna.",
"zh_tw" => "英文業務體現首頁聽到禁止警察平衡誠信上次基金次數。"
},
{
"en" => "Lorem ipsum Mollit officia sunt ea reprehenderit velit laborum.",
"zh_tw" => "解壓密碼效益價格女孩怪物高校互聯網交給商品人士儲存,優勢通過讓她都是親自一生現場大家動態,作用不同再度在此標題肯定優惠服。"
}
].sample
end
def get_random_subtitle
[
{
"en" => "Lorem ipsum is a pseudo-Latin text used in web design, typography, layout, and printing in place of English to emphasise design elements over content. It's also called placeholder (or filler) text. It's a convenient tool for mock-ups.",
"zh_tw" => "財富整無必提引人懸身作渡健朝化紙事。人解食米生利娘法平終票織絶般改。文本行暮際對新左報事迫開件勝初測出人。速摘藤請能攜針紹式盤談。報厚勝月注揚件視申幅念七屬年。頼疑小章的談集演選容為真北左。"
},
{
"en" => "While lorem ipsum's still resembles classical Latin, it actually has no meaning whatsoever. As Cicero's text doesn't contain the letters K, W, or Z, alien to latin, these, and others are often inserted randomly to mimic the typographic appearence of European languages, as are digraphs not to be found in the original.",
"zh_tw" => "目報貴代向能究介集分頃妻。休表化降最州別文東表住線。呼支保木前果告共芝暴禁玉姫五點稚。第色絡明域市造神草要督運流題。信下臨法職左通出官質給探。沖金普議雪受國女出般馬紙手災半塊。通別暮載典子郎將開展造能一。"
},
{
"en" => "In a professional context it often happens that private or corporate clients corder a publication to be made and presented with the actual content still not being ready. Think of a news blog that's filled with content hourly on the day of going live. However, reviewers tend to be distracted by comprehensible content.",
"zh_tw" => "轉殺東入館特造賠感購予主市推製理承博。選被桶善外出神際抵法政。品誰非萬女話感合文昭。恐勢供村著雨木助階野食川園公大。連返一暮際平首寫一會未京美刃。珍者見藤石第返前鳥科宅様。直島載死談待思際考以響策依室參將機。演況民王手更愛五督銘索女。"
}
].sample
end
def get_random_content
[
{
"en" => "Lorem ipsum In magna nisi aliquip enim ex consectetur. Lorem ipsum Id laboris veniam ullamco velit minim sit in aute commodo. Lorem ipsum Eiusmod nisi consectetur eu nostrud nisi et commodo laborum sint commodo. Lorem ipsum Irure aliquip laboris aliquip qui sint incididunt sunt nisi Ut pariatur. Lorem ipsum Sint culpa proident consequat sed eu proident ex ea dolor. Lorem ipsum Aliquip proident adipisicing fugiat fugiat consequat sed ex nulla. Lorem ipsum Labore culpa enim enim voluptate cillum velit labore esse voluptate. Lorem ipsum Aute est quis mollit consectetur reprehenderit. Lorem ipsum Pariatur et in Ut id laboris aute aliqua. Lorem ipsum Ut id non ad cillum non est ad sunt reprehenderit in nulla. Lorem ipsum Ea commodo cillum veniam Ut aute exercitation ullamco dolor aliqua. Lorem ipsum Quis anim ad officia esse ut magna. Lorem ipsum Irure aute reprehenderit officia esse qui ex laborum mollit Duis laboris.",
"zh_tw" => "對待證券首頁看法我和確認發布你看明顯之類答案透明多麼破,確保風險做法吸收不大,誘惑女子新手不論不可地上採購能力漫畫音樂營養河北笑,蒐集製造英國河南即可決策所說強化註冊還有廣場這麼這樣,好友音樂黃金有一定女,次數黑暗想法告知手續北京註冊。循環策略簡體中文股份塑料,加入時間經過會不會一家特色公告屬性協議多,公告穿著死亡說明角度體制交通路線期間太陽問題桌面依法,影視大學生道德虛擬業主自由不能,進去飛機本周越來越傳奇結構批發新人官員要有下,理念現像對比用戶名中國計算機目的,定位插件晚上加油年輕僅僅監督探索授權方式創業經營放棄。處理實現航空規定明天總,這一電源限制原因意思指數實驗表達互動代理體內較大早就代表,就不參數貢獻服務理論一方面計算進來貫徹規格面議不如監管證據,優秀監管試題回答容量,突破允許障礙考研你能也就是他們的我說空調也,拍攝男女增長其他官方方面發布結束模擬女子出了欄目我的心他,大幅備案無數貿易多種和平招聘,一時商標要在從事毫不手段經典可能會遭,高達旁邊演員代理適用於鑑定堅持管理。許多本次臨時發現小學前往第二章新型鏈接讓她這里聯賽鄭,相關讀者存儲博客零售最近多次付出造成請點擊也在房間帶,出去說是避免騎士還是注重不停網通相冊排行榜到處,尊重思路回到責任編輯每個人鬱,靈魂沒有甚至自己可能會說過出席化學新技術對手責任編輯可惜他說,家庭諾基亞沒事開通個性保密辛苦文檔選擇準備商城基本上他也休閒。"
},
{
"en" => "Lorem ipsum Ad dolor in aliqua labore in dolor qui anim laborum. Lorem ipsum Et sed cillum anim nisi dolore. Lorem ipsum Enim sit dolor incididunt in tempor laborum nulla dolor nulla officia. Lorem ipsum Ut ea incididunt ad in esse eiusmod magna Excepteur sed esse. Lorem ipsum Cupidatat elit in ut dolore in mollit velit. Lorem ipsum Dolor enim aliqua consectetur veniam exercitation anim Duis occaecat aute in ex. Lorem ipsum Voluptate eiusmod sint pariatur quis velit aute enim fugiat. Lorem ipsum Officia dolore exercitation nisi qui minim anim id magna exercitation. Lorem ipsum Non in mollit veniam ut Excepteur officia. Lorem ipsum Ea in aliqua non ut commodo consequat commodo proident in anim. Lorem ipsum Culpa et Excepteur occaecat incididunt laborum pariatur ad ex reprehenderit. Lorem ipsum Cillum sed occaecat elit Excepteur Duis dolor exercitation commodo ut dolore. Lorem ipsum Sunt reprehenderit in dolore voluptate Excepteur ullamco pariatur sed dolore magna nisi. Lorem ipsum Mollit anim Ut elit aliqua labore laborum aliquip commodo nisi sint. Lorem ipsum Esse eu elit in nisi id sint nulla consectetur.",
"zh_tw" => "加入時間一樣轉讓能量人們導致要有互動初步同學手機是怎麼,無關比例穿著再說上來好像我愛充滿當,新聞支付不足增加發揮神經果然將。招商經濟發展不少最後條款準確不,接受之類觀點身影蘇州總部可見言論空中一會這個問題電子如果您,解放危機顯卡享受足夠味道快速分類回答生成聯。一款帶來監督獎勵也能台北提出開了前面檢查,監管液晶交易建設而言看過放下江湖對了航空,智慧現代化緊緊一邊哥,屏幕長大角色前面精神新華網,刷新物質滿意看看反饋情感放在購買男生簡,默認最重要男孩世界杯還可以獲取全市版主我,位於讓他菜單矛盾塑料讓我畢業生作用人大常委會清楚寂。它們排行榜一張優勢本身接著感情人間有時候排行他就,形式第二天加快查詢尷尬影視大全你有詳細勝利和你演出出,世界杯多多供應改革監督出台作出總結提高最快全體美元文明西,神經那天法院你會靈活備案味道減,總是處理器森林服務器便宜中央不得不福建,回應插件倒是我們告訴你多媒體政府江蘇遺憾開口哥哥,言論你想文學外貿將會母親辛苦部落分析例如高級對,有限責任公司回事核心只要它們以往哪些大幅提交優勢對外否則。全省讓我們享受騎士嘗試男生新華網據說用戶,數碼相機用戶名退出得到見面部門老公小區讓他大賽被人開了,職責溝通字幕普遍介紹運,每年有一些點這裡下載身子竟然篇文章全國新年多個是不是天津您。這段頭銜下降河北獲得防止獨立道理公主策劃部落方案其實,等等等待不錯客服以外提示商家面對新聞,虛擬排行榜可以說恢復此時加大優勢上漲第一。品牌天使本身電子放在勝,又有痛苦尤其是如有商品金額有限公司爭取森林舉報好評期,印刷說到一部分金錢酒店畢業生交友概念治理付出,患者研究真實污染大力外資西安一聲這麼多內置舉報投,進步上次所需治理上傳文件大小否則個人形成有限責任公司成果魔法。提前安排的是考研起來手指小心所以監控一看很難一,媽媽在線有限責任公司適應重視就好會員增加環境試驗青年謝謝四川,贏得客人生意賓館語文。一體情形接下來鈴聲玻璃數碼相機動物英,出了禮物值得書庫看起來開了,治理不喜歡互相妻子偉大頭銜滿意動力花,似乎立刻爭取魔獸作品把你頻道,價值工程種種鐵路模擬慢慢保持爆炸才是迅速同一進,接收相關配套分配案例以後方面,具體室內請大家路線法律責任會員你有多,傳真零售日韓人事避免教育活,協調同步實施身影一大等方面海外本。趕緊安排特色技巧它們如果你非法,位於是由稱為不肯不錯核心你是行情明,股東日期值得國產正文,水晶後面模樣出售好多,說到不足怎麼辦市場名單友情鏈接稿件事,成熟隨著轉移解決不在人類台灣還在,家族慢慢鐵通怎麼電器願意設置內容簡介點這裡自主創,發貼或是男子裝置舉行網通優勢不限交通沒事聯盟最。年齡寶寶你自己曝光儀器體會情況不可一台這次考生農業變化鼠標,情感就在這麼多結婚身上公里給我紡織轉讓,錄入流程形成真實過了預防是有其實科技設計,外資充分森林如有事業,股東欣賞污染開展法院山東還沒有英國英文投票。廣播本地下載均為部分還可以,理解一對平時為何精華並不地址老婆演,一對不能湖北爸爸讓她早就酒店權力歐,同一先進多個協調通過創造關心機構興奮有機會都,笑話文化請求稿件我這現實求助改革,標題令人限制批准是個聯賽理念竟然麻煩目前,導航街道上次最新是他次數需,先進性反而付款認識批准禮物像是郵政。水果合理不肯智能明天世,時間措施鍵盤大部分國家吸引東西藥品不大作為光臨所謂,有時發行將軍女性再說都沒裡面地上實際上股權語文而已運行平台結,郵編但我前面讓我們亞洲拿出必須人口商品全身突破退出作品當中計,具備出發反正您是公斤想要。"
}
].sample
end
end

View File

@ -1,237 +0,0 @@
require "uri"
require "net/http"
module OrbitBackendHelper
def self.included(base)
ActionView::Helpers::FormBuilder.send(:include,OrbitFormHelper)
end
def group_impression_by_day(field,day_limit,start_day=Date.today,format = 'day')
limit_ele = Impression.desc(:id).where({ created_at: { "$lt" => start_day-(day_limit-2).days }}).first || Impression.first
key_op = [['year','$year'],['month', '$month'], ['day', '$dayOfMonth']]
key_op = key_op.take(1 + key_op.find_index { |key, op| format == key })
project_date_fields = Hash[*key_op.collect { |key, op| [key, {op => "$#{field}"}] }.flatten]
group_id_fields = Hash[*key_op.collect { |key, op| [key, "$#{key}"] }.flatten]
pipeline = [
{"$match"=> {"_id" => {"$gte" => (limit_ele['_id'] rescue '')}}},
{"$project" => {field => 1}.merge(project_date_fields)},
{"$group" => {"_id" => group_id_fields,"count" => {"$sum" => 1}}},
{"$sort" => {"_id"=>-1}}
]
tmp = Impression.collection.aggregate(pipeline)
if tmp.count < day_limit
tmp1 = tmp
tmp = (0...day_limit).collect do |i|
d = start_day - i.days
d_year = d.year
d_month = d.month
d_day = d.day
count = tmp1.select do |v|
n_date = v['_id']
n_date['year']==d_year && n_date['month']==d_month && n_date['day']==d_day
end[0]['count'] rescue 0
{'_id'=>{'year'=>d_year,'month'=>d_month,'day'=>d_day},'count'=>count}
end
puts ['tmp',tmp]
end
tmp
end
def thead(field,center=false,enable_sort=true)
sort = field.to_s.include?('.') ? field.to_s.split('.')[1] : field.to_s
active = params[:sort].eql? sort
order = active ? (["asc", "desc"]-[params[:order]]).first : "asc"
arrow = (order.eql? "desc") ? "<b class='icons-arrow-up-3'></b>" : "<b class='icons-arrow-down-4'></b>"
klass = field.eql?(:title) ? "span5" : "span2"
th_data = (sort=="preview" || !enable_sort) ? t(field.to_sym) : "<a href='?sort=#{sort}&order=#{order}'>#{t(field.to_sym)} #{active ? arrow : ""}</a>"
"<th class='#{klass} #{active ? "active" : ""}' style='#{center ? "text-align:center" : ""}'>#{th_data}</th>".html_safe
end
def add_attribute(partial, f, attribute)
new_object = f.object.send(attribute).build rescue nil
fields = f.fields_for(attribute, new_object, :child_index => "new_#{attribute}") do |f|
render :partial => partial, :object => new_object, :locals => {:f => f}
end
end
def is_filter_active?(field, value)
params[:filters][field].include?(value.to_s) ? "active" : "" rescue ""
end
def select_category(f, module_app)
@user_authorized_categories = module_app.categories.enabled.authorized(current_user) if @user_authorized_categories.nil?
render :partial => '/admin/categories/select_form', :locals => {:f=> f, :module_app=>module_app, :categories=> @user_authorized_categories }
end
def copy_to_all_language_button(language_tab, language_area)
render :partial => '/shared/copy_to_all_language_button', :locals => {:language_area => language_area, :language_tab => language_tab}
end
def select_tags(f, module_app)
render :partial => '/admin/tags/tag_form', :locals => {:f=> f, :module_app=>module_app, :tags=>module_app.tags }
end
def render_filter(fields, search_dom_id=nil, quick_new=false)
render :partial => "shared/filter", :locals =>{:fields => fields, :search_dom_id=>search_dom_id, :quick_new=>quick_new}
end
def display_visitors(options={})
Impression.where(options).count
end
def display_visitors_today
if (defined? @result_of_thirty_day).nil?
display_visitors(created_at: {'$gte' => Time.now.beginning_of_day})
else
@result_of_thirty_day[0]['count']
end
end
def display_visitors_this_week
if (defined? @result_of_thirty_day).nil?
display_visitors(created_at: {'$gte' => Time.now.beginning_of_week})
else
@result_of_thirty_day[0..((Time.now-Time.now.beginning_of_week)/86400).floor].map{|v| v['count']}.reduce{|v,x| v+x}
end
end
def display_visitors_this_month
if (defined? @result_of_thirty_day).nil?
visitors_this_month = Rails.cache.fetch("visitors_this_month", expires_in: 1.day) do
display_visitors(created_at: {'$gte' => Time.now.beginning_of_month})
end
visitors_this_month
else
@result_of_thirty_day[0..((Time.now-Time.now.beginning_of_month)/86400).floor].map{|v| v['count']}.reduce{|v,x| v+x}
end
end
def display_visitors_this_year
visitors_this_year = Rails.cache.fetch("visitors_this_year", expires_in: 1.day) do
display_visitors(created_at: {'$gte' => Time.now.beginning_of_year})
end
visitors_this_year
end
def get_month_traffic
#site = Site.first
#if site.month_traffic_cache.blank? or (site.month_traffic_cache['updated_at'] < (Time.now-1.day) rescue true)
#site.month_traffic_cache = {}
#site.month_traffic_cache['result'] = []
@result_of_thirty_day = group_impression_by_day(:created_at,30)
trafic_result = @result_of_thirty_day.map do |v|
date = v['_id'].values
[Date.new(date[0],date[1],date[2]).to_time,v['count']]
end
#site.month_traffic_cache['result'] = trafic_result
#site.month_traffic_cache['updated_at'] = Time.now
#site.save
#end
#[:name=> t(:visitors_count),:data=>site.month_traffic_cache['result']]
[:name=> t(:visitors_count),:data=>trafic_result]
end
def can_edit_or_delete?(obj)
create_user = obj.create_user_id.to_s rescue nil
if @user_authenticated_categories.first == "all"
return true
elsif obj.class == Page && current_user.is_manager?(ModuleApp.where(:key=>'page_content').first)
return true
elsif @current_user_is_sub_manager && !create_user.nil?
create_user == current_user.id.to_s
else
@user_authenticated_categories.include?obj.category_id rescue (current_user.is_manager?(@module_app) rescue false)
end
end
def user_authenticated_categories
@user_authenticated_categories
end
def is_user_sub_manager?
@current_user_is_sub_manager
end
def has_access? #@user_has_privileges comes from orbit_member_controller.. used just in members
@user_has_privileges
end
def check_store_permissions #checks with the store if it has proper access and rights to access store
store_permission = {}
store_token = current_site.store_token rescue nil
if !store_token.nil?
params_to_send = {'store_token' => current_site.store_token}
uri = URI.parse(OrbitStore::URL)
http = Net::HTTP.new(uri.host,uri.port)
http.read_timeout = 25 #seconds
request = Net::HTTP::Get.new("/site/permissions")
request.body = params_to_send.to_query
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
if response.nil?
data = {}
data["message"] = "Could not connect to the store."
data["error"] = "CONNECTION_REFUSED"
data["success"] = false
else
data = JSON.parse(response.body) rescue nil
end
if data.nil?
data = {}
data["message"] = "Could not connect to the store."
data["error"] = "JSON_ERROR"
data["success"] = false
end
if !data["success"]
case data["error"]
when "INVALID_SITE_TOKEN"
current_site.store_token = nil
current_site.save
end
store_permission["permission_granted"] = false
store_permission["error"] = data["error"]
store_permission["message"] = data["message"]
else
store_permission["permission_granted"] = true
end
else
store_permission["permission_granted"] = false
store_permission["error"] = "SITE_NOT_REGISTERED"
store_permission["message"] = "Site not registered."
end
store_permission
end
def render_401
render "errors/401"
end
def render_403
render "errors/403"
end
def need_access_right
render_401 if !has_access?
end
def get_referer_url
referer_path = Rails.application.routes.recognize_path(request.referer)
if referer_path[:controller]!="pages" or (referer_path[:controller]==params[:controller] and referer_path[:action]!="index")
referer_url = '/'+params[:controller]
else
referer_url = request.referer
end
referer_url
end
end

View File

@ -1,150 +0,0 @@
module OrbitFormHelper
def self.included(base)
#ActionView::Helpers::FormBuilder.send(:include, Orbit::FormBuilder)
ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::UrlHelper)
ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::TagHelper)
ActionView::Helpers::FormBuilder.send(:include,ActionView::Context)
ActionView::Helpers::FormBuilder.send(:include,ActionView::Helpers::FormTagHelper)
end
def datetime_picker(object_name, options = {})
options[:icon_time] ||= 'icons-clock'
options[:icon_date] ||= 'icons-calendar'
options[:icon_clear] ||= 'icons-cross-3'
options[:input_class] ||= 'input-large'
options[:new_record] = true if options[:new_record].nil?
options = objectify_options(options)
options[:value] ||= options[:object].send(object_name) if options[:object] && options[:object][object_name]
options[:placeholder] ||= (options[:format].to_s.empty? ? nil : options[:format])
case options[:picker_type]
when 'date'
content_tag :div, :id => options[:id], :class => options[:class] do
date_picker(object_name, options)
end
when 'time'
content_tag :div, :id => options[:id], :class => options[:class] do
time_picker(object_name, options)
end
when 'separated'
options[:label] ||= I18n.t('datetime_picker.separated.label')
content_tag :div, :id => options[:id], :class => "separated_picker #{options[:class]}" do
concat label_tag options[:label] unless options[:no_label]
concat hidden_field(object_name, :value => options[:value])
concat separated_picker(object_name, options)
end
when 'simple'
content_tag :div, :id => options[:id], :class => options[:class] do
simple_picker(object_name, options)
end
else
content_tag :div, :id => options[:id], :class => options[:class] do
default_picker(object_name, options)
end
end
end
def default_picker(object_name, options)
custom = {}
options[:format] = options[:format] || 'yyyy/MM/dd hh:mm'
options[:value] = format_value(options[:value], options[:format]) if options[:value] && !options[:new_record]
options[:value] = "" if options[:new_record]
custom[:picker_class] = 'default_picker'
custom[:label] = options[:label] || I18n.t('datetime_picker.default.label')
custom[:placeholder] = options[:placeholder] || I18n.t('datetime_picker.default.placeholder')
picker(object_name, options.merge(custom))
end
def picker(object_name, options)
content_tag :div, :class => "#{options[:picker_class]} input-append" do
concat label_tag options[:label] unless options[:no_label]
if object_name.nil?
if !options['id'].nil?
concat text_field_tag nil ,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :data => options[:data], :id => options['id']
else
concat text_field_tag nil,options[:value], :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :data => options[:data]
end
else
if !options['id'].nil?
concat text_field object_name , :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data], :id => options['id']
else
concat text_field object_name, :placeholder => options[:placeholder], :class => options[:input_class], 'data-format' => options[:format], :value => options[:value], :data => options[:data]
end
end
concat (content_tag :span, :class => 'add-on clearDate' do
content_tag :i, nil, :class => options[:icon_clear]
end)
concat (content_tag :span, :class => 'add-on iconbtn' do
content_tag :i, nil, 'data-time-icon' => options[:icon_time], 'data-date-icon' => options[:icon_date]
end)
end
end
def format_value(value, format = 'yyyy-MM-dd hh:mm')
value.strftime(format.gsub('yyyy', '%Y').gsub('MM', '%m').gsub('dd', '%d').gsub('hh', '%H').gsub('mm', '%M')) rescue ""
end
def simple_picker(object_name, options)
onkeypress_for_input = 'return (event.charCode >= 48 && event.charCode <= 57) || event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 9'
onkeyup_for_input = 'this.value=(this.value.length <= 2 ? (parseInt(this.value) > 0 && parseInt(this.value) < 32 ? this.value : this.value.substring(0,this.value.length-1)) : this.value.substring(0,this.value.length-1))'
onkeyup_for_input2 = 'this.value=(this.value.length == 4 ? (parseInt(this.value) > 1900 && parseInt(this.value) < 3000 ? this.value : this.value.substring(0,this.value.length-1)) : (this.value.length > 4 ? this.value.substring(0,this.value.length-1) : this.value))'
html = "<div class='simple-date-picker'>
<input type='text' class='span1' #{(options[:value] ? "value='#{options[:value].day}'" : "")} placeholder='Date' onkeypress='#{onkeypress_for_input}' onkeyup='#{onkeyup_for_input}'>
<select class='span2'>"
["January","February","March","April","May","June","July","August","September","October","November","December"].each_with_index do |mon,index|
html = html + "<option value='#{(index < 9 ? "0" : "")}#{(index + 1).to_s}' #{(options[:value] && options[:value].month == (index + 1) ? "selected='selected'" : "")}>#{mon}</option>"
end
html = html + "</select><input type='text' class='span3' #{(options[:value] ? "value='#{options[:value].year}'" : "")} placeholder='Year' onkeypress='#{onkeypress_for_input}' onkeyup='#{onkeyup_for_input2}'>"
html = html + hidden_field(object_name, :value => options[:value] || "1901-01-01")
html = html + "</div>"
html.html_safe
end
def date_picker(object_name, options)
custom = {}
custom[:format] = options[:format] || 'yyyy/MM'
custom[:value] = format_value(options[:value], custom[:format]) if options[:value]
custom[:picker_class] = 'date_picker'
custom[:label] = options[:label] || I18n.t('datetime_picker.date.label')
options[:placeholder] ||= I18n.t('datetime_picker.date.placeholder')
picker(object_name, options.merge(custom))
end
def time_picker(object_name, options)
custom = {}
custom[:format] = options[:format] || 'hh:mm'
custom[:value] = format_value(options[:value], custom[:format]) if options[:value]
custom[:picker_class] = 'time_picker'
custom[:label] = options[:label] || I18n.t('datetime_picker.time.label')
custom[:placeholder] = options[:placeholder] || I18n.t('datetime_picker.time.placeholder')
picker(object_name, options.merge(custom))
end
def separated_picker(object_name, options)
custom = {}
custom[:no_label] = true
custom[:separated] = true
date_picker(nil, options.merge(custom).merge({:format=>'yy/mm/dd','id'=>"_1_#{object_name}"})) + time_picker(nil, options.merge(custom).merge({:format=>'hh:mm','id'=>"_2_#{object_name}"}))
end
def single_picker(object_name, options)
content_tag :div, :id => options[:id], :class => options[:class] do
picker(object_name, options)
end
end
def double_picker(object_name, options)
end
end
module Orbit::FormBuilder
# ActionPack's metaprogramming would have done this for us, if FormHelper#labeled_input
# had been defined at load. Instead we define it ourselves here.
#def datetime_picker(method, options = {})
# @template.datetime_picker(@object_name, method, objectify_options(options))
#end
end

View File

@ -1,5 +0,0 @@
class Multithread
include Mongoid::Document
field :key
field :status
end

View File

@ -1,6 +0,0 @@
class PageSet
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :site
field :auto_convert_flag, type: Boolean, :default => false
end

View File

@ -1,117 +0,0 @@
class Site
include Mongoid::Document
include Mongoid::Timestamps
include Slug
DEBUG = false
has_many :page_sets, :autosave => true, :dependent => :destroy
accepts_nested_attributes_for :page_sets, :allow_destroy => true
field :title, as: :slug_title, type: String, localize: true
field :school, type: String
field :department, type: String
field :address, type: String
field :footer, localize: true
field :social_share, type: String
field :sub_menu, localize: true
field :site_type
field :site_map_link, type: String, :default => "/sitemap"
field :terms_of_use_link, type: String
field :google_analytics, type: String
field :in_use_locales, :type => Array
field :valid_locales, :type => Array
field :site_active, :type => Boolean
field :frontend_open, :type => Boolean, :default => true
field :backend_openness_on, :type => Boolean, :default => false
field :mobile_api_openness_on, :type => Boolean, :default => false
field :desktop_closed, :type => Boolean, :default => false
field :enable_language_detection, :type => Boolean, :default => false
field :enable_redirect_index, :type => Boolean, :default => true
field :enable_zh_cn, :type => Boolean, :default => true
field :enable_language_options, :type => Boolean, :default => true
field :default_locale, :default => "zh_tw"
field :mobile_on, :type => Boolean, :default => false
field :announcement_category, :type => Array, :default=>[]
field :mobile_bar_color, :type => Array, :default=>[]
field :phone_number, :type => Array,:default=>[]
field :title_always_on, :type => Boolean, :default => false
field :display_title_in_frontend, :type => Boolean, :default => true
field :sitemap_menu_in_header, :type => Boolean, :default => false
field :enable_terms_of_use, :type => Boolean, :default => false
field :search,:type => Hash
field :site_settings
field :template, type: String
field :store_token
field :enable_last_update, type: Boolean, :default => false
field :personal_plugins_sort, type: Array, :default => []
field :sign_up_roles, type: Array, :default => []
field :required_sign_up_attributes , :type => Hash , :default => {}
field :mobile_orbit_bar_title, localize: true
field :google_oauth_enabled, :type => Boolean, :default => false
field :google_client_id
field :google_client_secret
field :meta_tags
field :every_page_sharer, type: Array, :default => ["facebook","twitter","google","printer"]
field :sync_enabled, type: Boolean, :default => false
field :sync_rake_task
field :month_traffic_cache
field :home_link, :type => String, :default=>"/"
field :home_link_1, :type => String, :default=>"/"
field :site_title, :type => Hash, :default=>{:zh_tw=>"主頁",:en=>"home_page"}
field :site_title_1, :type => Hash, :default=>{:zh_tw=>"主頁",:en=>"home_page"}
field :is_hidden_orbit_bar , type: Boolean, :default => false
field :orbit_bar_background_color , type: String, :default => ""
field :orbit_bar_background_hover_color
field :orbit_bar_text_color , type: String, :default => "#ffffff"
field :orbit_bar_text_hover_color
field :orbit_bar_submenu_background_color , type: String, :default => ""
field :orbit_bar_submenu_text_color , type: String, :default => "#ffffff"
field :orbit_bar_animation_time , type: String, :default => "0.3s"
field :login_text , type: String, :default => "", localize: true
mount_uploader :default_image, ImageUploader
mount_uploader :site_logo, ImageUploader
mount_uploader :site_logo_1, ImageUploader
mount_uploader :favicon, ImageUploader
mount_uploader :mobile_icon, ImageUploader
after_initialize do |record|
if !record.new_record?
if record.is_hidden_orbit_bar.nil?
record.is_hidden_orbit_bar = false
record.save
end
if record.orbit_bar_background_color.nil?
record.orbit_bar_background_color = ""
record.save
end
if record.orbit_bar_text_color.nil?
record.orbit_bar_text_color = ""
record.save
end
if record.orbit_bar_submenu_background_color.nil?
record.orbit_bar_submenu_background_color = ""
record.save
end
if record.orbit_bar_submenu_text_color.nil?
record.orbit_bar_submenu_text_color = ""
record.save
end
if record.orbit_bar_animation_time.nil?
record.orbit_bar_animation_time = "0.3s"
record.save
end
end
if record.orbit_bar_background_color == '#000000' && record.orbit_bar_text_color == '#000000'
record.update(:orbit_bar_text_color => '#ffffff')
end
if record.orbit_bar_submenu_background_color == '#000000' && record.orbit_bar_submenu_text_color == '#000000'
record.update(:orbit_bar_submenu_text_color => '#ffffff')
end
end
def register_site(url,university,department,email,country)
api_key = STORE_CONFIG[:store_settings]["api_key"]
self.generate_site_token
store = Store.new(self.id.to_s,self.site_token,api_key)
store.post_client(self.id.to_s,self.site_token,self.title,url,university,department,email,country)
end
end

View File

@ -1,54 +0,0 @@
<script src="/assets/lib/jquery-ui-1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="/assets/lib/jquery-ui-1.12.1/jquery-ui.min.css">
<script type="text/javascript">
function see_detail(i){
$(".detail-only-content-"+i).dialog("option", "width", $(window).width()*0.8);
$(".detail-only-content-"+i).dialog("option", "min-height", $(window).height()*0.2);
$(".detail-only-content-"+i).dialog("option", "max-height", $(window).height()*0.8);
$(".detail-only-content-"+i).dialog("option", "max-height", $(window).height()*0.8);
if ($(".detail-only-content-"+i).find('.content').attr('data-href')==''){
$(".detail-only-content-"+i).dialog("option", "buttons", {});
}
$(".detail-only-content-"+i).dialog("open");
}
$(document).ready(function(){
$("div[class^='detail-only-content']").dialog({
autoOpen: false,
show: "blind",
model:true,
hide: "explode",
buttons:{
'<%= t('announcement.more') %>':function(){
window.open($(this).parents("div").find('.content').attr('data-href'), "_blank")
}
}
});
})
</script>
<% Array(@data['site_anncs']).compact.each_with_index do |v,i| %>
<div class="detail-only-content-<%= i %>">
<div class="content" data-href="<%= v['see_more_link'] %>">
<%= v['content'][I18n.locale.to_s].to_s.html_safe %>
</div>
</div>
<% end %>
<div class="box-header">
<h2>
<i class="icons-chat"></i>
<span class="break"></span>
Messages from RulingCare
</h2>
</div>
<div class="box-content">
<table class="table table-bordered table-striped table-hover">
<tbody>
<% Array(@data['site_anncs']).compact.each_with_index do |v,i| %>
<tr>
<td style="cursor: pointer;" onclick="see_detail(<%= i %>)"><%= v['title'][I18n.locale.to_s].to_s.html_safe %></td>
</tr>
<% end %>
</tbody>
</table>
</div>

View File

@ -1,310 +0,0 @@
<!-- test for some stuff -->
<style type="text/css">
.container{
}
#new_update_container{
display: none;
}
#update_progress{
margin: 0 auto;
text-align: center;
}
#update_status{
/*display: none;*/
}
#update_done{
display: none;
}
#update_failed{
display: none;
}
.panel{
/*max-height: 400px;*/
border-radius: 5px;
overflow: hidden;
border: 1px solid #DFDFDF;
background: #FFF;
box-shadow: 0px 0px 10px #CCC;
}
.panel-heading{
font-size: 16px;
color: #666;
padding: 10px 20px;
background-color: #fafafa;
background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2));
background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2);
background-image: -o-linear-gradient(top, #ffffff, #f2f2f2);
background-image: linear-gradient(to bottom, #ffffff, #f2f2f2);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0);
*zoom: 1;
border-bottom: 1px solid #DDD;
}
.table{
margin: 0;
-webkit-border-radius: 5px;
border-radius: 5px;
}
.pannel-body{
max-height: 400px;
overflow: scroll;
overflow-x: hidden;
overflow-y: hidden;
padding: 15px;
}
.pannel-body:hover{
overflow-y: scroll;
}
::-webkit-scrollbar {
width: 5px;
}
::-webkit-scrollbar-track {
background-color: #AAA;
}
::-webkit-scrollbar-thumb {
background-color: #666;
}
.break{
border-left: 1px solid #FCFCFC;
border-right: 1px solid #DDD;
padding: 10px 0;
margin: 0 15px;
}
</style>
<div class="container">
<div class="row-fluid">
<div class="span6">
<div id="new_update_container">
<div class="panel">
<div class="panel-heading">
<i class="icon-exclamation-sign"></i>
<span class="break"></span>
<span class="panel-title"><%= t("update_manager_.available_updates") %></span>
<span id="num_new_updates" class="badge badge-important pull-right"></span>
<% if !@store_permissions["permission_granted"] %>
<span class="break pull-right"></span>
<small class="pull-right text-error">
<% if @store_permissions["message"].size > 30 %>
<a class="tooltipalert text-error" href="#"
onclick="return false;" title="<%= @store_permissions["message"] %>"><%= @store_permissions["message"][0..17] + "..." %></a>
<script type="text/javascript">
$('.tooltipalert').tooltip({
position: {
my: "center bottom-4",
at: "center top"
}
});
</script>
<% else %>
<%= @store_permissions["message"] %>
<% end %>
</small>
<% end %>
</div>
<div class="pannel-body">
<table class="table table-striped">
<tbody id="new_update_table">
</tbody>
</table>
</div>
</div>
<div style="height: 55px;">
<% if @store_permissions["permission_granted"] %>
<button id="update_btn" class="btn btn-primary pull-right" style="margin: 10px;"><i class="icon-inbox icon-white"></i> <%= t("update_manager_.system_update") %></button>
<% else %>
<a href="/<%= I18n.locale.to_s %>/admin/designs" class="pull-right">Please register here.</a>
<% end %>
</div>
</div>
<div id="update_status">
<div class="panel">
<div class="panel-heading">
<i class="icon-info-sign"></i>
<span class="break"></span>
<span class="panel-title"><%= t("update_manager_.update_status") %></span>
<% if !@store_permissions["permission_granted"] %>
<small class="pull-right text-error">
<% if @store_permissions["message"].size > 30 %>
<a class="tooltipalert text-error" href="#"
onclick="return false;" title="<%= @store_permissions["message"] %>"><%= @store_permissions["message"][0..17] + "..." %></a>
<script type="text/javascript">
$('.tooltipalert').tooltip({
position: {
my: "center bottom-4",
at: "center top"
}
});
</script>
<% else %>
<%= @store_permissions["message"] %>
<% end %>
</small>
<% end %>
</div>
<div class="pannel-body">
<div id="update_done" class="alert alert-success" style="font-size: 16px; text-align: center; margin: 0px;">
<i class="icon-ok-sign">&nbsp;&nbsp;&nbsp;&nbsp;<%= t("update_manager_.update_done") %></i>
</div>
<div id="update_failed" class="alert alert-error" style="font-size: 16px; text-align: center; margin: 0px;">
<i class="icon-remove">&nbsp;&nbsp;&nbsp;&nbsp;<%= t("update_manager_.update_faild") %></i>
</div>
<div id="update_progress">
<img src="/assets/spin.gif" width="50"><br/>
<span id="progress_msg"></span>
</div>
</div>
</div>
<div style="padding: 10px 0; height: 65px;">
<button id="chech_update_btn" class="btn btn-small btn-inverse pull-right"><i class="icon-refresh icon-white"></i> <%= t("update_manager_.check_update") %></button>
</div>
</div>
</div>
<div class="span6">
<div class="panel">
<div class="panel-heading">
<i class="icon-th-list"></i>
<span class="break"></span>
<span class="panel-title"><%= t("update_manager_.update_history") %></span>
<span id="num_updates" class="badge badge-success pull-right"></span>
</div>
<div class="pannel-body" id="update-history-body">
<table class="table table-striped">
<tbody id="update_history_table">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
var update_logs;
var update_log_display;
var new_updates;
function get_update_history(){
$.getJSON("<%= admin_site_get_update_history_path %>",function(data){
update_logs = data;
update_log_display = 0;
$("#num_updates").text(update_logs.length);
$("#update_history_table").html("");
show_update_history();
});
}
function show_update_history(){
for(var i = 0; i<30; i++){
var log = update_logs[update_log_display];
update_log_display++;
$("#update_history_table").append("<tr data-id='"+log[0]+"'><td width=30%'>"+log[1]+"</td><td width=50%'>"+log[2]+"</td><td width=20%'><button type='button' class='btn btn-primary' onclick='restore_orbit(this)'>restore</button></td></tr>");
if((update_log_display+1)>update_logs.length) break;
}
}
function check_updates(){
$("#progress_msg").html("<strong><%= t("update_manager_.checking_update") %></strong>");
$("#new_update_container").fadeOut(function(){
$("#update_done").fadeOut(function(){
$("#update_status").fadeIn(function(){
$("#update_progress").fadeIn();
$.getJSON("<%= admin_site_check_updates_path %>",function(data){
new_updates = data;
show_new_updates();
});
});
});
});
}
function show_new_updates(){
if(new_updates.length){
$("#num_new_updates").text(new_updates.length);
$.each(new_updates,function(){
$("#new_update_table").append("<tr><td>"+$(this)[0]+"</td><td>"+$(this)[1]+"</td></tr>");
});
$("#update_status").fadeOut(function(){$("#new_update_container").fadeIn();});
}else{
$("#update_progress").fadeOut(function(){$("#update_done").fadeIn();});
}
}
function check_module_updates(){
$("#progress_msg").html("<strong><%= t("update_manager_.updating_orbit") %></strong>");
$("#new_update_container").fadeOut(function(){
$("#update_done").fadeOut(function(){
$("#update_status").fadeIn(function(){
$("#update_progress").fadeIn();
$.get("<%= admin_site_bundle_install_path %>",function(result){
$("#update_progress").fadeOut(function(){$("#update_done").fadeIn();});
$("#update_status").fadeIn();
});
});
});
});
}
function restore_orbit(ele){
$("#update_done").hide()
$("#update_progress").show()
$("#progress_msg").html("<strong>restoring...</strong>");
$("#new_update_container").fadeOut(function(){
$("#update_status").fadeIn();
});
id = $(ele).parents('tr').data('id')
update_orbit('restore',id)
}
function update_orbit(type,id){
$.get("<%= admin_site_update_orbit_path %>",{type: type,id: id},function(result){
if (result=='finish'){
$("#progress_msg").html("<strong><%= t("update_manager_.restart_server") %></strong>");
$.get("<%= admin_site_restart_server_path %>").always(function(){
setTimeout(function(){window.location.href="<%= admin_site_update_manager_path %>"},5000)
});
}else if(result=='waiting'){
$("#progress_msg").html("<strong><%= t("update_manager_.restart_server") %></strong>");
setTimeout(function(){update_orbit('get_result')},1000)
}
});
}
$(document).ready(function(){
check_updates();
get_update_history();
// $("#module_update_btn").click(check_module_updates);
$("#chech_update_btn").click(check_updates);
$("#update_btn").click(function(){
$("#progress_msg").html("<strong><%= t("update_manager_.updating_orbit") %></strong>");
$("#new_update_container").fadeOut(function(){
$("#update_status").fadeIn();
});
update_orbit('update','')
});
$("#update-history-body").scroll(function () {
if((update_log_display+1)<update_logs.length){
var scroll_pos = ($("#update-history-body").scrollTop()+$("#update-history-body").height())/$("#update_history_table").height()*100;
if(scroll_pos>90){
show_update_history();
}
}
});
});
</script>