kindeditor。

dev_repository_hjq
lizanle 11 years ago
parent 5f203ec8c0
commit d1bc2b85d0

@ -0,0 +1,6 @@
source "http://rubygems.org"
gemspec
gem 'carrierwave'
gem 'mini_magick'

File diff suppressed because it is too large Load Diff

@ -0,0 +1,2 @@
require 'bundler'
Bundler::GemHelper.install_tasks

@ -0,0 +1 @@
//= require kindeditor/kindeditor.js

@ -0,0 +1,127 @@
#coding: utf-8
require "find"
class Kindeditor::AssetsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
@imgFile, @dir = params[:imgFile], params[:dir]
unless @imgFile.nil?
if Kindeditor::AssetUploader.save_upload_info? # save upload info into database
begin
@asset = "Kindeditor::#{@dir.camelize}".constantize.new(:asset => @imgFile)
@asset.owner_id = params[:owner_id] ? params[:owner_id] : 0
@asset.owner_type = params[:owner_type] ? params[:owner_type] : ""
logger.warn '========= Warning: the owner_id is 0, "delete uploaded files automatically" will not work. =========' if defined?(logger) && @asset.owner_id == 0
@asset.asset_type = @dir
if @asset.save
render :text => ({:error => 0, :url => @asset.asset.url,:asset_id => @asset.id}.to_json)
else
show_error(@asset.errors.full_messages)
end
rescue Exception => e
show_error(e.to_s)
end
else # do not touch database
begin
uploader = "Kindeditor::#{@dir.camelize}Uploader".constantize.new
uploader.store!(@imgFile)
render :text => ({:error => 0, :url => uploader.url}.to_json)
rescue CarrierWave::UploadError => e
show_error(e.message)
rescue Exception => e
show_error(e.to_s)
end
end
else
show_error("No File Selected!")
end
end
def list
@root_path = "#{Rails.public_path}/#{RailsKindeditor.upload_store_dir}/"
@root_url = "/#{RailsKindeditor.upload_store_dir}/"
@img_ext = Kindeditor::AssetUploader::EXT_NAMES[:image]
@dir = params[:dir].strip || ""
unless Kindeditor::AssetUploader::EXT_NAMES.keys.map(&:to_s).push("").include?(@dir)
render :text => "Invalid Directory name."
return
end
Dir.chdir(Rails.public_path)
RailsKindeditor.upload_store_dir.split('/').each do |dir|
Dir.mkdir(dir) unless Dir.exist?(dir)
Dir.chdir(dir)
end
Dir.mkdir(@dir) unless Dir.exist?(@dir)
@root_path += @dir + "/"
@root_url += @dir + "/"
@path = params[:path].strip || ""
if @path.empty?
@current_path = @root_path
@current_url = @root_url
@current_dir_path = ""
@moveup_dir_path = ""
else
@current_path = @root_path + @path + "/"
@current_url = @root_url + @path + "/"
@current_dir_path = @path
@moveup_dir_path = @current_dir_path.gsub(/(.*?)[^\/]+\/$/, "")
end
@order = %w(name size type).include?(params[:order].downcase) ? params[:order].downcase : "name"
if !@current_path.match(/\.\./).nil?
render :text => "Access is not allowed."
return
end
if @current_path.match(/\/$/).nil?
render :text => "Parameter is not valid."
return
end
if !File.exist?(@current_path) || !File.directory?(@current_path)
render :text => "Directory does not exist."
return
end
@file_list = []
Dir.foreach(@current_path) do |filename|
hash = {}
if filename != "." and filename != ".." and filename != ".DS_Store"
file = @current_path + filename
if File.directory?(file)
hash[:is_dir] = true
hash[:has_file] = (Dir.foreach(file).count > 2)
hash[:filesize] = 0
hash[:is_photo] = false
hash[:filetype] = ""
else
hash[:is_dir] = false
hash[:has_file] = false
hash[:filesize] = File.size(file)
hash[:dir_path] = ""
file_ext = file.gsub(/.*\./,"")
hash[:is_photo] = @img_ext.include?(file_ext)
hash[:filetype] = file_ext
end
hash[:filename] = filename
hash[:datetime] = File.mtime(file).to_s(:db)
@file_list << hash
end
end
@file_list.sort! {|a, b| a["file#{@order}".to_sym] <=> b["file#{@order}".to_sym]}
@result = {}
@result[:moveup_dir_path] = @moveup_dir_path
@result[:current_dir_path] = @current_dir_path
@result[:current_url] = @current_url
@result[:total_count] = @file_list.count
@result[:file_list] = @file_list
render :text => @result.to_json
end
private
def show_error(msg)
render :text => ({:error => 1, :message => msg}.to_json)
end
end

