fix old site after upgrade

This commit is contained in:
邱博亞 2021-11-27 13:37:57 +08:00
parent 3a239cf1ad
commit 30d394c953
3 changed files with 193 additions and 0 deletions

View File

@ -0,0 +1,119 @@
module Admin::GmailHelper
class ClientID
attr_accessor :id
attr_accessor :secret
def initialize(id,secret)
@id = id
@secret = secret
end
end
require "google/apis/gmail_v1"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
SCOPE = ['https://mail.google.com/']
OOB_URI = "urn:ietf:wg:oauth:2.0:oob"
GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
GmailTokenFile = "public/gmail-token.yaml"
def authorize_gmail(code=nil,site=nil)
site = Site.first if site.nil?
client_id = Google::Auth::ClientId.new(site.gmail_client_id,site.gmail_client_secret)
if !File.exist?(GmailTokenFile) and code.nil? and !site.gmail_access_token.nil? and !site.gmail_refresh_token.nil?
token_json ={"client_id" => site.gmail_client_id,
"access_token" => site.gmail_access_token,
"refresh_token" => site.gmail_refresh_token,
"scope" => SCOPE,
"expiration_time_millis" => 3600}.to_json
File.open(GmailTokenFile, 'w') { |file| file.write(YAML.dump({'me' => token_json})) }
end
token_store = Google::Auth::Stores::FileTokenStore.new(file: GmailTokenFile)
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
user_id = 'me'
credentials = authorizer.get_credentials user_id
if credentials.nil? && !code.nil?
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
def AccountsUrl(cmd)
"#{GOOGLE_ACCOUNTS_BASE_URL}/#{cmd}"
end
def GeneratePermissionUrl(scope = 'https://mail.google.com/')
client_id = Site.first.gmail_client_id
scope = ERB::Util.url_encode(scope)
request_url = AccountsUrl('o/oauth2/auth')
redirect_uri = OOB_URI
"#{request_url}?scope=#{scope}&client_id=#{client_id}&response_type=code&redirect_uri=#{redirect_uri}"
end
def send_post_request(request_url,param,req_params={})
uri = URI(request_url)
res_net = Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https',
open_timeout: 60,read_timeout: 60,
verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
req = Net::HTTP::Post.new(uri)
req.content_type='application/x-www-form-urlencoded'
req_params.each do |k,v|
req[k] = v
end
req.body = URI.encode_www_form(param)
http.request(req)
end
end
def AuthorizeTokens(client_id, client_secret, authorization_code)
credentials = authorize_gmail(authorization_code)
"""
param = {}
param['client_id'] = client_id
param['client_secret'] = client_secret
param['code'] = authorization_code
param['redirect_uri'] = 'urn:ietf:wg:oauth:2.0:oob'
param['grant_type'] = 'authorization_code'
request_url = AccountsUrl('o/oauth2/token')
res_net = send_post_request(request_url,param,{'Pragma'=>'no-cache','Cache-Control'=>'no-store'})
res_net.code=='200' ? JSON.load(res_net.body) : {}
"""
credentials.as_json
end
def set_new_token()
site = Site.first if site.nil?
client_secret = site.gmail_client_secret
client_id = site.gmail_client_id
access_token = site.gmail_access_token
refresh_token = site.gmail_refresh_token
access_token = RefreshToken(client_id, client_secret, refresh_token)['access_token']
if !access_token.nil?
site.update_attributes(gmail_access_token: access_token)
end
access_token
end
def RefreshToken(client_id, client_secret, refresh_token)
param = {}
param['client_id'] = client_id
param['client_secret'] = client_secret
param['refresh_token'] = refresh_token
param['grant_type'] = 'refresh_token'
request_url = AccountsUrl('o/oauth2/token')
res_net = send_post_request(request_url,param)
res_net.code=='200' ? JSON.load(res_net.body) : {}
end
def send_gmail(raw,service=nil)
site = Site.first
if service.nil?
service = Google::Apis::GmailV1::GmailService.new
service.client_options.application_name = "Gmail API"
service.authorization = authorize_gmail(nil,site)
end
user_id = 'me'
message = Google::Apis::GmailV1::Message.new(raw: raw)
error = nil
result = nil
service.send_user_message(user_id,message,quota_user: site[:title][site.default_locale||:zh_tw]){|r,err| result=r;error=err}
[service,error]
end
end

View File

@ -22,6 +22,52 @@ else
storage_options.merge!(options)
end
end
#monkey the behavier as before(mongoid 4)
module Mongoid
module Contextual
class Mongo
def add_default_sort_options
if !criteria.options.key?(:sort)
criteria.options[:sort] = {:_id => 1}
apply_option(:sort)
end
end
def first
add_default_sort_options
return documents.first if cached? && cache_loaded?
try_cache(:first) do
if raw_doc = view.limit(-1).first
doc = Factory.from_db(klass, raw_doc, criteria.options[:fields])
eager_load([doc]).first
end
end
end
def last
add_default_sort_options
try_cache(:last) do
with_inverse_sorting do
if raw_doc = view.limit(-1).first
doc = Factory.from_db(klass, raw_doc, criteria.options[:fields])
eager_load([doc]).first
end
end
end
end
def documents_for_iteration
add_default_sort_options
return documents if cached? && !documents.empty?
return view unless eager_loadable?
docs = view.map{ |doc| Factory.from_db(klass, doc, criteria.options[:fields]) }
eager_load(docs)
end
end
end
end
BSON::Int64.class_eval do
def bson_int64?
self.to_bson_key.bson_int64?
end
end
end
module Mongoid
module Findable

View File

@ -0,0 +1,28 @@
# unicorn_rails -c config/unicorn.rb -E development -D
# kill -s USR2 PID_OF_MASTER
rails_root = `pwd`.gsub("\n", "")
rails_env = ENV['RAILS_ENV'] || 'production'
cpu_cores = %x(cat /proc/cpuinfo | grep processor | wc -l).sub("\n",'').to_i rescue 2
cpu_cores = File.read("#{rails_root}/../cpu_cores.txt").force_encoding('utf-8').sub("\n",'').to_i if (File.exists?("#{rails_root}/../cpu_cores.txt") rescue false)
worker_processes (rails_env == 'production' ? cpu_cores : 1)
# preload_app true
timeout 30
listen "#{rails_root}/tmp/unicorn.sock", :backlog => 64
stderr_path "#{rails_root}/log/unicorn.log"
stdout_path "#{rails_root}/log/unicorn.log"
before_fork do |server, worker|
ENV['worker_num'] = "#{worker.nr}"
old_pid = "#{rails_root}/tmp/pids/unicorn.pid.oldbin"
if File.exists?(old_pid) && server.pid != old_pid
begin
Process.kill("QUIT", File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
end
end
end