first commit for curation

This commit is contained in:
rulingcom committed 2025-05-07 22:25:46 +08:00
1 parent 88c18c28d4
commit f8177ac3c2
134 files changed
+561 -6300

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
= Bulletin
= CurationPost
This project rocks and uses MIT-LICENSE.
+1 -1
View File
@@ -8,7 +8,7 @@ require 'rdoc/task'
RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'Announcement'
rdoc.title = 'Curation'
rdoc.options << '--line-numbers'
rdoc.rdoc_files.include('README.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
-339
View File
@@ -1,339 +0,0 @@
# encoding: UTF-8
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "announcement/version"
require 'json'
require 'yaml'
require 'fileutils'
bundle_update_flag = ARGV[0]=='update' || ARGV[0]=='install'
if bundle_update_flag
env_pwd = ENV['PWD']
begin
require ::File.expand_path('app/helpers/bundler_helper.rb', env_pwd)
extend BundlerHelper
rescue LoadError
def bundler_with_clean_env(&block)
if block_given?
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env(&block)
else
Bundler.with_clean_env(&block)
end
end
end
end
if File.exist?("#{env_pwd}/app/models/google.rb")
FileUtils.rm("#{env_pwd}/app/models/google.rb", :force => true)
end
if Dir.exist?("#{env_pwd}/app/models/concern")
FileUtils.rm_r("#{env_pwd}/app/models/concern", :force => true)
end
app_path = File.expand_path(__dir__)
template_path = env_pwd + '/app/templates'
all_template = Dir.glob(template_path+'/*/')
puts 'editing files for sassc'
use_local_gemfile = File.exist?(env_pwd + '/.use_local_gemfile')
new_gemfile_text = File.read(app_path+'/temp_file/Gemfile')
old_gemfile_text = File.read(env_pwd+'/Gemfile')
check_texts = ['@import "../../bootstrap/variables";',".response-content {\n justify-self: auto;\n}\n"]
git_url = bundler_with_clean_env{%x[cd '#{env_pwd}' && git config --get remote.origin.url].split("\n")[0]}
git_remote = bundler_with_clean_env{%x[cd '#{env_pwd}' && git remote].split("\n")[0]}
if !(git_url.include?('//ruling.digital/git')) && !(File.exist?("#{env_pwd}/custom_git.txt"))
puts 'changing remote url'
bundler_with_clean_env{system("cd #{env_pwd} && git remote set-url #{git_remote} https://ruling.digital/git")}
end
default_announcement_widget_info = JSON.parse(File.read("#{app_path}/modules/announcement/info.json"))["widgets"].sort_by{|h| h["filename"].to_i} rescue []
all_template.each do |folder|
if !folder.include?('mobile')
begin
if folder.split('/')[-1] != 'mobile'
bundler_with_clean_env{%x[cp -rf #{app_path}/temp_file/templates/javascripts/* #{folder}assets/javascripts/plugin/.]}
unity_text = File.open(folder+'assets/stylesheets/template/base/_unity.scss','r:UTF-8') do |f|
f.read
end rescue ''
if unity_text.split(/\n/).join.strip.empty?
File.open(folder+'assets/stylesheets/template/base/_unity.scss', 'a') do |file|
file.puts "@charset \"utf-8\";\n\n@import \"variables\";\n\n// Title\n.unity-title {\n margin: 0.5em 0;\n line-height: 1.5;\n font-family: $main-font;\n font-size: $font-h1;\n\n .layout-footer & {\n margin-bottom: 10px;\n border-bottom: none;\n\n span {\n display: inline;\n margin-bottom: 0;\n border-bottom: none;\n }\n }\n}\n\n.status {\n font-family: $main-font;\n font-size: 0.75rem;\n}\n\n.status-top {\n background-color: $theme-color-second;\n}\n\n.status-hot {\n background-color: $theme-color-third;\n}\n\n.status-source {\n background-color: $theme-color-main;\n\n a {\n color: $theme-white;\n }\n}\n"
end
end
filename = folder+'assets/stylesheets/template/base/_variables.scss'
texts = File.open(filename,'r:UTF-8') do |f|
f.read
end.force_encoding('UTF-8').gsub(/(\r\n){2,}/, "\r\n")
s1 = texts.scan(/{|}/)
if s1.count % 2 != 0
i = texts.rindex(s1[-1])
texts[i] = ""
end
regex_pattern = /((?=^)[ \t\r\n]*)*\.response-content {\n justify-self: auto;\n}[\r\n]*|((?=^)[ \t\r\n]*)*\.response-content {\n position: static;\n}[\r\n]*|((?=^)[ \t\r\n]*)*\.response-content {\n position: relative;\n}[\r\n]*/m #|((?=^)[ \t\r\n]*)*\.response-content[^{]*{[^}]*@media[^{]*{[^{]*}[^{]*@media[^{]*{[^{]*}[^}]*}[^}]*}
if !texts.include? "$font-h1:"
texts = "$font-h1: 1.5rem;\n$font-h2: 1.35rem;\n$font-h3: 1.2rem;\n$font-h4: 1.1rem;\n$font-h5: 1rem;\n$font-h6: 0.9rem;\n\n" + texts
end
if !texts.include? "$main-font:"
texts = "$main-font: Arial, \"微軟正黑體\", \"Helvetica Neue\", Helvetica, sans-serif;\n" + texts
end
if !texts.include? "$theme-white"
texts = "$theme-white: #fff;\n" + texts
end
File.open(filename,'w') do |f|
f.write texts
end
tp_text = File.read(folder+'assets/stylesheets/template/template.scss').force_encoding('UTF-8') rescue ''
tp_last_text = tp_text
tp_text.scan(/@import.*http.*;/).each do |pat|
if pat.scan(/@import\W+url/).count==0
pat1 = pat.sub(/@import\W/,"@import url(")
pat1 = pat1.sub(/;/,");")
tp_last_text = tp_last_text.sub(pat,pat1)
end
end
if tp_last_text != tp_text
File.open(folder+'assets/stylesheets/template/template.scss','w') do |f|
f.write tp_last_text
end
end
texts = texts.gsub(/\n{2,}/,"\n")
auto_save_array = texts.scan(regex_pattern)
if auto_save_array.count > 1
auto_save_text = auto_save_array.join('')
File.open(folder+'assets/stylesheets/template/base/_autobackup.bak', 'a') do |file|
file.puts auto_save_text
end
texts = texts.gsub(regex_pattern,"")
File.open(filename, 'w') do |file|
file.write (texts)
end
end
check_texts.each do |check_text|
if !texts.include?(check_text)
puts "editing #{folder}assets/stylesheets/template/base/_variables.scss"
texts = texts + "\n" + check_text
File.open(filename, 'w') do |file|
file.write(texts)
end
end
end
end
rescue => e
puts "not found #{folder}assets/stylesheets/template/base/_variables.scss"
end
begin
puts "updating announcement show page"
bundler_with_clean_env{%x[cp -f #{app_path}/modules/announcement/show.html.erb #{folder}modules/announcement/show.html.erb]}
rescue
puts "There has some error in updating announcement show page"
end
info_json_file = "#{folder}modules/announcement/info.json"
if File.exist?(info_json_file)
begin
file_text = File.read(info_json_file) rescue ""
encode_file_text = file_text.encode("UTF-8", "UTF-8", invalid: :replace, replace: "???")
next if (encode_file_text.include?("???") rescue true)
info = JSON.parse(encode_file_text) rescue {}
flag = (info.count != 0 rescue false)
if flag
puts "Checking announcement widgets"
widget_info = info["widgets"].sort_by{|h| h["filename"].to_i} rescue []
update_flag = false
last_index = widget_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
if !last_index.nil?
idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
default_announcement_widget_info.each do |h|
name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
widget_info_index = (widget_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
if (widget_info_index == -1 || widget_info_index.nil?)
update_flag = true
copy_h = h.dup
h.delete("force_cover")
last_index = last_index + 1
copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
copy_h["name"].keys.each do |locale|
copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
end
widget_info << copy_h
bundler_with_clean_env{%x[cp -f #{app_path}/modules/announcement/_#{h["filename"]}.html.erb #{folder}modules/announcement/_#{copy_h["filename"]}.html.erb]}
elsif h["force_cover"] == "true"
bundler_with_clean_env{%x[cp -f #{app_path}/modules/announcement/_#{h["filename"]}.html.erb #{folder}modules/announcement/_#{widget_info[widget_info_index]["filename"]}.html.erb]}
end
end
if update_flag
info["widgets"] = widget_info
puts "Writing json #{info["widgets"].count} in #{info_json_file}"
begin
info_json = JSON.pretty_generate(info).gsub(":[",":[\n").gsub(":{",":{\n")
rescue
info_json = info.to_s.gsub("=>",": \n")
end
File.open(info_json_file,"w+"){|f| f.write(info_json)}
end
bundler_with_clean_env{%x[cp -rn #{app_path}/modules/announcement/thumbs/* #{folder}modules/announcement/thumbs/.]}
end
end
rescue => e
puts e
puts "There has some error when checking announcement widgets"
end
end
end
end
if !use_local_gemfile && old_gemfile_text != new_gemfile_text
unicorn_rails = %x[which unicorn_rails].sub("\n",'')
puts 'updating gemfile'
if Dir["#{env_pwd}/config/secrets.yml"].length==0
r = open("#{env_pwd}/config/environment.rb",'r'){|f| f.read()}
secret_key = r.scan(/Orbit::Application\.config\.secret_key_base = '(.*)'/).flatten[0] rescue nil
if !secret_key.nil?
open("#{env_pwd}/config/secrets.yml",'w+') do |f|
c = {"production"=> {"secret_key_base"=> secret_key},"development"=> {"secret_key_base"=> secret_key}}
c = c.to_yaml.sub("---\n",'')
f.write(c)
end
end
end
bundler_with_clean_env{%x[cp -f '#{env_pwd}'/Gemfile '#{env_pwd}'/Gemfile.bak123]}
bundler_with_clean_env{%x[cp -f '#{app_path}'/temp_file/Gemfile '#{env_pwd}'/Gemfile]}
check_version = %x[cd #{env_pwd} && git rev-list `git rev-parse --abbrev-ref HEAD` | grep 2f23511469505bd114df2c863a477a8730bcdefa]
if check_version.strip != '' #update mongoid version
command4 = ""
puts 'mongoid has been updated!'
else
command4 = ";mv #{env_pwd}/app/controllers/sessions_controller.rb #{env_pwd}/tmp/sessions_controller_backup.rb;cp -rf #{app_path}/temp_file/app #{env_pwd};cp -rf #{app_path}/temp_file/config #{env_pwd};rm #{env_pwd}/app/models/google.rb"
end
log_development = File.mtime(env_pwd+'/log/development.log').strftime('%Y%m%d%H%M').to_i rescue 0
log_production = File.mtime(env_pwd+'/log/production.log').strftime('%Y%m%d%H%M').to_i rescue 0
if log_development > log_production
mode = 'development'
else
mode = 'production'
end
files = Dir[env_pwd+'/Gemfile.lock']
dir_name = env_pwd.split('/')[-1]
watch_dog = %x[screen -ls auto_reopen_#{dir_name}]
if watch_dog.scan("auto_reopen_#{dir_name}").count != 0
bundler_with_clean_env{%x[screen -ls | grep auto_reopen_#{dir_name} | cut -d. -f1 | awk '{print $1}' | xargs kill]}
end
if %x[ruby -v].scan(/\d\.\d\.\d/)[0] == '2.1.3'
install_cmd = 'rvm install 2.1.10 && rvm use default 2.1.10;'
use_cmd = 'source ~/.rvm/scripts/rvm && rvm use 2.1.10 --default;'
else
install_cmd = ''
use_cmd = ''
end
#if files.count ==0
# command1 = "gem install bundler -v 1.17.3 ; bundle update --all"
#else
if RUBY_VERSION.to_f==2.1
command1 = "gem install bundler -v 1.17.3 ; bundle update --all"
#else
#command1 = "gem install bundler -v 2.3.3 ; bundle update --all"
end
#end
filedata = File.read(env_pwd+"/built_in_extensions.rb")
exist_str = "gem 'patchfile', git: 'http://gitlab.tp.rulingcom.com/chiu/patch_file.git'"
if filedata.include? exist_str
puts "patchfile exist"
else
file = env_pwd+"/built_in_extensions.rb"
open(file, 'a') { |f|
f.puts exist_str
}
end
all_command = "#{install_cmd} #{command1} #{command4} "
watch_dog_cmd = "watch -n 30 \'unset UNICORN_FD && bundle exec #{unicorn_rails} -c config/unicorn.rb -D -E #{mode}\'"
#file = File.new(File.join(env_pwd,'bundle_update_background.sh'),"w")
#file.write(all_command)
#file.chmod(0755)
#file.close
restart_cmd = "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}"
a = Thread.start do
bundler_with_clean_env do
puts env_pwd
puts mode
exec("cd #{env_pwd} && env -i HOME=\"$HOME\" bash -l -c \"#{all_command}\" ;screen -d -m -S auto_reopen_#{dir_name} bash -c \"#{use_cmd} #{restart_cmd};#{watch_dog_cmd}\" ")
end
end
now_priority = Thread.current.priority.to_i
system('sleep 2')
a.priority = now_priority + 2
a.run
#Thread.exit
else
dir_name = env_pwd.split('/')[-1]
watch_dog = %x[screen -ls auto_reopen_#{dir_name}]
if watch_dog.scan("auto_reopen_#{dir_name}").count != 0
bundler_with_clean_env{%x[screen -ls | grep auto_reopen_#{dir_name} | cut -d. -f1 | awk '{print $1}' | xargs kill]}
end
#system("cp -rf #{app_path}/temp_file/app #{env_pwd}")
end
c = open("#{env_pwd}/config/mongoid.yml",'r'){|f| f.read}
if c.scan(/^[ \t]*sessions\:/).length != 0
c = c.gsub(/^([ \t]*)sessions\:/,'\1clients:')
r = YAML.load(c)
r.each do |mode,v1|
v1.each do |clients,d|
d.each do |k,v|
next if v.class != Hash
if !v["username"].nil?
if v["options"].nil?
v["options"] = {}
end
v["options"]["user"] = v["username"]
v.delete "username"
end
if !v["password"].nil?
if v["options"].nil?
v["options"] = {}
end
v["options"]["password"] = v["password"]
v.delete "password"
end
if !v["options"].nil? && !v["options"]["pool_size"].nil?
v["options"]["max_pool_size"] = v["options"]["pool_size"]
v["options"].delete "pool_size"
end
if !v["options"].nil? && v["options"]["read"].class == String
v["options"]["read"] = {"mode"=> v["options"]["read"]}
end
end
end
end
c = YAML.dump(r).sub("---\n",'')
open("#{env_pwd}/config/mongoid.yml",'w+'){|f| f.write(c)}
end
if !File.exist?("#{env_pwd}/.carrierwave_upgraded")
upgrading = File.exist?("#{env_pwd}/.carrierwave_upgrading")
File.open("#{env_pwd}/.carrierwave_upgrading", "w") {}
uploaders = Dir.chdir(env_pwd){ Dir.glob("app/uploaders/*") }
uploaders.each do |uploader|
if upgrading
bundler_with_clean_env{%x[cd #{env_pwd} && git checkout -- #{uploader}]}
end
uploader_contents = File.read("#{env_pwd}/#{uploader}")
uploader_contents.gsub!(/^[ \t]*require[ \t]+['"]carrierwave\/processing\/mime_types['"][ \t]*$/, '')
uploader_contents.gsub!(/^[ \t]*include[ \t]+CarrierWave::MimeTypes[ \t]*$/, '')
File.open("#{env_pwd}/#{uploader}", "w"){|f| f.write(uploader_contents)}
end
File.open("#{env_pwd}/.carrierwave_upgraded", "w") {}
end
end
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "announcement"
s.version = Announcement::VERSION
s.authors = ["RulingDigital"]
s.email = ["orbit@rulingcom.com"]
s.homepage = "http://www.rulingcom.com"
s.summary = "Announcements for Orbit"
s.description = "Announcements for Orbit"
s.license = "MIT"
s.metadata = {
"_require" => "#{File.expand_path("../app/models/announcement_setting", __FILE__)}",
"global_hash" => "{enable_manually_sort: (AnnouncementSetting.first.enable_manually_sort rescue false),enable_annc_dept: (AnnouncementSetting.first.enable_annc_dept rescue false), annc_depts_translations: (AnnouncementSetting.first.annc_depts_translations rescue {})}"
}
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rufus-scheduler", "~> 3.6.0"
s.add_dependency "mimemagic" , "0.3.9"
end
@@ -1,67 +1,67 @@
# encoding: utf-8
require 'rubyXL'
class Admin::AnnouncementsController < OrbitAdminController
include Admin::AnnouncementsHelper
class Admin::CurationsController < OrbitAdminController
include Admin::CurationsHelper
before_action ->(module_app = @app_title) { set_variables module_app }
before_action :set_bulletin, only: [:edit, :destroy, :comment]
before_action :load_access_level, :load_settings
before_action :set_module_pages, only: [:edit,:new]
def set_module_pages
@module_pages = Page.where(:module => 'announcement').collect{|p| [p.name,p.id] }
@module_pages = Page.where(:module => 'curation').collect{|p| [p.name,p.id] }
end
def initialize
super
@app_title = "announcement"
@app_title = "curation"
end
def update_sort
ids = params[:ids]
ids.each_with_index do |id,i|
Bulletin.where(id: id).update(sort_number: i)
CurationPost.where(id: id).update(sort_number: i)
end
AnnsCache.all.delete
CurationCache.all.delete
edit_sort
render 'update_sort',layout: false
end
def update_sort_setting
setting = @announcement_setting
setting.update_attributes(settings_params)
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['announcement'][:enable_manually_sort] = setting.enable_manually_sort
OrbitHelper::SharedHash['curation'][:enable_manually_sort] = setting.enable_manually_sort
end
redirect_to edit_sort_admin_announcement_path
redirect_to edit_sort_admin_curation_path
end
def edit_sort
@setting = AnnouncementSetting.first
@announcements = Bulletin.where(is_top: true).order_by({is_top: -1,sort_number: 1,postdate: -1, _id: -1})
@table_fields = ['announcement.table.sort_number','announcement.table.title','announcement.default_widget.postdate']
@setting = CurationSetting.first
@announcements = CurationPost.where(is_top: true).order_by({is_top: -1,sort_number: 1,postdate: -1, _id: -1})
@table_fields = ['curation.table.sort_number','curation.table.title','curation.default_widget.postdate']
end
def comment_hidden
b = BulletinComment.find(params[:id]) rescue nil
b = CurationPostComment.find(params[:id]) rescue nil
if !b.nil?
b.is_hidden = !b.is_hidden
b.save
@table_feed_fields = ["announcement.time", "announcement.comment", "announcement.account","ip","is_hidden"]
@comments = b.bulletin.bulletin_comments.reverse rescue []
@table_feed_fields = ["curation.time", "curation.comment", "curation.account","ip","is_hidden"]
@comments = b.curation_post.curation_post_comments.reverse rescue []
render partial: 'comment'
end
end
def comment
@table_feed_fields = ["announcement.time", "announcement.comment", "announcement.account","ip","is_hidden"]
@comments = @bulletin.bulletin_comments.reverse rescue []
@table_feed_fields = ["curation.time", "curation.comment", "curation.account","ip","is_hidden"]
@comments = @bulletin.curation_post_comments.reverse rescue []
end
def index
Bulletin.remove_expired_status
CurationPost.remove_expired_status
@tags = @module_app.tags
@table_fields = [:status, :category, :title, :start_date, :end_date, "announcement.comment", :last_modified]
setting = AnnouncementSetting.first
@table_fields = [:status, :category, :title, :start_date, :end_date, "curation.comment", :last_modified]
setting = CurationSetting.first
@annc_depts = []
@enable_annc_dept = false
if (setting.enable_annc_dept rescue false)
@table_fields.insert(1, "announcement.annc_dept")
@table_fields.insert(1, "curation.annc_dept")
@annc_depts = setting.annc_depts
@enable_annc_dept = true
end
@@ -71,55 +71,55 @@ class Admin::AnnouncementsController < OrbitAdminController
if current_user_is_sub_manager
@categories = current_user.approved_categories.select{|c| c.module_app_id == @module_app.id} rescue []
@filter_fields = filter_fields(@categories, @tags)
@bulletins = Bulletin.where(:create_user_id=>current_user.id,:is_preview.in=>[false,nil])
@bulletins = CurationPost.where(:create_user_id=>current_user.id,:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
.with_status(filters("status"))
else
@bulletins = Bulletin.where(:uid=>nil)
@bulletins = CurationPost.where(:uid=>nil)
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
end
else
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
@bulletins = Bulletin.where(:is_preview.in=>[false,nil])
@bulletins = CurationPost.where(:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
.with_status(filters("status"))
end
@bulletins = search_data(@bulletins,[:title]).page(params[:page]).per(10)
if request.xhr?
render :partial => "index"
end
end
def get_all_anncs_without_subannc
Bulletin.remove_expired_status
CurationPost.remove_expired_status
@tags = @module_app.tags
@table_fields = [:category, :title, :start_date]
@current_user = current_user
if AnnouncementSetting.first.is_display_edit_only && !current_user.is_admin? && !current_user.is_manager?(@module_app)
if CurationSetting.first.is_display_edit_only && !current_user.is_admin? && !current_user.is_manager?(@module_app)
current_user_is_sub_manager = !current_user.is_manager?(@module_app) && (current_user.is_sub_manager?(@module_app) || current_user.is_sub_manager_with_role?(@module_app)) rescue false
if current_user_is_sub_manager
@categories = current_user.approved_categories.select{|c| c.module_app_id == @module_app.id} rescue []
@filter_fields = filter_fields(@categories, @tags)
@bulletins = Bulletin.where(:create_user_id=>current_user.id,:title.ne => "",:is_preview.in=>[false,nil])
@bulletins = CurationPost.where(:create_user_id=>current_user.id,:title.ne => "",:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
.with_status(filters("status"))
else
@bulletins = Bulletin.where(:uid=>nil)
@bulletins = CurationPost.where(:uid=>nil)
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
end
else
@categories = @module_app.categories.enabled
@filter_fields = filter_fields(@categories, @tags)
@bulletins = Bulletin.where(:title.ne => "",:is_preview.in=>[false,nil])
@bulletins = CurationPost.where(:title.ne => "",:is_preview.in=>[false,nil])
.order_by(sort)
.with_categories(filters("category"))
.with_tags(filters("tag"))
@@ -133,17 +133,13 @@ class Admin::AnnouncementsController < OrbitAdminController
render :layout => false
end
end
def feed
@table_feed_fields = ["announcement.feed_name",:tags , :category , "announcement.rssfeed", "announcement.jsonfeed"]
@feeds = BulletinFeed.all.asc(:created_at)
end
def generate_iframe_url
iframe_params = params.require(:iframe).permit!
uids = iframe_params['member_ids'].to_a.map{|m_id| MemberProfile.find(m_id).uid rescue nil}.select{|uid| !uid.nil?}
url_params = iframe_params.except(:member_ids)
url_params['uids'] = uids if uids != []
render :plain => '/xhr/panel/announcement/widget/sync_data?'+url_params.to_param
render :plain => '/xhr/panel/curation/widget/sync_data?'+url_params.to_param
end
def settings
@setting = @announcement_setting
@@ -164,16 +160,16 @@ class Admin::AnnouncementsController < OrbitAdminController
def excel_format
respond_to do |format|
format.xlsx {
response.headers['Content-Disposition'] = 'attachment; filename="announcement_import_format.xlsx"'
response.headers['Content-Disposition'] = 'attachment; filename="curation_import_format.xlsx"'
}
end
end
def export_excel
@thread = Multithread.where(:key=>'export_announcements').first
@thread = Multithread.where(:key=>'export_curations').first
update_flag = true
if @thread.nil?
@thread = Multithread.create(:key=>'export_announcements',:status=>{:status=>'Processing'})
@thread = Multithread.create(:key=>'export_curations',:status=>{:status=>'Processing'})
else
update_flag = false if @thread.status[:status] == 'Processing' && @thread.respond_to?(:updated_at) && (@thread.updated_at > DateTime.now - 1.minute rescue false)
if update_flag
@@ -187,11 +183,11 @@ class Admin::AnnouncementsController < OrbitAdminController
end
Thread.new do
begin
@announcements = Bulletin.where(:is_preview.ne=>true).desc(:id)
last_updated = [Bulletin.max(:updated_at).to_i, AnnouncementSetting.max(:updated_at).to_i].max
filename = "public/announcement_export_#{last_updated}.xlsx"
@announcements = CurationPost.where(:is_preview.ne=>true).desc(:id)
last_updated = [CurationPost.max(:updated_at).to_i, CurationSetting.max(:updated_at).to_i].max
filename = "public/curation_export_#{last_updated}.xlsx"
if File.exist?(filename)
@thread.update(:status=>{:status=>'finish','finish_percent'=>100,'info'=>I18n.t('announcement.read_from_cache')})
@thread.update(:status=>{:status=>'finish','finish_percent'=>100,'info'=>I18n.t('curation.read_from_cache')})
else
excel_contents = render_to_string( handlers: [:axlsx], formats: [:xlsx] ,partial: 'export_excel.xlsx' )
File.open(filename, 'w') do |f|
@@ -199,7 +195,7 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
@thread.status[:file] = filename
@thread.status[:filename] = "announcement_export_#{DateTime.now.in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y_%m_%d_%H%M')}.xlsx"
@thread.status[:filename] = "curation_export_#{DateTime.now.in_time_zone(Time.zone.utc_offset / 3600).strftime('%Y_%m_%d_%H%M')}.xlsx"
@thread.save
rescue => e
@thread.status[:status] = 'error'
@@ -209,7 +205,7 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
end
redirect_to admin_announcement_import_path(:thread_id=>@thread.id.to_s)
# redirect_to admin_curation_import_path(:thread_id=>@thread.id.to_s)
end
def render_404
render :file => "#{Rails.root}/app/views/errors/404.html", :layout => false, :status => 404, :formats => [:html]
@@ -222,160 +218,42 @@ class Admin::AnnouncementsController < OrbitAdminController
render_404
end
end
def import_from_xml
download_tmp_xml params["import_xml"]
import_from_tmp_xml File.read(File.join(Rails.root, "tmp", "ann_cc_ntu.xml"))
redirect_to admin_announcements_path
end
def import_from_wp
import_from_wordpress params["import_xml"].tempfile
redirect_to admin_announcements_path
end
def importanns
workbook = RubyXL::Parser.parse(params["import_file"].tempfile)
raw_categories = @module_app.categories.asc(:created_at).to_a.map.with_index{|v, k| [k.to_s,v]}.to_h
raw_tags = @module_app.tags.asc(:created_at).to_a.map.with_index{|v, k| [k.to_s,v]}.to_h
categories = raw_categories.clone
tags = raw_tags.clone
sheet = workbook[0]
if sheet.count <= 503
sheet.each_with_index do |row, i|
if i == 2
begin
cats_text = row.cells[0].value.to_s.sub(/(^|,)\s*Example\s*:.*$/,'')
cats_keys = cats_text.split('->').map{|s| s.split(',')[-1].strip}[0...-1]
cats_values = cats_text.split('->')[1..-1].to_a.map{|s| s.strip.sub(/,\s*\d+$/,'')}
categories_relations = cats_keys.zip(cats_values).to_h
rescue => e
categories_relations = {}
end
begin
tags_text = row.cells[1].value.to_s.sub(/(^|,)\s*Example\s*:.*$/,'')
tags_keys = tags_text.split('->').map{|s| s.split(',')[-1].strip}[0...-1]
tags_values = tags_text.split('->')[1..-1].to_a.map{|s| s.strip.sub(/,\s*\d+$/,'')}
tags_relations = tags_keys.zip(tags_values).to_h
rescue => e
tags_relations = {}
end
if categories_relations.present?
categories = categories_relations.map do |k, v|
tmp = raw_categories[k]
if tmp && tmp.title.strip == v
[k, tmp]
else
tmp = raw_categories.detect{|kk, vv| vv.title.strip == v}
if tmp.nil?
tmp = @module_app.categories.create(:title_translations=> localize_data(v))
end
[k, tmp]
end
end.to_h
end
if tags_relations.present?
tags = tags_relations.map do |k, v|
tmp = raw_tags[k]
if tmp && tmp.name.strip == v
[k, tmp]
else
tmp = raw_tags.detect{|kk, vv| vv.name.strip == v}
if tmp.nil?
tmp = @module_app.tags.create(:name_translations=> localize_data(v))
end
[k, tmp]
end
end.to_h
end
end
next if i < 3
v = row.cells.first.value rescue nil
next if v.blank?
import_this_announcement(row, categories, tags)
end
redirect_to admin_announcements_path
else
redirect_to admin_announcements_path(:error => "1")
end
end
def createsettings
setting = AnnouncementSetting.new(settings_params)
setting = CurationSetting.new(settings_params)
setting.save
redirect_to admin_announcement_settings_path
redirect_to admin_curation_settings_path
end
def updatesettings
setting = @announcement_setting
ids = params['announcement_setting']['anns_status_settings'].to_a.collect do |i,v|
ids = params['curation_setting']['curation_status_settings'].to_a.collect do |i,v|
v['_id']
end.compact
AnnsStatusSetting.where(:id.nin=>ids).destroy
CurationStatusSetting.where(:id.nin=>ids).destroy
setting.update_attributes(settings_params)
setting.save
redirect_to admin_announcement_settings_path
end
def feedform
if params[:type] == "new"
@announcement_feed = BulletinFeed.new(id: nil)
render :partial => "feed_form"
else params[:type] == "edit"
@announcement_feed = BulletinFeed.find(params[:id])
render :partial => "edit_feed_form"
end
end
def createfeed
announcement_feed = BulletinFeed.new(feed_params)
announcement_feed.save
#BulletinFeed.create_feed_cache(nil,announcement_feed)
feeds = BulletinFeed.all.asc(:created_at)
render :partial => "feed", :collection => feeds
end
def updatefeed
ann_feed = BulletinFeed.find(params[:id])
ann_feed.update_attributes(feed_params)
ann_feed.save
#BulletinFeed.create_feed_cache(nil,ann_feed)
feeds = BulletinFeed.all.asc(:created_at)
render :partial => "feed", :collection => feeds
end
def deletefeed
ann_feed = BulletinFeed.find(params[:id])
ann_feed.destroy
feeds = BulletinFeed.all.asc(:created_at)
render :partial => "feed", :collection => feeds
redirect_to admin_curation_settings_path
end
def new
@tags = @module_app.tags
@statuses = []
@bulletin = Bulletin.new
@bulletin = CurationPost.new
@bulletin.email_sentdate = Time.now
@reach_limit = @bulletin.check_status_limit(current_user,true)
if defined? Calendar
categories = user_authenticated_categories rescue ['all']
if categories.first == "all"
@calendar_categories = CalendarType.all
else
@calendar_categories = CalendarType.where(:category_id.in => categories) rescue []
end
end
end
def create
bps = bulletin_params
bulletin = Bulletin.new(bps)
if !bps['bulletin_links_attributes'].nil?
bps['bulletin_links_attributes'].each do |idx,link|
bps['bulletin_links_attributes'].delete(idx.to_s) if link['url'].blank?
bulletin = CurationPost.new(bps)
if !bps['curation_post_links_attributes'].nil?
bps['curation_post_links_attributes'].each do |idx,link|
bps['curation_post_links_attributes'].delete(idx.to_s) if link['url'].blank?
end
end
if((!AnnouncementSetting.first.only_manager_can_edit_status) || (AnnouncementSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
if bps[:is_top] == "1" && !AnnouncementSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
if((!CurationSetting.first.only_manager_can_edit_status) || (CurationSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
if bps[:is_top] == "1" && !CurationSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
bps[:is_top] = "0"
bps[:top_end_date] = nil
end
@@ -385,12 +263,9 @@ class Admin::AnnouncementsController < OrbitAdminController
bps[:is_hidden] = false
end
if !defined?(Calendar).nil?
bps = update_calendar(bps,bulletin)
end
bulletin.create_user_id = current_user.id
bulletin.update_user_id = current_user.id
if AnnouncementSetting.is_pro?
if CurationSetting.is_pro?
if user_can_approve?
bulletin.approved = true
else
@@ -399,7 +274,7 @@ class Admin::AnnouncementsController < OrbitAdminController
else
bulletin.approved = true
end
bulletin.save
build_email(bulletin,I18n.locale)
Thread.new do
@@ -411,7 +286,7 @@ class Admin::AnnouncementsController < OrbitAdminController
def approve_bulletin
id = params[:id]
bulletin = Bulletin.find(id)
bulletin = CurationPost.find(id)
if params["approved"] == "true"
bulletin.approved = true
bulletin.rejected = false
@@ -424,7 +299,7 @@ class Admin::AnnouncementsController < OrbitAdminController
end
bulletin.save
#BulletinFeed.create_feed_cache(bulletin)
redirect_to admin_announcements_path
redirect_to admin_curation_path
end
def edit
@@ -432,14 +307,6 @@ class Admin::AnnouncementsController < OrbitAdminController
@reach_limit = @bulletin.check_status_limit(current_user,true)
@tags = @module_app.tags
@categories = @module_app.categories.enabled
if defined? Calendar
categories = user_authenticated_categories rescue ['all']
if categories.first == "all"
@calendar_categories = CalendarType.all
else
@calendar_categories = CalendarType.where(:category_id.in => categories) rescue []
end
end
@statuses = []
@bulletin.email_sentdate = Time.now if @bulletin.email_sent == false
else
@@ -449,8 +316,8 @@ class Admin::AnnouncementsController < OrbitAdminController
def update
uid = params[:id].split('-').last
bulletin = Bulletin.find_by(:uid=>uid)
Bulletin.where(:copy_id=>bulletin.id.to_s).destroy
bulletin = CurationPost.find_by(:uid=>uid)
CurationPost.where(:copy_id=>bulletin.id.to_s).destroy
bulletin.is_edit = true
bulletin.save
set_approved = bulletin.is_preview
@@ -460,13 +327,13 @@ class Admin::AnnouncementsController < OrbitAdminController
bps[:tags] = bps[:tags].blank? ? [] : bps[:tags]
bps[:email_member_ids] = bps[:email_member_ids].blank? ? [] : bps[:email_member_ids]
if !bps['bulletin_links_attributes'].nil?
bps['bulletin_links_attributes'].each do |idx,link|
bps['bulletin_links_attributes'].delete(idx.to_s) if link['url'].blank?
if !bps['curation_post_links_attributes'].nil?
bps['curation_post_links_attributes'].each do |idx,link|
bps['curation_post_links_attributes'].delete(idx.to_s) if link['url'].blank?
end
end
if((!AnnouncementSetting.first.only_manager_can_edit_status) || (AnnouncementSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
if bps[:is_top] == "1" && !AnnouncementSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
if((!CurationSetting.first.only_manager_can_edit_status) || (CurationSetting.first.only_manager_can_edit_status && (@current_user.is_admin? || @current_user.is_manager?(@module_app))) )
if bps[:is_top] == "1" && !CurationSetting.check_limit_for_user(bulletin.create_user_id, bulletin.id)
bps[:is_top] = "0"
bps[:top_end_date] = nil
end
@@ -494,38 +361,32 @@ class Admin::AnnouncementsController < OrbitAdminController
bulletin.notify_feed("update")
end
#BulletinFeed.create_feed_cache(bulletin)
now_bulletin_page = Bulletin.where(:title.ne => "",:is_preview.in=>[false,nil])
now_bulletin_page = CurationPost.where(:title.ne => "",:is_preview.in=>[false,nil])
.order_by(sort).map(&:id).map.with_index.select{|v,i| v==bulletin.id}[0][1] rescue nil
now_bulletin_page = now_bulletin_page.nil? ? 0 : ((now_bulletin_page+1).to_f/10).ceil
redirect_to admin_announcements_path(:page=>now_bulletin_page)
redirect_to admin_curations_path(:page=>now_bulletin_page)
end
def destroy
@bulletin.destroy
Thread.new do
@bulletin.notify_feed("destroy")
end
redirect_to admin_announcements_path
redirect_to admin_curations_path
end
def delete
if params[:ids]
Bulletin.any_in(:uid => params[:ids]).destroy_all
Thread.new do
Bulletin.notify_feed_delete(params[:ids])
end
CurationPost.any_in(:uid => params[:ids]).destroy_all
end
if request.xhr?
render :body => nil, :status => 204
else
redirect_to admin_announcements_path
redirect_to admin_curations_path
end
end
def preview
if params['preview_type'].eql?('edit')
bulletin_data = bulletin_params
org_bulletin = Bulletin.find(params['bulletin_id'])
org_bulletin = CurationPost.find(params['bulletin_id'])
bulletin = org_bulletin.clone
bulletin.generate_uid
bulletin.bulletin_files = []
@@ -534,16 +395,16 @@ class Admin::AnnouncementsController < OrbitAdminController
bulletin.image = org_bulletin.image
end
if !bulletin_data['bulletin_files_attributes'].blank?
bulletin_data['bulletin_files_attributes'].each do |key, bulletin_file|
if !bulletin_data['curation_post_files_attributes'].blank?
bulletin_data['curation_post_files_attributes'].each do |key, bulletin_file|
next if !bulletin_file['_destroy'].blank?
file = nil
if bulletin_file['id'].blank?
file = BulletinFile.new(bulletin_file)
file = CurationPostFile.new(bulletin_file)
file.bulletin_id = bulletin.id
file.save
else
org_file = BulletinFile.find(bulletin_file['id'])
org_file = CurationPostFile.find(bulletin_file['id'])
file = org_file.clone
file.bulletin_id = bulletin.id
file.file = org_file.file
@@ -557,15 +418,15 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
if !bulletin_data['bulletin_links_attributes'].blank?
bulletin_data['bulletin_links_attributes'].each do |key, bulletin_link|
if !bulletin_data['curation_post_links_attributes'].blank?
bulletin_data['curation_post_links_attributes'].each do |key, bulletin_link|
next if !bulletin_link['_destroy'].blank?
if bulletin_link['id'].blank?
link = BulletinLink.new(bulletin_link)
link = CurationPostLink.new(bulletin_link)
link.bulletin_id = bulletin.id
else
link = BulletinLink.find(bulletin_link['id']).clone
link = CurationPostLink.find(bulletin_link['id']).clone
link.bulletin_id = bulletin.id
bulletin_link.delete('id')
bulletin_link.delete('_destroy')
@@ -577,33 +438,33 @@ class Admin::AnnouncementsController < OrbitAdminController
end
end
bulletin_data.delete('bulletin_files_attributes')
bulletin_data.delete('bulletin_links_attributes')
bulletin_data.delete('curation_post_files_attributes')
bulletin_data.delete('curation_post_links_attributes')
bulletin.update_attributes(bulletin_data)
bulletin.copy_id = params['bulletin_id']
else
bulletin = Bulletin.new(bulletin_params)
bulletin = CurationPost.new(bulletin_params)
end
bulletin.is_preview = true
bulletin.save
#BulletinFeed.create_feed_cache(bulletin)
render :plain=>page_for_bulletin(bulletin) + "?preview=true"
end
def get_preview_action
bulletin = Bulletin.find_by(:uid=>params['uid'])
bulletin = CurationPost.find_by(:uid=>params['uid'])
is_not_edit = (!bulletin.is_edit)
org_bulletin = bulletin.get_org_model
Bulletin.where(:copy_id=>org_bulletin.id.to_s).destroy
CurationPost.where(:copy_id=>org_bulletin.id.to_s).destroy
if is_not_edit
bulletin.destroy
render :json=> {:success=>true,:action=>"close"}
else
render :json=> {:success=>true,:action=>"redirect",:path=>edit_admin_announcement_path(:id=>org_bulletin.id)}
render :json=> {:success=>true,:action=>"redirect",:path=>edit_admin_curation_path(:id=>org_bulletin.id)}
end
end
def destroy_preview
bulletin = Bulletin.find_by(:uid=>params['uid'])
bulletin = CurationPost.find_by(:uid=>params['uid'])
if bulletin.is_preview
bulletin.destroy
end
@@ -624,7 +485,7 @@ class Admin::AnnouncementsController < OrbitAdminController
is_sent = !params[:resend_mail].eql?("true") if !params[:resend_mail].blank?
doc = Nokogiri::HTML(bulletin.title_translations[locale])
title = doc.text.empty? ? 'no content' : doc.text
bulletin.email.update_attributes(
:create_user=>current_user,
:mail_sentdate=>bulletin.email_sentdate,
@@ -649,59 +510,22 @@ class Admin::AnnouncementsController < OrbitAdminController
private
def load_settings
@announcement_setting = AnnouncementSetting.first rescue nil
@announcement_setting = CurationSetting.first rescue nil
if @announcement_setting.nil?
@announcement_setting = AnnouncementSetting.create
@announcement_setting = CurationSetting.create
end
end
def set_bulletin
@bulletin = Bulletin.find(params[:id])
@bulletin = CurationPost.find(params[:id])
end
def bulletin_params
params[:bulletin][:email_sent] = params[:bulletin][:email_sent].nil? ? 0 : params[:bulletin][:email_sent]
params.require(:bulletin).permit!
end
def feed_params
feed_params = params.require(:bulletin_feed).permit!
if feed_params[:tag_ids].nil?
feed_params[:tag_ids] = []
end
if feed_params[:category_ids].nil?
feed_params[:category_ids] = []
end
feed_params
params[:curation_post][:email_sent] = params[:curation_post][:email_sent].nil? ? 0 : params[:curation_post][:email_sent]
params.require(:curation_post).permit!
end
def settings_params
params.require(:announcement_setting).permit!
end
def update_calendar(bps,bulletin)
bps = bps.to_h.with_indifferent_access
if bps[:add_to_calendar] == '0' && !bps[:event_id].blank?
Event.find(bps[:event_id]).destroy rescue nil
bps[:event_id] = nil
elsif bps[:add_to_calendar] == '1'
event = Event.find(bps[:event_id]) rescue Event.new(create_user_id: current_user.id)
e_start = bps[:calendar_start_date].blank? ? bps[:postdate] : bps[:calendar_start_date]
e_start = Time.now.to_datetime if e_start.blank?
e_end = bps[:calendar_end_date].blank? ? bps[:deadline] : bps[:calendar_end_date]
#e_end = Time.now.to_datetime + 1.year if e_end.blank?
event.update_attributes(model_class: 'Bulletin',
module_key: 'announcement',
model_cat: bps[:category_id],
model_tags: bps[:tags],
model_page_id: bps[:page_id],
model_id: bulletin.id,start: e_start,
end: e_end,update_user_id: current_user.id,
all_day: bps[:calendar_all_day],
calendar_type_id: bps[:calendar_type_id],
title_translations: bps[:title_translations],
note_translations: bps[:subtitle_translations])
bps[:event_id] = event.id
end
bps
params.require(:curation_setting).permit!
end
end
@@ -1,96 +0,0 @@
require "rss"
class AnnouncementFeedsController < ApplicationController
include Admin::AnnouncementsHelper
def feed_add_remote
if params[:url].present?
uid = params[:uid].to_s
bulletin_feed = BulletinFeed.where(uid: uid).first
if !(bulletin_feed.remote_urls.include?(params[:url]))
bulletin_feed.remote_urls << params[:url]
bulletin_feed.save
end
end
render :json => {success: true}
end
def feed_remove_remote
if params[:url].present?
uid = params[:uid].to_s
bulletin_feed = BulletinFeed.where(uid: uid).first
if bulletin_feed.remote_urls.delete(params[:url])
bulletin_feed.save
end
end
render :json => {success: true}
end
def feed
uid = params[:uid].to_s
startdt = params[:start].blank? ? nil : params[:start]
enddt = params[:end].blank? ? nil : params[:end]
dt = params[:date].blank? ? nil : params[:date]
feed_cache = BulletinFeedCache.where(uid: uid, start: startdt, end: enddt, date: dt)
feed_cache_old = feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).last
feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).destroy
count = feed_cache.count
if count > 1
feed_cache.limit(count-1).destroy
end
feed_cache = feed_cache.first
anns = ''
if feed_cache.nil?
anns = BulletinFeed.where(uid: uid).first.generate_one_cache_timeout(startdt: startdt,enddt: enddt,dt: dt,base_url: request.base_url,timeout: 20)
anns = (feed_cache_old.content rescue "") if anns.nil?
else
anns = feed_cache.content
end
render :json => anns
end
def rssfeed
uid = params[:uid].to_s
@bf = BulletinFeed.find_by(:uid => uid) rescue nil
if !@bf.nil?
tags = @bf.tag_ids
if !tags.empty?
@announcements = Bulletin.can_display_and_sorted.is_approved.filter_by_tags(tags)
else
@announcements = Bulletin.can_display_and_sorted.is_approved
end
categories = @bf.category_ids
if !categories.empty?
@announcements = @announcements.filter_by_categories(categories)
end
end
respond_to do |format|
format.html {redirect_to "/xhr/announcements/rssfeed/#{@bf.uid}.rss"}
format.rss
end
end
def feeds
feeds = []
BulletinFeed.all.each do |bf|
feed = {}
feed["title_translations"] = bf.title_translations
feed["uid"] = bf.uid
feed["url"] = "#{request.base_url}/xhr/announcements/feed/#{bf.uid}"
feed["xml_url"] = "#{request.base_url}/xhr/announcements/rssfeed/#{bf.uid}.rss"
feed["tags"] = []
bf.tag_ids.each do |t|
tag = Tag.find(t)
d = {}
d["name_translations"] = tag.name_translations
feed["tags"] << d
end
feeds << feed
end
render :json => {"feeds" => feeds}.to_json
end
end
@@ -1,5 +1,5 @@
# encoding: utf-8
class BulletinsController < ApplicationController
class CurationPostsController < ApplicationController
before_filter :set_I18n
def annc_depts_translations
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
@@ -1,6 +1,6 @@
class AnnouncementsController < ApplicationController
class CurationsController < ApplicationController
ViewRootDir = File.expand_path("../../views", __FILE__)
include AnnouncementsHelper
include CurationsHelper
DefaultImgSrc = "/assets/announcement-default.jpg\" onerror=\"this.src=&quot;/assets/announcement-default-2.jpg&quot;;this.onerror='';"
def initialize
super
@@ -300,7 +300,7 @@ class AnnouncementsController < ApplicationController
end
max_all_count = [OrbitHelper.widget_data_count,anns.count].min
if @tab_option != 0
OrbitHelper.set_widget_title(OrbitHelper.widget_title +
OrbitHelper.set_widget_title(OrbitHelper.widget_title +
"<div style=\"clear: both;\"></div>" +
"<ul class=\"nav_tabs_filter\">" +
(use_tag ? tags.map.with_index{|tag,i|
@@ -310,7 +310,7 @@ class AnnouncementsController < ApplicationController
if tag != "all"
begin
read_more_text = I18n.t("announcement.more_") + tags_translations[tag]
rescue
rescue
nil
end
end
@@ -322,7 +322,7 @@ class AnnouncementsController < ApplicationController
if cat != "all"
begin
read_more_text = I18n.t("announcement.more_") + cats_translations[cat]
rescue
rescue
nil
end
end
@@ -361,19 +361,19 @@ class AnnouncementsController < ApplicationController
}
}
var wpexLocalize = {
"lightboxType": "iLightbox",
"iLightbox": { "auto": false, "skin": "minimal", "path": "horizontal",
"lightboxType": "iLightbox",
"iLightbox": { "auto": false, "skin": "minimal", "path": "horizontal",
"infinite": false, "maxScale": 1, "minScale": 0, "width": 1400, "height": "",
"slideshow": { "pauseTime": 3000, "startPaused": true },
"effects": { "reposition": true, "repositionSpeed": 200, "switchSpeed": 300,
"loadedFadeSpeed": 50, "fadeSpeed": 500
},
"show": { "title": true, "speed": 200 },
"hide": { "speed": 200 },
"slideshow": { "pauseTime": 3000, "startPaused": true },
"effects": { "reposition": true, "repositionSpeed": 200, "switchSpeed": 300,
"loadedFadeSpeed": 50, "fadeSpeed": 500
},
"show": { "title": true, "speed": 200 },
"hide": { "speed": 200 },
"overlay": { "blur": true, "opacity": "0.9" },
"slideShow": "Slideshow", "next": "Next", "previous": "Previous" ,
"thumbnails": { "maxWidth": 120, "maxHeight": 80 }
}
"slideShow": "Slideshow", "next": "Next", "previous": "Previous" ,
"thumbnails": { "maxWidth": 120, "maxHeight": 80 }
}
};
$(document).ready(function(){
var first_filter_tab = $("[data-subpart-id=\"'+subpart.id.to_s+'\"] .filter_tab").eq(0);
@@ -403,7 +403,7 @@ class AnnouncementsController < ApplicationController
if cats.count == 1 && cats[0] != "all"
begin
read_more_text = I18n.t("announcement.more_") + ((all_tags.count == 1 && all_tags[0] != 'all') ? tags_translations[tags[0]] : cats_translations[cats[0]])
rescue
rescue
nil
end
end
@@ -581,7 +581,7 @@ class AnnouncementsController < ApplicationController
first_deadline = sorted_anns.pluck(:deadline).compact.sort[0]
first_postdate = anns_for_locale.open_in_future.limit(1).pluck(:postdate)[0]
invalid_date = [first_postdate,first_deadline].compact.sort[0]
if devide_flag
now_anns = sorted_anns.to_a
top_anns = now_anns.select{|v| v.is_top}.map{|v| data_to_human_type(v,set_tags)}
@@ -2,7 +2,7 @@ require "net/http"
require "uri"
require 'json'
module Admin::AnnouncementsHelper
module Admin::CurationsHelper
def page_for_bulletin(bulletin)
if !bulletin.is_external_link || bulletin.external_link.blank?
ann_page = nil
@@ -1,4 +1,4 @@
module AnnouncementsHelper
module CurationsHelper
extend self
def data_to_human_type(a,set_tag_ids=nil,tmp_enable_annc_dept=false,annc_depts=[])
@@ -218,7 +218,7 @@ module AnnouncementsHelper
if wrap_elements.count > 0
htmls = parsing_repeats_again(wrap_elements,d[data_name][i], level + 1)
htmls[0].each_with_index do |html,i|
element = element.gsub(html,htmls[1][i])
element = element.gsub(html,htmls[1][i])
end
end
item.each do |key,value|
@@ -254,11 +254,11 @@ module AnnouncementsHelper
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = AnnouncementsController.new
begin
begin
data = @data# rescue nil
rescue Exception => e
rescue Exception => e
write_debug_file(e,'announcements',@target_action) if Site::DEBUG
end
end
if !data.nil?
wrap_elements = doc.css("*[data-list][data-level='0']")
htmls = parsing_repeats_again(wrap_elements,data,1)
@@ -291,11 +291,11 @@ module AnnouncementsHelper
doc = Nokogiri::HTML(file, nil, "UTF-8")
file.close
controller = AnnouncementsController.new
begin
begin
data = @data# rescue nil
rescue Exception => e
rescue Exception => e
write_debug_file(e,'announcements',@target_action) if Site::DEBUG
end
end
if data.nil?
return "<div class='well'> No content to show. </div>".html_safe
end
@@ -400,8 +400,8 @@ module AnnouncementsHelper
if layout_types.empty?
Dir.glob("#{Rails.root}/app/templates/#{@key}/modules/#{module_app}/*").each do |w|
next if File.ftype(w).eql?("directory")
w = File.basename(w, ".*")
w = File.basename(w, ".*")
w = File.basename(w, ".*")
w = File.basename(w, ".*")
if w[0,1] != "_" && w[0,1] != "s" && w != "info"
layout_types << w
end
@@ -434,7 +434,7 @@ module AnnouncementsHelper
<p><strong class=\"carousel__description\">#{e['description']}</strong></p>
</div>
<div class=\"transitionfade\"></div>
</div>"
</div>"
end.join+
"</div>
<ul class=\"controlplay\"><a class=\"resume-slide\" title = \"#{data['resume_btn_title']}\"><i></i></a><a class=\"pause-slide\" title = \"#{data['pause_btn_title']}\"><i></i></a></ul>
-179
View File
@@ -1,179 +0,0 @@
class BulletinFeed
include Mongoid::Document
include Mongoid::Timestamps
include Slug
field :title, as: :slug_title, type: String, localize: true
field :tag_ids, type: Array, default: []
field :category_ids, type: Array, default: []
field :remote_urls, type: Array, default: []
before_save do
BulletinFeedCache.where(uid: self.uid).each do |cache|
cache.regenerate
end
end
def annc_depts_translations
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['announcement'][:annc_depts_translations] rescue AnnouncementSetting.first.annc_depts_translations
else
AnnouncementSetting.first.annc_depts_translations rescue {}
end
end
def enable_annc_dept
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['announcement'][:enable_annc_dept] rescue AnnouncementSetting.first.enable_annc_dept
else
AnnouncementSetting.first.enable_annc_dept rescue false
end
end
def self.create_feed_cache(bulletin=nil,bulletin_feed=nil)
Thread.new do
if !bulletin.nil?
BulletinFeed.where(:tag_ids.in => Array(bulletin.tag_ids).collect{|v| v.to_s}).each do |bulletin_feed|
uid = bulletin_feed.uid
BulletinFeedCache.where(:uid => uid).each do |cache|
cache.regenerate
end
end
elsif !bulletin_feed.nil?
uid = bulletin_feed.uid
BulletinFeedCache.where(:uid => uid).each do |cache|
cache.regenerate
end
end
end
end
def generate_one_cache_timeout(startdt: nil,enddt: nil,dt: nil, base_url: nil, timeout: nil)
begin
if timeout.nil?
feed_cache_content = self.generate_one_cache(startdt: startdt,enddt: enddt,dt: dt,base_url: base_url)
else
Timeout::timeout(timeout) do
feed_cache_content = nil
thread = Thread.new do
feed_cache_content = self.generate_one_cache(startdt: startdt,enddt: enddt,dt: dt,base_url: base_url)
end
(1..(timeout.to_i+1)).each do
sleep(1)
break if !feed_cache_content.nil? && !thread.alive?
end
feed_cache_content
end
end
rescue=> e
puts [e,e.backtrace]
nil
end
end
def generate_one_cache(startdt: nil,enddt: nil,dt: nil, base_url: nil)
base_url = Site.first.root_url if base_url.nil?
uid = self.uid
bf = self
annc_depts = []
tmp_enable_annc_dept = (enable_annc_dept rescue false)
if tmp_enable_annc_dept
annc_depts = annc_depts_translations[I18n.default_locale.to_s] rescue []
end
tags = bf.tag_ids
categories = bf.category_ids
if !(categories.empty? && tags.empty?)
anns_before_filter = Bulletin.is_approved_and_show
can_display_and_sorted_flag = false
if !dt.nil?
dt = DateTime.parse(dt)
dtt = dt + 1.day
anns_before_filter = anns_before_filter.where(:postdate.gt => dt, :postdate.lt => dtt)
elsif !startdt.blank? && enddt.blank?
startdt = DateTime.parse(startdt)
enddt = DateTime.now
anns_before_filter = anns_before_filter.where(:postdate.gt => startdt, :postdate.lt => enddt)
elsif !startdt.blank? && !enddt.blank?
startdt = DateTime.parse(startdt)
enddt = DateTime.parse(enddt) + 1.day
anns_before_filter = anns_before_filter.where(:postdate.gt => startdt, :postdate.lt => enddt)
else
can_display_and_sorted_flag = true
end
if !tags.empty?
anns_before_filter = anns_before_filter.filter_by_tags(tags)
end
if !categories.empty?
anns_before_filter = anns_before_filter.filter_by_categories(categories,paginate=false)
end
anns_before_filter.selector = {"$and"=>[anns_before_filter.selector,{"$or"=>(I18n.available_locales.map{|v| {"title.#{v}"=>{"$nin"=>["", nil]}}})}]}
if can_display_and_sorted_flag
announcements = anns_before_filter.valid_time_range.to_a
else
announcements = anns_before_filter.to_a
end
else
anns_before_filter = Bulletin.can_display_and_sorted
announcements = anns_before_filter.to_a
end
all_anns = []
tag_ids = []
category_ids = []
first_postdate = anns_before_filter.open_in_future.limit(1).pluck(:postdate)[0]
first_deadline = nil
cat_ids = announcements.collect{|a| a.category_id.blank? ? nil : a.category_id.to_s}.compact.uniq
tag_ids = announcements.collect{|a| a.tag_ids.collect{|v| v.blank? ? nil : v.to_s}}.flatten.compact.uniq
tag_names = tag_ids.map{|tag_id| Tag.find(tag_id).name_translations rescue nil}.compact
category_titles = cat_ids.map{|cat_id| Category.find(cat_id).title_translations rescue nil}.compact
basic_query = {:module => 'announcement',:enabled_for=>I18n.locale}
if !cat_ids.blank?
query = basic_query.merge({:categories.all => cat_ids})
else
query = basic_query.clone
end
if !tag_ids.blank?
query = query.merge({:tags.all => tag_ids})
end
page = Page.where(query).first || Page.where(basic_query).first
more_url = page ? page.get_url : nil
announcements.each_with_index do |anns,i|
deadline = anns.deadline
if !deadline.blank?
if first_deadline.nil? || first_deadline>deadline
first_deadline = deadline
end
end
a = anns.get_data(annc_depts, tmp_enable_annc_dept, more_url, base_url, cat_ids, tag_ids)
all_anns << a
end
invalid_date = [first_postdate,first_deadline].compact.sort[0]
anns = {
"announcements" => all_anns,
"tags" => tag_names,
"categories" => category_titles
}.to_json
BulletinFeedCache.where(uid: uid,start: startdt,end: enddt,date: dt).destroy
feed_cache = BulletinFeedCache.create(uid: uid,content: anns,start: startdt,end: enddt,date: dt,invalid_date: invalid_date)
anns
end
def self.smart_convertor(text,url)
doc = Nokogiri.HTML(text)
doc.search('a[href]').each do |link|
if link['href'].nil?
link.delete 'href'
elsif link['href'].start_with?('/')
link['href'] = url + link['href']
elsif link['href'].start_with?('../')
link['href'] = url + link['href'][3..-1]
end
end
doc.search('img[src]').each do |link|
if link['src'].nil?
link.delete 'src'
elsif link['src'].start_with?('/')
link['src'] = url + link['src']
elsif link['src'].start_with?('../')
link['src'] = url + link['src'][3..-1]
end
end
return doc.css('body').inner_html
end
end
-34
View File
@@ -1,34 +0,0 @@
class BulletinFeedCache
include Mongoid::Document
include Mongoid::Timestamps
field :content, type: String, default: ''
field :uid
field :start
field :end
field :date
field :invalid_date, type: DateTime
def self.regenerate_all
caches = self.all.to_a
time_now = Time.now
caches.each do |cache|
if cache.invalid_date && cache.invalid_date <= time_now
cache.destroy
else
cache.regenerate
end
end
uids = BulletinFeed.all.pluck(:uid) - caches.collect(&:uid)
BulletinFeed.where(:uid.in=> uids).each do |feed|
feed.generate_one_cache()
end
end
def regenerate
st = self.start
et = self.end
dt = self.date
uid = self.uid
BulletinFeed.where(uid: uid).each{|v| v.generate_one_cache(startdt: st,enddt: et,dt: dt)} rescue nil
self.destroy
end
end
@@ -1,7 +1,7 @@
class AnnsCache
class CurationCache
include Mongoid::Document
field :parent_id
field :filter_result
field :locale,type: String,default: 'zh_tw'
field :invalid_date, type: DateTime
end
end
@@ -1,4 +1,4 @@
class Bulletin
class CurationPost
include Mongoid::Document
include Mongoid::Timestamps
@@ -8,8 +8,8 @@ class Bulletin
include OrbitTag::Taggable
include OrbitCategory::Categorizable
include Slug
require 'announcement/cache'
include Announcement::Cache
require 'curation/cache'
include Curation::Cache
attr_accessor :org_tag_ids,:org_category_id
def tags=(ids)
self.org_tag_ids = self.tag_ids
@@ -35,13 +35,10 @@ class Bulletin
end
super(index,value)
end
SubPart.class_eval { include Announcement::Cache }
Page.class_eval { include Announcement::Cache }
SubPart.class_eval { include Curation::Cache }
Page.class_eval { include Curation::Cache }
before_destroy do
if self.event_id.present? && !defined?(Calendar).nil?
Event.where(:id=>self.event_id).destroy
end
AnnsCache.all.destroy
CurationCache.all.destroy
end
field :is_edit, type: Boolean, default: false #use to check whether the preview record changed
field :copy_id
@@ -53,7 +50,6 @@ class Bulletin
field :calendar_end_date, :type => DateTime
field :calendar_all_day,type: Boolean,default: false
field :calendar_type_id
field :event_id
field :page_id
field :title, as: :slug_title, type: String, localize: true
field :title_plain_text, type: String, localize: true
@@ -92,13 +88,13 @@ class Bulletin
field :display_sub_annc_date, :type => Boolean, :default => false
mount_uploader :image, ImageUploader
has_many :bulletin_links, :autosave => true, :dependent => :destroy
has_many :bulletin_files, :autosave => true, :dependent => :destroy
has_many :bulletin_comments, :autosave => true, :dependent => :destroy
has_many :bulletin_carousel_images, :autosave => true, :dependent => :destroy
accepts_nested_attributes_for :bulletin_files, :allow_destroy => true
accepts_nested_attributes_for :bulletin_links, :allow_destroy => true
accepts_nested_attributes_for :bulletin_carousel_images, :allow_destroy => true
has_many :curation_post_links, :autosave => true, :dependent => :destroy
has_many :curation_post_files, :autosave => true, :dependent => :destroy
has_many :curation_post_comments, :autosave => true, :dependent => :destroy
has_many :curation_post_carousel_images, :autosave => true, :dependent => :destroy
accepts_nested_attributes_for :curation_post_files, :allow_destroy => true
accepts_nested_attributes_for :curation_post_links, :allow_destroy => true
accepts_nested_attributes_for :curation_post_carousel_images, :allow_destroy => true
before_destroy :destroy_email
@@ -122,7 +118,7 @@ class Bulletin
index({postdate: 1}, { unique: false, background: true })
index({is_top: -1,postdate: -1, _id: -1}, { unique: false, background: true })
index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
if AnnouncementSetting.pluck(:enable_manually_sort).first == true
if CurationSetting.pluck(:enable_manually_sort).first == true
index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,sort_number: 1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
end
field :sort_number, type: Integer
@@ -141,23 +137,13 @@ class Bulletin
def to_calendar_param
self.to_param
end
def calendar_type
CalendarType.where(:category_id.in => self.calendar_type_id)
end
def event
if !self.event_id.nil?
Event.where(:id => self.event_id).first
else
nil
end
end
def check_limit
check_status_limit(update_user).length>0 ? false : true
end
def check_status_limit(user,check_only=false)
role_ids = user.member_profile.roles.map(&:id) rescue []
status_settings = (role_ids.collect do |role_id|
AnnouncementSetting.first.anns_status_settings.select{|v| v.role_id.to_s == role_id.to_s}
CurationtSetting.first.anns_status_settings.select{|v| v.role_id.to_s == role_id.to_s}
end.flatten rescue [])
reach_limit = []
if status_settings.count != 0
@@ -239,7 +225,7 @@ class Bulletin
self.display_img rescue false
end
def comments
self.bulletin_comments.select{|v| !v.is_hidden}
self.curation_post_comments.select{|v| !v.is_hidden}
end
def open_comment_for_user(user)
role_ids = user.member_profile.roles.collect{|v| v.id.to_s} rescue ['visitor']
@@ -267,26 +253,21 @@ class Bulletin
status.html_safe
end
def top_text
I18n.t("announcement.status.top")
I18n.t("curation.status.top")
end
def hot_text
I18n.t("announcement.status.hot")
I18n.t("curation.status.hot")
end
def hidden_text
I18n.t("announcement.status.hidden")
end
def carousel_image_type
(self.custom_carousel_image_type == 0 ? AnnouncementSetting.last.carousel_image_type : self.custom_carousel_image_type - 1) rescue 0
(self.custom_carousel_image_type == 0 ? CurationSetting.last.carousel_image_type : self.custom_carousel_image_type - 1) rescue 0
end
def carousel_image_width
(self.custom_carousel_image_width.blank? ? AnnouncementSetting.last.carousel_image_width : self.custom_carousel_image_width) rescue "75%"
end
def self.agenda_events(agenda_start, agenda_end,read_more_url)
events = self.monthly_event(agenda_start, agenda_end).convert_front(read_more_url)
end
def self.monthly_event(start_date,end_date)
self.any_of({:postdate.lte => start_date,:deadline.gte => start_date},{:postdate.gte => start_date,:deadline.lte => end_date},{:postdate.lte => end_date,:deadline.gte => end_date}).asc(:postdate)
(self.custom_carousel_image_width.blank? ? CurationSetting.last.carousel_image_width : self.custom_carousel_image_width) rescue "75%"
end
def self.convert_front(read_more_url)
self.all.collect do |re|
{:id => re.id.to_s,
@@ -301,7 +282,7 @@ class Bulletin
end
def get_sub_annc_title_trans(locale=I18n.locale)
I18n.with_locale(locale) do
self.custom_sub_annc_title_trans.blank? ? (AnnouncementSetting.first.get_sub_annc_title_trans(locale) rescue I18n.t("announcement.table.title")) : self.custom_sub_annc_title_trans
self.custom_sub_annc_title_trans.blank? ? (CurationSetting.first.get_sub_annc_title_trans(locale) rescue I18n.t("curation.table.title")) : self.custom_sub_annc_title_trans
end
end
def get_sub_annc_list
@@ -313,16 +294,16 @@ class Bulletin
end
def enable_annc_dept
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['announcement'][:enable_annc_dept] rescue AnnouncementSetting.first.enable_annc_dept
OrbitHelper::SharedHash['curation'][:enable_annc_dept] rescue CurationSetting.first.enable_annc_dept
else
AnnouncementSetting.first.enable_annc_dept rescue false
CurationSetting.first.enable_annc_dept rescue false
end
end
def annc_depts_translations
if defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash
OrbitHelper::SharedHash['announcement'][:annc_depts_translations] rescue AnnouncementSetting.first.annc_depts_translations
OrbitHelper::SharedHash['curation'][:annc_depts_translations] rescue CurationSetting.first.annc_depts_translations
else
AnnouncementSetting.first.annc_depts_translations rescue {}
CurationSetting.first.annc_depts_translations rescue {}
end
end
def self.smart_convertor(text,url)
@@ -377,7 +358,7 @@ class Bulletin
if tag_ids.nil?
tag_ids = self.tag_ids
end
basic_query = {:module => 'announcement',:enabled_for=>locale}
basic_query = {:module => 'curation',:enabled_for=>locale}
if !cat_ids.blank?
query = basic_query.merge({:categories.all => cat_ids})
else
@@ -423,142 +404,35 @@ class Bulletin
a["author"] = author
a["params"] = self.to_param
a["subtitle_ann"] = self.subtitle if self.display_subtitle?
a["bulletin_links"] = []
a["bulletin_files"] = []
a["bulletin_carousel_images"] = self.bulletin_carousel_images.map{|image| {"src"=>"#{base_url}" + image.file.url,"description"=>image.description.to_s,"description_text"=>image.description_text }}
a["curation_post_links"] = []
a["curation_post_files"] = []
a["curation_post_carousel_images"] = self.curation_post_carousel_images.map{|image| {"src"=>"#{base_url}" + image.file.url,"description"=>image.description.to_s,"description_text"=>image.description_text }}
a["external_link"] = self["is_external_link"] ? self.external_link : nil
self.tags.each do |tag|
a["tags"] << {"name_translations" => tag.name_translations}
end
cat = self.category
a["category"] = {"title_translations" => (cat.title_translations rescue {})}
self.bulletin_links.each do |bl|
self.curation_post_links.each do |bl|
b = {}
b["url"] = bl.url
b["title_translations"] = bl.title_translations
a["bulletin_links"] << b
a["curation_post_links"] << b
end
self.bulletin_files.each do |bf|
self.curation_post_files.each do |bf|
b = {}
b["description_translations"] = bf.description_translations
b["title_translations"] = bf.title_translations
b["url"] = ("#{base_url}" + bf.file.url rescue "")
a["bulletin_files"] << b
a["curation_post_files"] << b
end
return a
end
def get_related_feeds
@category_id ||= self.category_id
@tag_ids ||= self.tag_ids
related_feeds = BulletinFeed.any_of({:category_ids=>@category_id.to_s}, {:tag_ids.in=>@tag_ids.map(&:to_s)}).to_a
end
def notify_feed(type="create")
if @is_hidden_changed
if self.is_hidden
if type == 'create'
return []
else
type = 'destroy'
end
else
type = 'create'
end
elsif self.is_hidden
return []
end
related_feeds = self.get_related_feeds.select{|feed| feed.remote_urls.count != 0}
if related_feeds.count != 0
bulletin_data = self.get_data
if type == "destroy"
tmp_data = {'type'=>'destroy', 'data'=>[self.uid]}
else
tmp_data = {'type'=>type, 'data'=>[bulletin_data.to_json]}
end
request = Net::HTTP::Post.new('/xhr/feeds/notify_change', 'Content-Type' => 'application/json')
related_feeds.each do |feed|
tmp_data['uid'] = feed.uid
request.body = tmp_data.to_json
feed.remote_urls.each do |remote_url|
uri = URI(remote_url)
http_req = Net::HTTP.new(uri.host, uri.port)
if remote_url.include?('https')
http_req.use_ssl = true
end
response = self.class.http_request( http_req , request )
end
end
end
end
def migrate_title_plain_text
self.title_plain_text_translations = OrbitHelper.get_plain_text_translations(self.title_translations)
end
def self.notify_all_feed(force_update=false)
related_feeds = BulletinFeed.where(:remote_urls.nin=>[nil, []]).to_a
related_feeds.each do |feed|
uid = feed.uid
startdt = nil
enddt = nil
dt = nil
feed_cache = BulletinFeedCache.where(uid: uid, start: startdt, end: enddt, date: dt)
if force_update
feed_cache = nil
else
feed_cache_old = feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).last
feed_cache.all_of([{:invalid_date.ne=>nil},{:invalid_date.lte => Time.now}]).destroy
count = feed_cache.count
if count > 1
feed_cache.limit(count-1).destroy
end
feed_cache = feed_cache.first
anns = ''
end
if feed_cache.nil?
anns = feed.generate_one_cache_timeout(startdt: startdt,enddt: enddt,dt: dt,timeout: 20)
anns = (feed_cache_old.content rescue "") if anns.nil?
else
anns = feed_cache.content
end
request = Net::HTTP::Post.new('/xhr/feeds/notify_change', 'Content-Type' => 'application/json')
tmp_data = {'type'=>'update_all', 'uid'=> uid, 'data'=>anns}
request.body = tmp_data.to_json
feed.remote_urls.each do |remote_url|
uri = URI(remote_url)
http_req = Net::HTTP.new(uri.host, uri.port)
if remote_url.include?('https')
http_req.use_ssl = true
end
response = self.http_request( http_req , request )
end
end
end
def self.notify_feed_delete(ids)
all_feeds = BulletinFeed.all.select{|feed| feed.remote_urls.count != 0}
if all_feeds.count != 0
tmp_data = {'type'=>'destroy'}
request = Net::HTTP::Post.new('/xhr/feeds/notify_change', 'Content-Type' => 'application/json')
all_feeds.each do |feed|
feed_uid = feed.uid
feed_cache = BulletinFeedCache.where(:uid=>feed_uid).first
if feed_cache
tmp_data['uid'] = feed_uid
tmp_data['data'] = ids & JSON.parse(feed_cache.content)["announcements"].map{|a| a["id"]}
request.body = tmp_data.to_json
if tmp_data['data'].count != 0
feed.remote_urls.each do |remote_url|
uri = URI(remote_url)
http_req = Net::HTTP.new(uri.host, uri.port)
if remote_url.include?('https')
http_req.use_ssl = true
end
response = self.http_request( http_req , request )
end
end
end
end
end
end
def self.http_request(http, request)
response = http.request(request)
if response.code.to_i == 301 || response.code.to_i == 302
@@ -1,5 +1,5 @@
# encoding: utf-8
class BulletinCarouselImage
class CurationPostCarouselImage
include Mongoid::Document
include Mongoid::Timestamps
@@ -8,7 +8,7 @@ class BulletinCarouselImage
field :description, localize: true
belongs_to :bulletin
belongs_to :curation_post
def description_text
Nokogiri::HTML(self.description.to_s).css("body").text() rescue ""
end
@@ -1,8 +1,8 @@
# encoding: utf-8
class BulletinComment
class CurationPostComment
include Mongoid::Document
include Mongoid::Timestamps
field :ip
field :comment
field :account_id
@@ -17,5 +17,5 @@ class BulletinComment
def roles
MemberProfile.where(:id => self.account_id).collect{|v| v.roles}.flatten
end
belongs_to :bulletin
end
belongs_to :curation_post
end
@@ -1,5 +1,5 @@
# encoding: utf-8
class BulletinFile
class CurationPostFile
include Mongoid::Document
include Mongoid::Timestamps
@@ -10,14 +10,14 @@ class BulletinFile
field :title, localize: true
field :choose_lang, :type => Array, :default => ["en","zh_tw"]
field :privacy_type, type: String, default: 'public'
belongs_to :bulletin
belongs_to :curation_post
def self.to_fronted(locale=I18n.locale)
self.all.map{|file| file.to_fronted(locale)}.compact rescue []
end
def to_fronted(locale=I18n.locale)
file = self
(file.enabled_for?(locale) && !file[:file].blank?) ? { "file_url" => "/xhr/announcements/file/#{file.id}/#{file['file']}" + "\" title=\"#{file.file_title}",
"file_title" => (file.title.blank? ? URI.unescape(File.basename(file.file.path)) : file.title rescue '')
(file.enabled_for?(locale) && !file[:file].blank?) ? { "file_url" => "/xhr/curations/file/#{file.id}/#{file['file']}" + "\" title=\"#{file.file_title}",
"file_title" => (file.title.blank? ? URI.unescape(File.basename(file.file.path)) : file.title rescue '')
} : nil rescue nil
end
@@ -1,17 +1,17 @@
# encoding: utf-8
require 'uri'
class BulletinLink
class CurationPostLink
include Mongoid::Document
include Mongoid::Timestamps
field :url
field :title, localize: true
belongs_to :bulletin
belongs_to :curation_post
before_save :add_http
#validates :url, :presence => true, :format => /\A(http|https):\/\/(([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5})|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(:[0-9]{1,5})?(\/.*)?\Z/i
protected
@@ -23,4 +23,4 @@ class BulletinLink
end
end
end
end
@@ -1,4 +1,4 @@
class AnnouncementSetting
class CurationPostSetting
include Mongoid::Document
include Mongoid::Timestamps
field :carousel_image_type, :type => Integer, :default => 0 # 0: carousel, 1: album
@@ -24,7 +24,7 @@ class AnnouncementSetting
def self.check_limit_for_user(user_id, b_id = nil)
limit = self.first.top_limit rescue 0
return true if limit == 0
count = Bulletin.where(:is_top => true, :create_user_id => user_id, :id.ne => b_id).count
count = CurationPost.where(:is_top => true, :create_user_id => user_id, :id.ne => b_id).count
return count < limit
end
@@ -34,18 +34,18 @@ class AnnouncementSetting
def get_sub_annc_title_trans(locale=I18n.locale)
I18n.with_locale(locale) do
self.sub_annc_title_trans.blank? ? I18n.t("announcement.table.title") : self.sub_annc_title_trans
self.sub_annc_title_trans.blank? ? I18n.t("curation.table.title") : self.sub_annc_title_trans
end
end
before_save do
can_update_shared_hash = (defined?(OrbitHelper::SharedHash) && OrbitHelper::SharedHash)
if self.enable_manually_sort_changed? && self.enable_manually_sort
Bulletin.index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,sort_number: 1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
Bulletin.create_indexes
CurationPost.index({approved: -1,is_hidden: 1,is_preview: 1, is_top: -1,sort_number: 1,postdate: -1,_id: -1,deadline: -1}, { unique: false, background: true })
CurationPost.create_indexes
if can_update_shared_hash
OrbitHelper::SharedMutex.synchronize do
OrbitHelper::SharedHash["announcement"][:enable_manually_sort] = self.enable_manually_sort
OrbitHelper::SharedHash["curation"][:enable_manually_sort] = self.enable_manually_sort
end
end
@need_update_bulletin = true
@@ -54,7 +54,7 @@ class AnnouncementSetting
if self.enable_annc_dept_changed?
if can_update_shared_hash
OrbitHelper::SharedMutex.synchronize do
OrbitHelper::SharedHash["announcement"][:enable_annc_dept] = self.enable_annc_dept
OrbitHelper::SharedHash["curation"][:enable_annc_dept] = self.enable_annc_dept
end
end
@need_update_bulletin = true
@@ -62,7 +62,7 @@ class AnnouncementSetting
if self.annc_depts_changed?
if can_update_shared_hash
OrbitHelper::SharedMutex.synchronize do
OrbitHelper::SharedHash["announcement"][:annc_depts_translations] = self.annc_depts_translations
OrbitHelper::SharedHash["curation"][:annc_depts_translations] = self.annc_depts_translations
end
end
@need_update_bulletin = true
@@ -71,9 +71,8 @@ class AnnouncementSetting
after_save do
if @need_update_bulletin
Thread.new do
AnnsCache.all.delete
Bulletin.notify_all_feed(true)
CurationCache.all.delete
end
end
end
end
end
@@ -1,7 +1,7 @@
class AnnsStatusSetting
class CurationStatusSetting
include Mongoid::Document
field :role_id
field :status
field :top_limit
belongs_to :announcement_setting
end
belongs_to :curation_setting
end
+1 -1
View File
@@ -5,5 +5,5 @@ scheduler = Rufus::Scheduler.new
#return if defined?(Rails::Console) || Rails.env.test? || File.split($0).last == 'rake'
scheduler.cron '43 2 * * *' do
system('bundle exec rake bulletin:remove_preview_bulletins')
system('bundle exec rake curation:remove_preview_curation_posts')
end
+1 -1
View File
@@ -2,7 +2,7 @@ en:
restful_actions:
feed: Feed
import: Import
announcement:
curation:
read_from_cache: "Read from cache!"
delete_selected: "Delete Selected"
expired: This announcement has been expired.
+1 -1
View File
@@ -3,7 +3,7 @@ zh_tw:
feed: 供給
import: 匯入
get_all_anncs_without_subannc: "選擇相關公告"
announcement:
curation:
read_from_cache: "從暫存中讀取!"
delete_selected: "刪除所選"
expired: 此則公告已過期
+173
View File
@@ -0,0 +1,173 @@
# encoding: UTF-8
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "curation/version"
require "json"
bundle_update_flag = ARGV[0]=='update' || ARGV[0]=='install'
if bundle_update_flag
require File.expand_path("../update_curation_post", __FILE__)
env_pwd = ENV['PWD']
begin
require ::File.expand_path('app/helpers/bundler_helper.rb', env_pwd)
extend BundlerHelper
rescue LoadError
def bundler_with_clean_env(&block)
if block_given?
if Bundler.respond_to?(:with_unbundled_env)
Bundler.with_unbundled_env(&block)
else
Bundler.with_clean_env(&block)
end
end
end
end
app_path = File.expand_path(__dir__)
template_path = env_pwd + '/app/templates'
all_template = Dir.glob(template_path+'/*/')
default_info_contents = JSON.parse(File.read("#{app_path}/modules/curation/info.json")) rescue {}
default_event_news_index_info = default_info_contents["frontend"].sort_by{|h| h["filename"].to_f} rescue []
default_event_news_widget_info = default_info_contents["widgets"].sort_by{|h| h["filename"].to_f} rescue []
default_event_news_show_info = default_info_contents["show"] rescue nil
all_template.each do |folder|
if !folder.include?('mobile')
if Dir.exist?("#{folder}modules/curation")
bundler_with_clean_env{system ("cp -rf #{folder}modules/curation #{folder}modules/curation && rm -rf #{folder}modules/curation")}
end
if Dir.exist?("#{folder}modules/curation/curation")
bundler_with_clean_env{system ("cp -rf #{folder}modules/curation/curation/* #{folder}modules/curation/. && rm -rf #{folder}modules/curation/curation")}
end
info_json_file = "#{folder}modules/curation/info.json"
if File.exist?(info_json_file)
bundler_with_clean_env{system ('cp -f '+ app_path + '/modules/curation/show.html.erb ' + "#{folder}modules/curation/.")}
update_event_news_template(folder)
begin
file_text = File.read(info_json_file) rescue ""
encode_file_text = file_text.encode("UTF-8", "UTF-8", invalid: :replace, replace: "???")
next if (encode_file_text.include?("???") rescue true)
info = JSON.parse(encode_file_text) rescue {}
flag = (info.count != 0 rescue false)
if flag
puts "Checking curation index"
index_info = info["frontend"].sort_by{|h| h["filename"].to_i} rescue []
last_index = index_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
update_index_flag = false
if !last_index.nil?
idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
default_event_news_index_info.each do |h|
name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
index_info_index = (index_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
if index_info_index == -1
update_index_flag = true
copy_h = h.dup
h.delete("force_cover")
last_index = last_index + 1
copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
copy_h["name"].keys.each do |locale|
copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
end
index_info << copy_h
bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/#{h["filename"]}.html.erb #{folder}modules/curation/#{copy_h["filename"]}.html.erb]}
elsif h["force_cover"] == "true"
bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/#{h["filename"]}.html.erb #{folder}modules/curation/#{index_info[index_info_index]["filename"]}.html.erb]}
end
end
if update_index_flag
info["frontend"] = index_info
puts "Writing json #{info["frontend"].count} in #{info_json_file}"
end
end
puts "Checking event_news widgets"
widget_info = info["widgets"].sort_by{|h| h["filename"].to_i} rescue []
last_index = widget_info.collect{|v| v["filename"].to_s.scan(/\d+/).collect{|v1| v1.to_i}}.flatten.sort[-1] rescue nil
update_widget_flag = false
if !last_index.nil?
idx_regex = /^(\d+[\. \t]*)|[ \t]+$/
default_event_news_widget_info.each do |h|
name_without_index = h["name"]["zh_tw"].gsub(idx_regex,'')
widget_info_index = (widget_info.index{|hh| hh["name"]["zh_tw"].gsub(idx_regex,'') == name_without_index}||-1 rescue -1)
if widget_info_index == -1
update_widget_flag = true
copy_h = h.dup
h.delete("force_cover")
last_index = last_index + 1
copy_h["filename"] = copy_h["filename"].sub(/\d+/){|ff| last_index.to_s}
copy_h["name"].keys.each do |locale|
copy_h["name"][locale] = copy_h["name"][locale].sub(/\d+/){|ff| last_index.to_s}
end
widget_info << copy_h
bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/_#{h["filename"]}.html.erb #{folder}modules/curation/_#{copy_h["filename"]}.html.erb]}
elsif h["force_cover"] == "true"
bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/_#{h["filename"]}.html.erb #{folder}modules/event_news_mod/_#{widget_info[widget_info_index]["filename"]}.html.erb]}
end
end
if update_widget_flag
info["widgets"] = widget_info
puts "Writing json #{info["widgets"].count} in #{info_json_file}"
end
end
update_show_flag = false
if !default_event_news_show_info.nil?
update_show_flag = info["show"] != default_event_news_show_info
info["show"] = default_event_news_show_info
default_event_news_show_info.each do |info_detail|
filename = info_detail['filename']
bundler_with_clean_env{%x[cp -f #{app_path}/modules/curation/#{filename}.html.erb #{folder}modules/curation/#{filename}.html.erb]}
end
end
if update_index_flag || update_widget_flag || update_show_flag
begin
info_json = JSON.pretty_generate(info).gsub(":[",":[\n").gsub(":{",":{\n")
rescue
info_json = info.to_s.gsub("=>",": \n")
end
File.open(info_json_file,"w+"){|f| f.write(info_json)}
end
end
rescue => e
puts e
puts "There has some error when checking event_news widgets"
end
else
if !Dir.exist?(File.dirname(info_json_file)) && Dir.exist?(File.dirname(File.dirname(info_json_file)))
bundler_with_clean_env{system ('cp -r '+ app_path + '/modules/ ' + folder)}
end
end
end
end
# all_template.each do |folder|
# if !folder.include?('mobile')
# moudle_path = "#{folder}modules/universal_table/"
# begin
# if Dir.exist?(File.dirname(moudle_path))
# bundler_with_clean_env{system ('cp -r '+ app_path + '/modules/ ' + folder)}
# end
# rescue => e
# puts "There was some error when updating event_news widget."
# end
# end
# end
end
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "curation"
s.version = Curation::VERSION
s.authors = ["RulingDigital"]
s.email = ["orbit@rulingcom.com"]
s.homepage = "http://www.rulingcom.com"
s.summary = "Curation for Orbit"
s.description = "Curation for Orbit"
s.license = "MIT"
s.metadata = {
"_require" => "#{File.expand_path("../app/models/curation_setting", __FILE__)}",
"global_hash" => "{enable_manually_sort: (CurationSetting.first.enable_manually_sort rescue false), is_postdate_sort_first: (CurationSetting.first.is_postdate_sort_first rescue false)}"
}
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["test/**/*"]
s.add_dependency "rufus-scheduler", "~> 3.6.0"
end
-6
View File
@@ -1,6 +0,0 @@
require "announcement/engine"
require "announcement/cache"
require "announcement/migrate"
module Announcement
end
-35
View File
@@ -1,35 +0,0 @@
module Announcement
module Cache
require 'active_support/concern'
extend ActiveSupport::Concern
included do
after_save :cache_tag_ids, :do_before_save
after_destroy :do_before_save
before_destroy :cache_tag_ids
end
def cache_tag_ids
if self.class == ::Bulletin
@tag_ids = self.tag_ids
@org_tag_ids = self.org_tag_ids
@category_id = self.category_id
@org_category_id = self.org_category_id
end
end
def do_before_save
if self.class == ::SubPart
::AnnsCache.where(parent_id: /^#{self.id}/).delete
elsif self.class == ::Bulletin || (self.class == ::Page && self.module == "announcement")
if self.class == ::Bulletin
tmp_tag_ids = (Array(@tag_ids) + Array(@org_tag_ids)).uniq
tmp_cat_ids = (Array(@category_id) + Array(@org_category_id)).uniq
Thread.new do
::BulletinFeedCache.where(:uid.in => ::BulletinFeed.any_of([{:tag_ids.in => tmp_tag_ids.collect{|v| v.to_s}},{:category_ids.in => tmp_cat_ids.collect{|v| v.to_s}}]).pluck(:uid)).to_a.each do |cache|
cache.regenerate
end
end
end
::AnnsCache.all.delete
end
end
end
end
-41
View File
@@ -1,41 +0,0 @@
module Announcement
module Migrate
def self.call
puts ['announcement migrate start']
gem_root = Announcement::Engine.root
require File.join(gem_root, 'app/models/announcement_setting')
require File.join(gem_root, 'app/models/bulletin')
require File.join(gem_root, 'app/models/bulletin_feed')
require File.join(gem_root, 'app/models/bulletin_feed_cache')
require File.join(gem_root, 'app/models/anns_cache')
setting = AnnouncementSetting.first || AnnouncementSetting.create
if !setting.migrate_flag.include?("v1")
Bulletin.all.pluck(:id, :title).each do |id, title_translations|
if title_translations.nil?
next
end
Bulletin.where(id: id).view.update_many({
"$set" => {
title_plain_text: OrbitHelper.get_plain_text_translations(title_translations)
}
})
end
setting.migrate_flag << "v1"
setting.save
end
AnnsCache.all.delete
#solve bug for thousands of generated feed cache
if BulletinFeedCache.count > BulletinFeed.count*5
BulletinFeedCache.collection.drop
end
BulletinFeedCache.regenerate_all
puts ['announcement migrate end']
end
end
end
+6
View File
@@ -0,0 +1,6 @@
require "curation/engine"
require "curation/cache"
require "curation/migrate"
module Curation
end
+26
View File
@@ -0,0 +1,26 @@
module Curation
module Cache
require 'active_support/concern'
extend ActiveSupport::Concern
included do
after_save :cache_tag_ids, :do_before_save
after_destroy :do_before_save
before_destroy :cache_tag_ids
end
def cache_tag_ids
if self.class == ::CurationPost
@tag_ids = self.tag_ids
@org_tag_ids = self.org_tag_ids
@category_id = self.category_id
@org_category_id = self.org_category_id
end
end
def do_before_save
if self.class == ::SubPart
::CurationCache.where(parent_id: /^#{self.id}/).delete
elsif self.class == ::CurationPost || (self.class == ::Page && self.module == "curation")
::CurationCache.all.delete
end
end
end
end
@@ -1,10 +1,10 @@
require "yaml"
module Announcement
module Curation
class Engine < ::Rails::Engine
initializer "announcement" do
initializer "curation" do
Rails.application.config.to_prepare do
begin
translate_data = Dir["#{Announcement::Engine.root}/config/locales/*.yml"] .map{|yaml_file| YAML.load(File.read(yaml_file))}
translate_data = Dir["#{Curation::Engine.root}/config/locales/*.yml"] .map{|yaml_file| YAML.load(File.read(yaml_file))}
data = {}
key1 = {}
key2 = {}
@@ -42,29 +42,29 @@ module Announcement
translate_data.each do |t_data|
v = t_data.values
k = t_data.keys[0]
key1[k] = v[0]['announcement']['picture_showing_size']
key2[k] = v[0]['announcement']['tabs_options']
key3[k] = v[0]['announcement']['read_more_position_options']
key4[k] = v[0]['announcement']['all_tabs_setting']
key1[k] = v[0]['curation']['picture_showing_size']
key2[k] = v[0]['curation']['tabs_options']
key3[k] = v[0]['curation']['read_more_position_options']
key4[k] = v[0]['curation']['all_tabs_setting']
key1_options.each_with_index do |kk,i|
key1_attr[i][k] = v[0]['announcement'][kk]
key1_attr[i][k] = v[0]['curation'][kk]
end
key2_options.each_with_index do |kk,i|
key2_attr[i][k] = v[0]['announcement'][kk]
key2_attr[i][k] = v[0]['curation'][kk]
end
key3_options.each_with_index do |kk,i|
key3_attr[i][k] = v[0]['announcement'][kk]
key3_attr[i][k] = v[0]['curation'][kk]
end
key4_options.each_with_index do |kk,i|
key4_attr[i][k] = v[0]['announcement'][kk]
key4_attr[i][k] = v[0]['curation'][kk]
end
key_item1[k] = v[0]['announcement']['showing_back_and_next']
key_item2[k] = v[0]['announcement']['enable_search']
value_item1[k] = v[0]['announcement']['not_show']
value_item2[k] = v[0]['announcement']['show_bottom']
value_item3[k] = v[0]['announcement']['show_top']
value2_item1[k] = v[0]['announcement']['no']
value2_item2[k] = v[0]['announcement']['yes']
key_item1[k] = v[0]['curation']['showing_back_and_next']
key_item2[k] = v[0]['curation']['enable_search']
value_item1[k] = v[0]['curation']['not_show']
value_item2[k] = v[0]['curation']['show_bottom']
value_item3[k] = v[0]['curation']['show_top']
value2_item1[k] = v[0]['curation']['no']
value2_item2[k] = v[0]['curation']['yes']
end
data[key1] = key1_attr
data[key2] = key2_attr
@@ -74,7 +74,7 @@ module Announcement
data_item[key_item2] = [value2_item1,value2_item2]
data_item[key1] = key1_attr
rescue => e
puts ['error in announcement',e]
puts ['error in curation',e]
end
if ENV['worker_num']=='0' && File.basename($0) != 'rake' && !Rails.const_defined?('Console')
@@ -82,21 +82,21 @@ module Announcement
begin
Migrate.call
rescue => e
puts ['error in announcement', e, e.backtrace]
puts ['error in curation', e, e.backtrace]
end
end
end
OrbitApp.registration "Announcement", :type => "ModuleApp" do
module_label "announcement.announcement"
OrbitApp.registration "Curation", :type => "ModuleApp" do
module_label "curation.curation"
base_url File.expand_path File.dirname(__FILE__)
widget_methods ["widget","random_announcement_widget", "tag_cloud"]
widget_methods ["widget","random_curation_widget", "tag_cloud"]
widget_settings [{"data_count"=>30}]
taggable "Bulletin"
taggable "CurationPost"
categorizable
authorizable
frontend_enabled
feeds_url "/xhr/announcements/feeds"
feeds_url "/xhr/curations/feeds"
data_count 1..30
begin
show_options data
@@ -106,61 +106,47 @@ module Announcement
end
if File.basename($0) != 'rake'
gem_root = Announcement::Engine.root
require File.join(gem_root, 'app/models/bulletin_feed')
require File.join(gem_root, 'app/models/bulletin_feed_cache')
require File.join(gem_root, 'app/models/anns_cache')
require File.join(gem_root, 'app/models/curation_cache')
begin
avoid_page_cache AnnsCache
avoid_page_cache BulletinFeedCache
avoid_page_cache BulletinFeed
rescue => e
puts ["avoid_page_cache", e.to_s]
end
end
side_bar do
head_label_i18n 'announcement.announcement', icon_class: "icons-megaphone"
head_label_i18n 'curation.curation', icon_class: "icons-megaphone"
available_for "users"
active_for_controllers (['admin/announcements'])
head_link_path "admin_announcements_path"
active_for_controllers (['admin/curations'])
head_link_path "admin_curations_path"
context_link 'announcement.all_articles',
:link_path=>"admin_announcements_path" ,
context_link 'curation.all_articles',
:link_path=>"admin_curations_path" ,
:priority=>1,
:active_for_action=>{'admin/announcements'=>'index'},
:active_for_action=>{'admin/curations'=>'index'},
:available_for => 'users'
context_link 'announcement.manually_sort',
:link_path=>"edit_sort_admin_announcement_path" ,
context_link 'curation.manually_sort',
:link_path=>"edit_sort_admin_curation_path" ,
:priority=>2,
:active_for_action=>{'admin/announcement'=>'edit_sort'},
:active_for_action=>{'admin/curation'=>'edit_sort'},
:available_for => 'managers'
context_link 'new_',
:link_path=>"new_admin_announcement_path" ,
context_link 'new_',
:link_path=>"new_admin_curation_path" ,
:priority=>3,
:active_for_action=>{'admin/announcements'=>'new'},
:active_for_action=>{'admin/curations'=>'new'},
:available_for => 'sub_managers'
context_link 'categories',
:link_path=>"admin_module_app_categories_path" ,
:link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'announcement').id}",
:link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'curation').id}",
:priority=>4,
:active_for_action=>{'admin/announcements'=>'categories'},
:active_for_category => 'Announcement',
:active_for_action=>{'admin/curations'=>'categories'},
:active_for_category => 'Curation',
:available_for => 'managers'
context_link 'tags',
:link_path=>"admin_module_app_tags_path" ,
:link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'announcement').id}",
:link_arg=>"{:module_app_id=>ModuleApp.find_by(:key=>'curation').id}",
:priority=>5,
:active_for_action=>{'admin/announcements'=>'tags'},
:active_for_tag => 'Announcement',
:available_for => 'managers'
context_link 'announcement.feed_list',
:link_path=>"admin_announcement_feed_path" ,
:priority=>6,
:active_for_action=>{'admin/announcements'=>'feed'},
:available_for => 'managers'
context_link 'announcement.import',
:link_path=>"admin_announcement_import_path" ,
:priority=>7,
:active_for_action=>{'admin/announcements'=>'import'},
:active_for_action=>{'admin/curations'=>'tags'},
:active_for_tag => 'Curation',
:available_for => 'managers'
context_link 'announcement.settings',
:link_path=>"admin_announcement_settings_path" ,
@@ -172,9 +158,9 @@ module Announcement
# temp = YAML.load_file(File.join(Rails.root,"config","mongoid.yml"))
# dbsettings = temp["production"]["sessions"]["default"]
# s = Moped::Session.new(dbsettings["hosts"])
# s.use dbsettings["database"]
# s.use dbsettings["database"]
# s[:bulletins].indexes.create({expirable_created_at: 1},{ expireAfterSeconds: 180 })
end
end
end
end
end
+32
View File
@@ -0,0 +1,32 @@
module Curation
module Migrate
def self.call
puts ['curation migrate start']
gem_root = Curation::Engine.root
require File.join(gem_root, 'app/models/curation_setting')
require File.join(gem_root, 'app/models/curation_cache')
setting = CurationSetting.first || CurationSetting.create
if !setting.migrate_flag.include?("v1")
CurationPost.all.pluck(:id, :title).each do |id, title_translations|
if title_translations.nil?
next
end
CurationPost.where(id: id).view.update_many({
"$set" => {
title_plain_text: OrbitHelper.get_plain_text_translations(title_translations)
}
})
end
setting.migrate_flag << "v1"
setting.save
end
CurationCache.all.delete
puts ['curation migrate end']
end
end
end
@@ -1,3 +1,3 @@
module Announcement
module Curation
VERSION = "0.0.1"
end
-8
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
+8
View File
@@ -0,0 +1,8 @@
desc 'Remove duplicated curation posts created by preview'
namespace :curation do
task :remove_preview_curation_posts => [:environment] do
posts = CurationPost.where(is_preview: true)
posts.destroy_all
end
end
File renamed without changes.
File renamed without changes.
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more