@ -0,0 +1,91 @@
# encoding: utf-8
require 'carrierwave/processing/mime_types'
class Kindeditor::AssetUploader < CarrierWave::Uploader::Base
EXT_NAMES = {:image => RailsKindeditor.upload_image_ext,
:flash => RailsKindeditor.upload_flash_ext,
:media => RailsKindeditor.upload_media_ext,
:file => RailsKindeditor.upload_file_ext}
# Include RMagick or ImageScience support:
# include CarrierWave::RMagick
# include CarrierWave::ImageScience
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
if Kindeditor::AssetUploader.save_upload_info?
"#{RailsKindeditor.upload_store_dir}/#{model.asset_type.to_s.underscore.gsub(/(kindeditor\/)|(_uploader)/, '')}/#{model.created_at.strftime("%Y%m")}"
else
"#{RailsKindeditor.upload_store_dir}/#{self.class.to_s.underscore.gsub(/(kindeditor\/)|(_uploader)/, '')}/#{Time.now.strftime("%Y%m")}"
end
end
def cache_dir
"#{Rails.root}/tmp/uploads"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :scale => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
before :store, :remember_cache_id
after :store, :delete_tmp_dir
# store! nil's the cache_id after it finishes so we need to remember it for deletition
def remember_cache_id(new_file)
@cache_id_was = cache_id
end
def delete_tmp_dir(new_file)
# make sure we don't delete other things accidentally by checking the name pattern
if @cache_id_was.present? && @cache_id_was =~ /\A[\d]{8}\-[\d]{4}\-[\d]+\-[\d]{4}\z/
FileUtils.rm_rf(File.join(cache_dir, @cache_id_was))
end
end
def filename
if original_filename
@name ||= Digest::MD5.hexdigest(File.dirname(current_path)).slice(0, 12)
"#{@name}.#{file.extension}"
end
end
def self.save_upload_info?
begin
%w(asset file flash image media).each do |s|
"Kindeditor::#{s.camelize}".constantize
end
return true
rescue
return false
end
end
end

@ -0,0 +1,10 @@
# encoding: utf-8
class Kindeditor::FileUploader < Kindeditor::AssetUploader
def extension_white_list
EXT_NAMES[:file]
end
end

@ -0,0 +1,10 @@
# encoding: utf-8
class Kindeditor::FlashUploader < Kindeditor::AssetUploader
def extension_white_list
EXT_NAMES[:flash]
end
end

@ -0,0 +1,10 @@
# encoding: utf-8
class Kindeditor::ImageUploader < Kindeditor::AssetUploader
def extension_white_list
EXT_NAMES[:image]
end
end

@ -0,0 +1,10 @@
# encoding: utf-8
class Kindeditor::MediaUploader < Kindeditor::AssetUploader
def extension_white_list
EXT_NAMES[:media]
end
end

@ -0,0 +1,6 @@
Rails.application.routes.draw do
namespace :kindeditor do
post "/upload" => "assets#create"
get "/filemanager" => "assets#list"
end
end

@ -0,0 +1,10 @@
Description:
install kindeditor for your application
Example:
rails generate rails_kindeditor:install
This will create:
config/kindeditor.rb

@ -0,0 +1,23 @@
module RailsKindeditor
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
desc "Install kindeditor for your application."
def copy_kindeditor_files
if ::Rails.version < "3.1.0"
warn "Warning: rails_kindeditor ~> v0.3.0 only support Rails3.1+!"
warn "If you're using rails3.0.x, please check rails_kindeditor v0.2.8"
else
template "rails_kindeditor.rb", "config/initializers/rails_kindeditor.rb"
end
end
def insert_or_copy_js_files
if File.exist?('app/assets/javascripts/application.js')
insert_into_file "app/assets/javascripts/application.js", "//= require kindeditor\n", :after => "jquery_ujs\n"
else
copy_file "application.js", "app/assets/javascripts/application.js"
end
end
end
end

@ -0,0 +1,17 @@
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require kindeditor
//= require_tree .

