From 86af2330425b927cac93a2d31e78450b6a2c5194 Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Tue, 5 May 2015 11:45:58 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E4=BF=AE=E6=AD=A3autologin=E5=A4=9A?= =?UTF-8?q?=E7=BB=88=E7=AB=AF=E7=99=BB=E5=BD=95=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/account_controller.rb | 5 +---- app/controllers/application_controller.rb | 18 +++++++++--------- app/controllers/my_controller.rb | 4 +++- app/models/token.rb | 17 +++++++++++++++-- config/environments/development.rb | 2 +- config/initializers/session_store.rb | 2 +- db/schema.rb | 10 ---------- 7 files changed, 30 insertions(+), 28 deletions(-) diff --git a/app/controllers/account_controller.rb b/app/controllers/account_controller.rb index 22db3d5b4..981e0cb3c 100644 --- a/app/controllers/account_controller.rb +++ b/app/controllers/account_controller.rb @@ -31,9 +31,6 @@ class AccountController < ApplicationController else authenticate_user end - rescue AuthSourceException => e - logger.error "An error occured when authenticating #{params[:username]}: #{e.message}" - render_error :message => e.message end # Log out current user and redirect to welcome page @@ -329,7 +326,7 @@ class AccountController < ApplicationController end def set_autologin_cookie(user) - token = Token.create(:user => user, :action => 'autologin') + token = Token.get_or_create_permanent_login_token(user) cookie_options = { :value => token.value, :expires => 7.days.from_now, diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 741af2aee..0dc86fb01 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -156,16 +156,16 @@ class ApplicationController < ActionController::Base user end end + def try_to_autologin1 - - # auto-login feature starts a new session - user = User.try_to_autologin(params[:token]) - if user - start_user_session(user) - end - user - + user = User.try_to_autologin(params[:token]) + if user + logout_user if User.current.id != user.id + start_user_session(user) + end + user end + # Sets the logged in user def logged_user=(user) reset_session @@ -200,7 +200,7 @@ class ApplicationController < ActionController::Base def logout_user if User.current.logged? cookies.delete(autologin_cookie_name) - Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin']) + # Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin']) self.logged_user = nil end end diff --git a/app/controllers/my_controller.rb b/app/controllers/my_controller.rb index d42a750a1..8c76da1a9 100644 --- a/app/controllers/my_controller.rb +++ b/app/controllers/my_controller.rb @@ -200,7 +200,9 @@ class MyController < ApplicationController @user = us.change_password params.merge(:current_user_id => @user.id) if @user.errors.full_messages.count <= 0 flash.now[:notice] = l(:notice_account_password_updated) - redirect_to my_account_url + # 修改完密码,让其重新登录,并更新Token + Token.delete_user_all_tokens(@user) + redirect_to logout_url end end rescue Exception => e diff --git a/app/models/token.rb b/app/models/token.rb index c89ff30bc..d9fc75d76 100644 --- a/app/models/token.rb +++ b/app/models/token.rb @@ -1,3 +1,4 @@ +#coding=utf-8 # Redmine - project management software # Copyright (C) 2006-2013 Jean-Philippe Lang # @@ -14,7 +15,7 @@ # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - +# class Token < ActiveRecord::Base belongs_to :user validates_uniqueness_of :value @@ -27,6 +28,14 @@ class Token < ActiveRecord::Base self.value = Token.generate_token_value end + def self.get_or_create_permanent_login_token(user) + token = Token.get_token_from_user(user, 'autologin') + unless token + token = Token.create(:user => user, :action => 'autologin') + end + token + end + def self.get_token_from_user(user, action) token = Token.where(:action => action, :user_id => user).first unless token @@ -42,7 +51,7 @@ class Token < ActiveRecord::Base # Delete all expired tokens def self.destroy_expired - Token.delete_all ["action NOT IN (?) AND created_on < ?", ['feeds', 'api'], Time.now - @@validity_time] + Token.delete_all ["action NOT IN (?) AND created_on < ?", ['feeds', 'api', 'autologin'], Time.now - @@validity_time] end # Returns the active user who owns the key for the given action @@ -80,6 +89,10 @@ class Token < ActiveRecord::Base Redmine::Utils.random_hex(20) end + def self.delete_user_all_tokens(user) + Token.delete_all(user_id: user.id) + end + private # Removes obsolete tokens (same user and action) diff --git a/config/environments/development.rb b/config/environments/development.rb index 5c2427320..1b653d929 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -11,7 +11,7 @@ RedmineApp::Application.configure do # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false - config.cache_store = :file_store, "#{Rails.root }/files/cache_store/" + # config.cache_store = :file_store, "#{Rails.root }/files/cache_store/" # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = true diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb index 3d06070a2..1d3a65f8b 100644 --- a/config/initializers/session_store.rb +++ b/config/initializers/session_store.rb @@ -1 +1 @@ -Rails.application.config.session_store ActionDispatch::Session::CacheStore, :expire_after => 20.minutes, :key => '_trustie_session', :domain => :all +Rails.application.config.session_store ActionDispatch::Session::CacheStore, :expire_after => 90.minutes, :key => '_trustie_session', :domain => :all diff --git a/db/schema.rb b/db/schema.rb index 006b26e91..dcbe017fb 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -654,16 +654,6 @@ ActiveRecord::Schema.define(:version => 20150428021035) do add_index "journal_details", ["journal_id"], :name => "journal_details_journal_id" - create_table "journal_details_copy", :force => true do |t| - t.integer "journal_id", :default => 0, :null => false - t.string "property", :limit => 30, :default => "", :null => false - t.string "prop_key", :limit => 30, :default => "", :null => false - t.text "old_value" - t.text "value" - end - - add_index "journal_details_copy", ["journal_id"], :name => "journal_details_journal_id" - create_table "journal_replies", :id => false, :force => true do |t| t.integer "journal_id" t.integer "user_id" From 05428213a269bce7932e8bf648bfc1044e8da249 Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Wed, 6 May 2015 11:04:57 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E8=AE=A9session=E4=BF=9D=E6=8C=81=EF=BC=8C?= =?UTF-8?q?=E9=98=B2=E6=AD=A2=E9=95=BF=E6=97=B6=E9=97=B4=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E6=97=B6session=E4=B8=A2=E5=A4=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/account_controller.rb | 4 ++++ config/routes.rb | 2 ++ public/javascripts/application.js | 11 +++++++++-- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/app/controllers/account_controller.rb b/app/controllers/account_controller.rb index 981e0cb3c..3089386bf 100644 --- a/app/controllers/account_controller.rb +++ b/app/controllers/account_controller.rb @@ -44,6 +44,10 @@ class AccountController < ApplicationController # display the logout form end + def heartbeat + render :json => session[:user_id] + end + # Lets user choose a new password def lost_password (redirect_to(home_url); return) unless Setting.lost_password? diff --git a/config/routes.rb b/config/routes.rb index d3b8a1b37..ae87c6a65 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -227,6 +227,8 @@ RedmineApp::Application.routes.draw do match '/projects/search', :via => [:get, :post] match '/users/search', :via => [:get, :post] #end + + match 'account/heartbeat', to: 'account#heartbeat', :via => :get match 'login', :to => 'account#login', :as => 'signin', :via => [:get, :post] match 'logout', :to => 'account#logout', :as => 'signout', :via => [:get, :post] match 'account/register', :via => [:get, :post], :as => 'register' diff --git a/public/javascripts/application.js b/public/javascripts/application.js index f61738935..b2bd70d8d 100644 --- a/public/javascripts/application.js +++ b/public/javascripts/application.js @@ -571,10 +571,16 @@ function warnLeavingUnsaved(message) { }; } +function setupHeartBeat(){ + var time = 60*1000*30; // 30 mins + setInterval(function(){$.getJSON('/account/heartbeat');},time); +} + function setupAjaxIndicator() { - $('#ajax-indicator').bind('ajaxSend', function(event, xhr, settings) { - + if(settings && settings.url && settings.url.endsWith('account/heartbeat')){ + return; + } if ($('.ajax-loading').length === 0 && settings.contentType != 'application/octet-stream') { $('#ajax-indicator').show(); } @@ -622,6 +628,7 @@ function transpotUrl (scope) { } $(document).ready(setupAjaxIndicator); +$(document).ready(setupHeartBeat); $(document).ready(hideOnLoad); $(document).ready(addFormObserversForDoubleSubmit); From 297cb9182ee7c762aac8998f63a35a8111c78407 Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Wed, 6 May 2015 11:08:33 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E5=BC=80=E5=8F=91=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E8=BF=98=E6=98=AF=E9=87=87=E7=94=A8filecache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/environments/development.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/environments/development.rb b/config/environments/development.rb index 1b653d929..5c2427320 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -11,7 +11,7 @@ RedmineApp::Application.configure do # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false - # config.cache_store = :file_store, "#{Rails.root }/files/cache_store/" + config.cache_store = :file_store, "#{Rails.root }/files/cache_store/" # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = true From 9ba55296f59f37d2f07389e130484cc9cd283826 Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Wed, 6 May 2015 15:17:42 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AF=86=E7=A0=81?= =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=90=8E=E8=B7=B3=E5=88=B0=E4=B8=AA=E4=BA=BA?= =?UTF-8?q?=E8=B5=84=E6=96=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/my_controller.rb | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/app/controllers/my_controller.rb b/app/controllers/my_controller.rb index 8c76da1a9..d4f98749a 100644 --- a/app/controllers/my_controller.rb +++ b/app/controllers/my_controller.rb @@ -202,31 +202,18 @@ class MyController < ApplicationController flash.now[:notice] = l(:notice_account_password_updated) # 修改完密码,让其重新登录,并更新Token Token.delete_user_all_tokens(@user) - redirect_to logout_url + logout_user + redirect_to signin_url(back_url: my_account_path) + else + flash.now[:error] = l(:notice_account_wrong_password) end end rescue Exception => e if e.message == 'wrong password' flash.now[:error] = l(:notice_account_wrong_password) + else + flash.now[:error] = e.message end - # @user = User.current - # unless @user.change_password_allowed? - # flash.now[:error] = l(:notice_can_t_change_password) - # redirect_to my_account_url - # return - # end - # if request.post? - # if @user.check_password?(params[:password]) - # @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation] - # - # if @user.save - # flash.now[:notice] = l(:notice_account_password_updated) - # redirect_to my_account_url - # end - # else - # flash.now[:error] = l(:notice_account_wrong_password) - # end - # end end # Create a new feeds key From 3f88a67eef7a9cb3772b58bc169d22ddaaf42b17 Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Wed, 6 May 2015 23:32:34 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=99=A8=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E7=9B=B4=E6=8E=A5=E7=B2=98=E8=B4=B4QQ=E6=88=AA?= =?UTF-8?q?=E5=B1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/rails_kindeditor/helper.rb | 4 +- .../assets/kindeditor/plugins/paste/paste.js | 37 +++ public/javascripts/paste.js | 292 ++++++++++++++++++ 3 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 public/assets/kindeditor/plugins/paste/paste.js create mode 100644 public/javascripts/paste.js diff --git a/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb b/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb index 33d44a2ec..56b4c7adf 100644 --- a/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb +++ b/lib/rails_kindeditor/lib/rails_kindeditor/helper.rb @@ -55,7 +55,7 @@ module RailsKindeditor }" else "KindEditor.ready(function(K){ - #{editor_id}K.create('##{dom_id}', #{get_options(options).to_json}); + #{editor_id}K.create('##{dom_id}', #{get_options(options).to_json}).loadPlugin('paste'); });" end end @@ -101,4 +101,4 @@ module RailsKindeditor @template.send("kindeditor", @object_name, method, objectify_options(options)) end end -end \ No newline at end of file +end diff --git a/public/assets/kindeditor/plugins/paste/paste.js b/public/assets/kindeditor/plugins/paste/paste.js new file mode 100644 index 000000000..0f63ce18c --- /dev/null +++ b/public/assets/kindeditor/plugins/paste/paste.js @@ -0,0 +1,37 @@ +KindEditor.plugin('paste', function(K) { + var editor = this, + name = 'paste'; + var contentWindow = document.getElementsByTagName('iframe')[0].contentWindow; + contentWindow.document.getElementsByTagName('body')[0].onpaste = function(event) { + // use event.originalEvent.clipboard for newer chrome versions + var items = (event.clipboardData || event.originalEvent.clipboardData).items; + console.log(JSON.stringify(items)); // will give you the mime types + // find pasted image among pasted items + var blob = null; + for (var i = 0; i < items.length; i++) { + if (items[i].type.indexOf("image") === 0) { + blob = items[i].getAsFile(); + } + } + // load image if there is a pasted image + if (blob !== null) { + var reader = new FileReader(); + reader.onload = function(event) { + console.log(event.target.result); // data url! + var data = new FormData(); + data.append("imgFile", blob, "imageFilename.png"); + $.ajax({ + url: '/kindeditor/upload?dir=image', + contentType: false, + type: 'POST', + data: data, + processData: false, + success: function(data) { + editor.exec('insertimage', JSON.parse(data).url); + } + }); + }; + reader.readAsDataURL(blob); + } + } +}); diff --git a/public/javascripts/paste.js b/public/javascripts/paste.js new file mode 100644 index 000000000..961a29acb --- /dev/null +++ b/public/javascripts/paste.js @@ -0,0 +1,292 @@ +// Generated by CoffeeScript 1.9.0 + +/* +paste.js is an interface to read data ( text / image ) from clipboard in different browsers. It also contains several hacks. + +https://github.com/layerssss/paste.js + */ + +(function() { + var $, Paste, createHiddenEditable, dataURLtoBlob; + + $ = window.jQuery; + + $.paste = function(pasteContainer) { + var pm; + if (typeof console !== "undefined" && console !== null) { + console.log("DEPRECATED: This method is deprecated. Please use $.fn.pastableNonInputable() instead."); + } + pm = Paste.mountNonInputable(pasteContainer); + return pm._container; + }; + + $.fn.pastableNonInputable = function() { + var el, _i, _len; + for (_i = 0, _len = this.length; _i < _len; _i++) { + el = this[_i]; + Paste.mountNonInputable(el); + } + return this; + }; + + $.fn.pastableTextarea = function() { + var el, _i, _len; + for (_i = 0, _len = this.length; _i < _len; _i++) { + el = this[_i]; + Paste.mountTextarea(el); + } + return this; + }; + + $.fn.pastableContenteditable = function() { + var el, _i, _len; + for (_i = 0, _len = this.length; _i < _len; _i++) { + el = this[_i]; + Paste.mountContenteditable(el); + } + return this; + }; + + dataURLtoBlob = function(dataURL, sliceSize) { + var b64Data, byteArray, byteArrays, byteCharacters, byteNumbers, contentType, i, m, offset, slice, _ref; + if (sliceSize == null) { + sliceSize = 512; + } + if (!(m = dataURL.match(/^data\:([^\;]+)\;base64\,(.+)$/))) { + return null; + } + _ref = m, m = _ref[0], contentType = _ref[1], b64Data = _ref[2]; + byteCharacters = atob(b64Data); + byteArrays = []; + offset = 0; + while (offset < byteCharacters.length) { + slice = byteCharacters.slice(offset, offset + sliceSize); + byteNumbers = new Array(slice.length); + i = 0; + while (i < slice.length) { + byteNumbers[i] = slice.charCodeAt(i); + i++; + } + byteArray = new Uint8Array(byteNumbers); + byteArrays.push(byteArray); + offset += sliceSize; + } + return new Blob(byteArrays, { + type: contentType + }); + }; + + createHiddenEditable = function() { + return $(document.createElement('div')).attr('contenteditable', true).css({ + width: 1, + height: 1, + position: 'fixed', + left: -100, + overflow: 'hidden' + }); + }; + + Paste = (function() { + Paste.prototype._target = null; + + Paste.prototype._container = null; + + Paste.mountNonInputable = function(nonInputable) { + var paste; + paste = new Paste(createHiddenEditable().appendTo(nonInputable), nonInputable); + $(nonInputable).on('click', (function(_this) { + return function() { + return paste._container.focus(); + }; + })(this)); + paste._container.on('focus', (function(_this) { + return function() { + return $(nonInputable).addClass('pastable-focus'); + }; + })(this)); + return paste._container.on('blur', (function(_this) { + return function() { + return $(nonInputable).removeClass('pastable-focus'); + }; + })(this)); + }; + + Paste.mountTextarea = function(textarea) { + var ctlDown, paste; + if (-1 !== navigator.userAgent.toLowerCase().indexOf('chrome')) { + return this.mountContenteditable(textarea); + } + paste = new Paste(createHiddenEditable().insertBefore(textarea), textarea); + ctlDown = false; + $(textarea).on('keyup', function(ev) { + var _ref; + if ((_ref = ev.keyCode) === 17 || _ref === 224) { + return ctlDown = false; + } + }); + $(textarea).on('keydown', function(ev) { + var _ref; + if ((_ref = ev.keyCode) === 17 || _ref === 224) { + ctlDown = true; + } + if (ctlDown && ev.keyCode === 86) { + return paste._container.focus(); + } + }); + $(paste._target).on('pasteImage', (function(_this) { + return function() { + return $(textarea).focus(); + }; + })(this)); + $(paste._target).on('pasteText', (function(_this) { + return function() { + return $(textarea).focus(); + }; + })(this)); + $(textarea).on('focus', (function(_this) { + return function() { + return $(textarea).addClass('pastable-focus'); + }; + })(this)); + return $(textarea).on('blur', (function(_this) { + return function() { + return $(textarea).removeClass('pastable-focus'); + }; + })(this)); + }; + + Paste.mountContenteditable = function(contenteditable) { + var paste; + paste = new Paste(contenteditable, contenteditable); + $(contenteditable).on('focus', (function(_this) { + return function() { + return $(contenteditable).addClass('pastable-focus'); + }; + })(this)); + return $(contenteditable).on('blur', (function(_this) { + return function() { + return $(contenteditable).removeClass('pastable-focus'); + }; + })(this)); + }; + + function Paste(_at__container, _at__target) { + this._container = _at__container; + this._target = _at__target; + this._container = $(this._container); + this._target = $(this._target).addClass('pastable'); + this._container.on('paste', (function(_this) { + return function(ev) { + var clipboardData, file, item, reader, text, _i, _j, _len, _len1, _ref, _ref1, _ref2, _ref3, _results; + if (((_ref = ev.originalEvent) != null ? _ref.clipboardData : void 0) != null) { + clipboardData = ev.originalEvent.clipboardData; + if (clipboardData.items) { + _ref1 = clipboardData.items; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + item = _ref1[_i]; + if (item.type.match(/^image\//)) { + reader = new FileReader(); + reader.onload = function(event) { + return _this._handleImage(event.target.result); + }; + reader.readAsDataURL(item.getAsFile()); + } + if (item.type === 'text/plain') { + item.getAsString(function(string) { + return _this._target.trigger('pasteText', { + text: string + }); + }); + } + } + } else { + if (-1 !== Array.prototype.indexOf.call(clipboardData.types, 'text/plain')) { + text = clipboardData.getData('Text'); + _this._target.trigger('pasteText', { + text: text + }); + } + _this._checkImagesInContainer(function(src) { + return _this._handleImage(src); + }); + } + } + if (clipboardData = window.clipboardData) { + if ((_ref2 = (text = clipboardData.getData('Text'))) != null ? _ref2.length : void 0) { + return _this._target.trigger('pasteText', { + text: text + }); + } else { + _ref3 = clipboardData.files; + _results = []; + for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { + file = _ref3[_j]; + _this._handleImage(URL.createObjectURL(file)); + _results.push(_this._checkImagesInContainer(function() {})); + } + return _results; + } + } + }; + })(this)); + } + + Paste.prototype._handleImage = function(src) { + var loader; + loader = new Image(); + loader.onload = (function(_this) { + return function() { + var blob, canvas, ctx, dataURL; + canvas = document.createElement('canvas'); + canvas.width = loader.width; + canvas.height = loader.height; + ctx = canvas.getContext('2d'); + ctx.drawImage(loader, 0, 0, canvas.width, canvas.height); + dataURL = null; + try { + dataURL = canvas.toDataURL('image/png'); + blob = dataURLtoBlob(dataURL); + } catch (_error) {} + if (dataURL) { + return _this._target.trigger('pasteImage', { + blob: blob, + dataURL: dataURL, + width: loader.width, + height: loader.height + }); + } + }; + })(this); + return loader.src = src; + }; + + Paste.prototype._checkImagesInContainer = function(cb) { + var img, timespan, _i, _len, _ref; + timespan = Math.floor(1000 * Math.random()); + _ref = this._container.find('img'); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + img = _ref[_i]; + img["_paste_marked_" + timespan] = true; + } + return setTimeout((function(_this) { + return function() { + var _j, _len1, _ref1, _results; + _ref1 = _this._container.find('img'); + _results = []; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + img = _ref1[_j]; + if (!img["_paste_marked_" + timespan]) { + cb(img.src); + } + _results.push($(img).remove()); + } + return _results; + }; + })(this), 1); + }; + + return Paste; + + })(); + +}).call(this); From eed39ef0ef7b0e2d37c9ee610d1ab7d5edf6f375 Mon Sep 17 00:00:00 2001 From: guange <8863824@gmail.com> Date: Fri, 8 May 2015 14:28:17 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E5=A4=B4=E5=83=8F?= =?UTF-8?q?=E4=BC=9A=E8=BF=9B=E8=A1=8C=E5=8E=8B=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Gemfile | 10 +-- app/controllers/avatar_controller.rb | 20 +----- app/controllers/my_controller.rb | 96 +++++++++----------------- app/views/avatar/_avatar_form.html.erb | 5 +- app/views/avatar/upload.js.erb | 2 +- lib/tasks/avatar.rake | 11 +++ lib/trustie.rb | 3 +- lib/trustie/utils.rb | 2 +- lib/trustie/utils/image.rb | 35 ++++++++++ public/javascripts/avatars.js | 3 + 10 files changed, 94 insertions(+), 93 deletions(-) create mode 100644 lib/tasks/avatar.rake create mode 100644 lib/trustie/utils/image.rb diff --git a/Gemfile b/Gemfile index 0103a18b5..0aa77ae99 100644 --- a/Gemfile +++ b/Gemfile @@ -24,6 +24,8 @@ gem 'acts-as-taggable-on', '2.4.1' gem 'spreadsheet' gem 'ruby-ole' gem 'rails_kindeditor',path:'lib/rails_kindeditor' +gem "rmagick", ">= 2.0.0" + group :development do gem 'grape-swagger' #gem 'grape-swagger-ui', git: 'https://github.com/guange2015/grape-swagger-ui.git' @@ -48,14 +50,6 @@ group :test do gem 'selenium-webdriver', '~> 2.42.0' gem "faker" - # platforms :mri, :mingw do - # group :rmagick do - # # RMagick 2 supports ruby 1.9 - # # RMagick 1 would be fine for ruby 1.8 but Bundler does not support - # # different requirements for the same gem on different platforms - # gem "rmagick", ">= 2.0.0" - # end - #end end # Gems used only for assets and not required diff --git a/app/controllers/avatar_controller.rb b/app/controllers/avatar_controller.rb index 771a14fe8..84b8a92e4 100644 --- a/app/controllers/avatar_controller.rb +++ b/app/controllers/avatar_controller.rb @@ -56,25 +56,9 @@ class AvatarController < ApplicationController # self.digest = md5.hexdigest end @temp_file = nil - # @avatar = Avatar.new(:receive_file => request.raw_post) - # @avatar.source_id = User.current.id - # @avatar.image_file = params[:filename].presence || Redmine::Utils.random_hex(16) - # saved = @avatar.save - begin - f = Magick::ImageList.new(diskfile) - # gif格式不再做大小处理 - if f.format != 'GIF' - width = 300.0 - proportion = (width/f[0].columns) - height = (f[0].rows*proportion) - f.resize_to_fill!(width,height) - f.write(diskfile) - end - - rescue Exception => e - logger.error "[Error] avatar : avatar_controller#upload ===> #{e}" - end + image = Trustie::Utils::Image.new(diskfile,true) + image.compress(300) respond_to do |format| format.js diff --git a/app/controllers/my_controller.rb b/app/controllers/my_controller.rb index d4f98749a..ebb7c2fc8 100644 --- a/app/controllers/my_controller.rb +++ b/app/controllers/my_controller.rb @@ -95,76 +95,46 @@ class MyController < ApplicationController @pref = @user.pref diskfile = disk_filename('User', @user.id) diskfile1 = diskfile + 'temp' - if request.post? - @user.safe_attributes = params[:user] - @user.pref.attributes = params[:pref] - @user.pref[:no_self_notified] = (params[:no_self_notified] == '1') - @user.login = params[:login] - unless @user.user_extensions.nil? - if @user.user_extensions.identity == 2 - @user.firstname = params[:enterprise_name] - end - end - - @se = @user.extensions - if params[:occupation].to_i.to_s == params[:occupation] - @se.school_id = params[:occupation] - else - @se.occupation = params[:occupation] - end - @se.gender = params[:gender] - @se.location = params[:province] if params[:province] - @se.location_city = params[:city] if params[:city] - @se.identity = params[:identity].to_i if params[:identity] - @se.technical_title = params[:technical_title] if params[:technical_title] - @se.student_id = params[:no] if params[:no] - - if @user.save && @se.save - # 头像保存 - if File.exist?(diskfile1) - if File.exist?(diskfile) - File.delete(diskfile) - end - File.open(diskfile1, "rb") do |f| - buffer = f.read(10) - if buffer != "DELETE" - File.open(diskfile1, "rb") do |f1| - File.open(diskfile, "wb") do |f| - buffer = "" - while (buffer = f1.read(8192)) - f.write(buffer) - end - end - end - - # File.rename(diskfile + 'temp',diskfile); - end + begin + if request.post? + @user.safe_attributes = params[:user] + @user.pref.attributes = params[:pref] + @user.pref[:no_self_notified] = (params[:no_self_notified] == '1') + @user.login = params[:login] + unless @user.user_extensions.nil? + if @user.user_extensions.identity == 2 + @user.firstname = params[:enterprise_name] end end - # 确保文件被删除 - if File.exist?(diskfile1) - File.delete(diskfile1) + @se = @user.extensions + if params[:occupation].to_i.to_s == params[:occupation] + @se.school_id = params[:occupation] + else + @se.occupation = params[:occupation] end + @se.gender = params[:gender] + @se.location = params[:province] if params[:province] + @se.location_city = params[:city] if params[:city] + @se.identity = params[:identity].to_i if params[:identity] + @se.technical_title = params[:technical_title] if params[:technical_title] + @se.student_id = params[:no] if params[:no] - @user.pref.save - @user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : []) - set_language_if_valid @user.language - flash[:notice] = l(:notice_account_updated) - redirect_to user_url(@user) - return - else - # 确保文件被删除 - if File.exist?(diskfile1) - File.delete(diskfile1) + if @user.save && @se.save + # 头像保存 + FileUtils.mv diskfile1, diskfile, force: true + @user.pref.save + @user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : []) + set_language_if_valid @user.language + flash[:notice] = l(:notice_account_updated) + redirect_to user_url(@user) + return + else + @user.login = lg end - @user.login = lg - end - else - # 确保文件被删除 - if File.exist?(diskfile1) - File.delete(diskfile1) end + ensure + File.delete(diskfile1) if File.exist?(diskfile1) end end diff --git a/app/views/avatar/_avatar_form.html.erb b/app/views/avatar/_avatar_form.html.erb index 56f1f130e..43aaf9132 100644 --- a/app/views/avatar/_avatar_form.html.erb +++ b/app/views/avatar/_avatar_form.html.erb @@ -73,4 +73,7 @@ <% content_for :header_tags do %> <%= javascript_include_tag 'avatars' %> <% end %> - \ No newline at end of file + + + + diff --git a/app/views/avatar/upload.js.erb b/app/views/avatar/upload.js.erb index a7a341f10..b39e308ec 100644 --- a/app/views/avatar/upload.js.erb +++ b/app/views/avatar/upload.js.erb @@ -1,4 +1,4 @@ var imgSpan = $('#avatar_image'); -imgSpan.attr({"src":'<%= @urlfile.to_s << "?" << Time.now.to_s%>'}); +imgSpan.attr({"src":'<%= "#{@urlfile.to_s}?#{Time.now.to_i}" %>'}); diff --git a/lib/tasks/avatar.rake b/lib/tasks/avatar.rake new file mode 100644 index 000000000..9fe4f34bb --- /dev/null +++ b/lib/tasks/avatar.rake @@ -0,0 +1,11 @@ +desc "compress and backup avatar" +task :compress_avatar => :environment do + path = File.join(Rails.root, "public/images/avatars/User") + Dir.foreach(path) do |f| + if f.to_s =~ /^\d+$/ + puts f + image = Trustie::Utils::Image.new(File.join(path,f), true) + image.compress(300) + end + end +end diff --git a/lib/trustie.rb b/lib/trustie.rb index ff70d118c..b6cec3c86 100644 --- a/lib/trustie.rb +++ b/lib/trustie.rb @@ -1 +1,2 @@ -require 'trustie/utils' \ No newline at end of file +require 'trustie/utils' +require 'trustie/utils/image' diff --git a/lib/trustie/utils.rb b/lib/trustie/utils.rb index 7d0b2a272..45e5f0028 100644 --- a/lib/trustie/utils.rb +++ b/lib/trustie/utils.rb @@ -17,4 +17,4 @@ end if __FILE__ == $0 puts Trustie::Utils.digest('/Users/guange/Downloads/QQ_V4.0.2.dmg') -end \ No newline at end of file +end diff --git a/lib/trustie/utils/image.rb b/lib/trustie/utils/image.rb new file mode 100644 index 000000000..849c155ee --- /dev/null +++ b/lib/trustie/utils/image.rb @@ -0,0 +1,35 @@ +#coding=utf-8 + +module Trustie + module Utils + class Image + def initialize(file, bak) + @file = file + @bak = bak + end + + def compress(size=300) + backup if @bak + begin + f = Magick::ImageList.new(@file) + if f.format != 'GIF' + width = size + if f[0].columns > width + proportion = (width/f[0].columns.to_f) + height = (f[0].rows*proportion) + f.resize_to_fill!(width,height.to_i) + f.write(@file) + end + end + rescue Exception => e + logger.error "[Error] compress : ===> #{e}" + end + end + + def backup + FileUtils.cp @file, "#{@file}.bak" + end + + end + end +end diff --git a/public/javascripts/avatars.js b/public/javascripts/avatars.js index 3d8420dc0..a8f10edf0 100644 --- a/public/javascripts/avatars.js +++ b/public/javascripts/avatars.js @@ -190,6 +190,9 @@ function dragOutHandler(e) { } function setupFileDrop() { + $('#avatar_image').on('click', function(){ + console.log("click"); + }); if (window.File && window.FileList && window.ProgressEvent && window.FormData) { $.event.fixHooks.drop = { props: [ 'dataTransfer' ] };