@ -0,0 +1,19 @@
RailsKindeditor.setup do |config|
# Specify the subfolders in public directory.
# You can customize it , eg: config.upload_dir = 'this/is/my/folder'
config.upload_dir = 'uploads'
# Allowed file types for upload.
config.upload_image_ext = %w[gif jpg jpeg png bmp]
config.upload_flash_ext = %w[swf flv]
config.upload_media_ext = %w[swf flv mp3 wav wma wmv mid avi mpg asf rm rmvb]
config.upload_file_ext = %w[doc docx xls xlsx ppt htm html txt zip rar gz bz2]
# Porcess upload image size
# eg: 1600x1600 => 800x800
# 1600x800 => 800x400
# 400x400 => 400x400 # No Change
# config.image_resize_to_limit = [800, 800]
end

@ -0,0 +1,14 @@
Description:
Copy model, migration and uploader to your application.
Example:
rails generate rails_kindeditor:migration
This will create:
app/models/kindeditor/asset.rb
app/models/kindeditor/file.rb
app/models/kindeditor/flash.rb
app/models/kindeditor/image.rb
app/models/kindeditor/media.rb
db/migrate/xxxxxxxxx_create_kindeditor_assets.rb

@ -0,0 +1,36 @@
module RailsKindeditor
class MigrationGenerator < Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __FILE__)
desc "Copy model and migration to your application."
class_option :orm, :type => :string, :aliases => "-o", :default => "active_record", :desc => "ORM options: active_record or mongoid"
def copy_files
orm = options[:orm].to_s
orm = "active_record" unless %w{active_record mongoid}.include?(orm)
%w(asset file flash image media).each do |file|
copy_model(orm, file)
end
if Rails.version < '4.0.0' && Rails.version >= '3.0.0' # insert code for rails3
insert_into_file "app/models/kindeditor/asset.rb", " attr_accessible :asset\n", :after => "before_save :update_asset_attributes\n"
end
if orm == "active_record"
migration_template "migration/migration.rb", "db/migrate/create_kindeditor_assets.rb"
end
end
def self.next_migration_number(dirname)
if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.3d" % (current_migration_number(dirname) + 1)
end
end
private
def copy_model(orm, name)
template "models/#{orm}/kindeditor/#{name}.rb", "app/models/kindeditor/#{name}.rb"
end
end
end

@ -0,0 +1,17 @@
class CreateKindeditorAssets < ActiveRecord::Migration
def self.up
create_table :kindeditor_assets do |t|
t.string :asset
t.integer :file_size
t.string :file_type
t.integer :owner_id
t.string :asset_type # list by kindeditor: image, file, media, flash
t.timestamps
end
end
def self.down
drop_table :kindeditor_assets
end
end

@ -0,0 +1,14 @@
class Kindeditor::Asset < ActiveRecord::Base
self.table_name = 'kindeditor_assets'
mount_uploader :asset, Kindeditor::AssetUploader
validates_presence_of :asset
before_save :update_asset_attributes
private
def update_asset_attributes
if asset.present? && asset_changed?
self.file_size = asset.file.size
self.file_type = asset.file.content_type
end
end
end

@ -0,0 +1,3 @@
class Kindeditor::File < Kindeditor::Asset
mount_uploader :asset, Kindeditor::FileUploader
end

@ -0,0 +1,3 @@
class Kindeditor::Flash < Kindeditor::Asset
mount_uploader :asset, Kindeditor::FlashUploader
end

@ -0,0 +1,3 @@
class Kindeditor::Image < Kindeditor::Asset
mount_uploader :asset, Kindeditor::ImageUploader
end

@ -0,0 +1,3 @@
class Kindeditor::Media < Kindeditor::Asset
mount_uploader :asset, Kindeditor::MediaUploader
end

@ -0,0 +1,27 @@
require 'carrierwave/mongoid'
class Kindeditor::Asset
include Mongoid::Document
include Mongoid::Timestamps
field :file_size, :type => Integer
field :file_type, :type => String
field :owner_id, :type => Integer
field :asset_type, :type => String
mount_uploader :asset, Kindeditor::AssetUploader
validates_presence_of :asset
before_save :update_asset_attributes
def self.collection_name
:kindeditor_assets
end
private
def update_asset_attributes
if asset.present? && asset_changed?
self.file_size = asset.file.size
self.file_type = asset.file.content_type
end
end
end

@ -0,0 +1,3 @@
class Kindeditor::File < Kindeditor::Asset
mount_uploader :asset, Kindeditor::FileUploader
end

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save