Commit dd40de65 by 梁宇哲

Merge branch 'refactor/app_push' into 'master'

推送服务代码重构一期

See merge request !2
parents 5b2d80ce 41b1d714
......@@ -38,3 +38,6 @@
# Ignore master key for decrypting credentials and more.
/config/master.key
config/database.yml
/db/schema.rb
ruby-2.6.0
\ No newline at end of file
ruby-2.6.5
\ No newline at end of file
......@@ -2,12 +2,13 @@ source 'https://gems.ruby-china.com'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.0'
ruby '2.6.5'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.2', '>= 5.2.2.1'
gem 'rails', '~> 6.0.0'
# Use sqlite3 as the database for Active Record
gem 'mysql2', '>= 0.3.18', '< 0.5'
# gem 'sqlite3'
gem 'mysql2', '~> 0.5.3'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
......@@ -49,13 +50,14 @@ group :development do
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem 'capistrano-faster-rails'
# deplopy
gem "capistrano", "~> 3.11", require: false
gem 'capistrano-rvm', '~> 0.1.2', require: false
gem 'capistrano-rails', '~> 1.4', require: false
gem 'capistrano3-puma', '~> 3.1', '>= 3.1.1', require: false # https://github.com/seuros/capistrano-puma
gem 'capistrano-sidekiq', '~> 1.0', '>= 1.0.2', require: false
gem 'capistrano-sidekiq', '~> 1.0', '>= 1.0.2'
end
group :test do
......
GEM
remote: https://gems.ruby-china.com/
specs:
actioncable (5.2.3)
actionpack (= 5.2.3)
actioncable (6.0.2.1)
actionpack (= 6.0.2.1)
nio4r (~> 2.0)
websocket-driver (>= 0.6.1)
actionmailer (5.2.3)
actionpack (= 5.2.3)
actionview (= 5.2.3)
activejob (= 5.2.3)
actionmailbox (6.0.2.1)
actionpack (= 6.0.2.1)
activejob (= 6.0.2.1)
activerecord (= 6.0.2.1)
activestorage (= 6.0.2.1)
activesupport (= 6.0.2.1)
mail (>= 2.7.1)
actionmailer (6.0.2.1)
actionpack (= 6.0.2.1)
actionview (= 6.0.2.1)
activejob (= 6.0.2.1)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 2.0)
actionpack (5.2.3)
actionview (= 5.2.3)
activesupport (= 5.2.3)
rack (~> 2.0)
actionpack (6.0.2.1)
actionview (= 6.0.2.1)
activesupport (= 6.0.2.1)
rack (~> 2.0, >= 2.0.8)
rack-test (>= 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (5.2.3)
activesupport (= 5.2.3)
rails-html-sanitizer (~> 1.0, >= 1.2.0)
actiontext (6.0.2.1)
actionpack (= 6.0.2.1)
activerecord (= 6.0.2.1)
activestorage (= 6.0.2.1)
activesupport (= 6.0.2.1)
nokogiri (>= 1.8.5)
actionview (6.0.2.1)
activesupport (= 6.0.2.1)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
activejob (5.2.3)
activesupport (= 5.2.3)
rails-html-sanitizer (~> 1.1, >= 1.2.0)
activejob (6.0.2.1)
activesupport (= 6.0.2.1)
globalid (>= 0.3.6)
activemodel (5.2.3)
activesupport (= 5.2.3)
activerecord (5.2.3)
activemodel (= 5.2.3)
activesupport (= 5.2.3)
arel (>= 9.0)
activestorage (5.2.3)
actionpack (= 5.2.3)
activerecord (= 5.2.3)
activemodel (6.0.2.1)
activesupport (= 6.0.2.1)
activerecord (6.0.2.1)
activemodel (= 6.0.2.1)
activesupport (= 6.0.2.1)
activestorage (6.0.2.1)
actionpack (= 6.0.2.1)
activejob (= 6.0.2.1)
activerecord (= 6.0.2.1)
marcel (~> 0.3.1)
activesupport (5.2.3)
activesupport (6.0.2.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
addressable (2.6.0)
public_suffix (>= 2.0.2, < 4.0)
airbrussh (1.3.1)
zeitwerk (~> 2.2)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
airbrussh (1.4.0)
sshkit (>= 1.6.1, != 1.7.0)
archive-zip (0.12.0)
io-like (~> 0.3.0)
arel (9.0.0)
bindex (0.7.0)
bootsnap (1.4.4)
bindex (0.8.1)
bootsnap (1.4.5)
msgpack (~> 1.0)
builder (3.2.3)
builder (3.2.4)
byebug (11.0.1)
capistrano (3.11.0)
capistrano (3.11.2)
airbrussh (>= 1.0.0)
i18n
rake (>= 10.0.0)
sshkit (>= 1.9.0)
capistrano-bundler (1.5.0)
capistrano-bundler (1.6.0)
capistrano (~> 3.1)
capistrano-faster-rails (1.0.7)
capistrano-rails (1.4.0)
capistrano (~> 3.1)
capistrano-bundler (~> 1.1)
capistrano-rvm (0.1.2)
capistrano (~> 3.0)
sshkit (~> 1.2)
capistrano-sidekiq (1.0.2)
capistrano-sidekiq (1.0.3)
capistrano (>= 3.9.0)
sidekiq (>= 3.4)
sidekiq (>= 3.4, < 6.0)
capistrano3-puma (3.1.1)
capistrano (~> 3.7)
capistrano-bundler
puma (~> 3.4)
capybara (3.20.2)
capybara (3.29.0)
addressable
mini_mime (>= 0.1.3)
nokogiri (~> 1.8)
rack (>= 1.6.0)
rack-test (>= 0.6.3)
regexp_parser (~> 1.2)
regexp_parser (~> 1.5)
xpath (~> 3.2)
childprocess (1.0.1)
rake (< 13.0)
childprocess (3.0.0)
chromedriver-helper (2.1.1)
archive-zip (~> 0.10)
nokogiri (~> 1.8)
......@@ -96,17 +109,17 @@ GEM
coffee-script-source (1.12.2)
concurrent-ruby (1.1.5)
connection_pool (2.2.2)
crass (1.0.4)
erubi (1.8.0)
crass (1.0.5)
erubi (1.9.0)
execjs (2.7.0)
ffi (1.11.1)
ffi (1.11.3)
globalid (0.4.2)
activesupport (>= 4.2.0)
god (0.13.7)
httparty (0.13.7)
json (~> 1.8)
multi_xml (>= 0.5.2)
i18n (1.6.0)
i18n (1.7.0)
concurrent-ruby (~> 1.0)
igetui-ruby (1.2.2)
json (~> 1.8, >= 1.8.1)
......@@ -119,7 +132,7 @@ GEM
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
loofah (2.2.3)
loofah (2.4.0)
crass (~> 1.0.2)
nokogiri (>= 1.5.9)
mail (2.7.1)
......@@ -128,63 +141,65 @@ GEM
mimemagic (~> 0.3.2)
method_source (0.9.2)
mimemagic (0.3.3)
mini_mime (1.0.1)
mini_mime (1.0.2)
mini_portile2 (2.4.0)
minitest (5.11.3)
msgpack (1.2.10)
minitest (5.13.0)
msgpack (1.3.1)
multi_xml (0.6.0)
mysql2 (0.4.10)
net-scp (1.2.1)
net-ssh (>= 2.6.5)
net-ssh (5.1.0)
nio4r (2.3.1)
nokogiri (1.10.3)
mysql2 (0.5.3)
net-scp (2.0.0)
net-ssh (>= 2.6.5, < 6.0.0)
net-ssh (5.2.0)
nio4r (2.5.2)
nokogiri (1.10.7)
mini_portile2 (~> 2.4.0)
public_suffix (3.0.3)
puma (3.12.1)
rack (2.0.7)
rack-protection (2.0.5)
public_suffix (4.0.1)
puma (3.12.2)
rack (2.0.8)
rack-protection (2.0.7)
rack
rack-test (1.1.0)
rack (>= 1.0, < 3)
rails (5.2.3)
actioncable (= 5.2.3)
actionmailer (= 5.2.3)
actionpack (= 5.2.3)
actionview (= 5.2.3)
activejob (= 5.2.3)
activemodel (= 5.2.3)
activerecord (= 5.2.3)
activestorage (= 5.2.3)
activesupport (= 5.2.3)
rails (6.0.2.1)
actioncable (= 6.0.2.1)
actionmailbox (= 6.0.2.1)
actionmailer (= 6.0.2.1)
actionpack (= 6.0.2.1)
actiontext (= 6.0.2.1)
actionview (= 6.0.2.1)
activejob (= 6.0.2.1)
activemodel (= 6.0.2.1)
activerecord (= 6.0.2.1)
activestorage (= 6.0.2.1)
activesupport (= 6.0.2.1)
bundler (>= 1.3.0)
railties (= 5.2.3)
railties (= 6.0.2.1)
sprockets-rails (>= 2.0.0)
rails-dom-testing (2.0.3)
activesupport (>= 4.2.0)
nokogiri (>= 1.6)
rails-html-sanitizer (1.0.4)
loofah (~> 2.2, >= 2.2.2)
rails-html-sanitizer (1.3.0)
loofah (~> 2.3)
rails_param (0.10.2)
railties (5.2.3)
actionpack (= 5.2.3)
activesupport (= 5.2.3)
railties (6.0.2.1)
actionpack (= 6.0.2.1)
activesupport (= 6.0.2.1)
method_source
rake (>= 0.8.7)
thor (>= 0.19.0, < 2.0)
rake (12.3.2)
thor (>= 0.20.3, < 2.0)
rake (13.0.1)
rb-fsevent (0.10.3)
rb-inotify (0.10.0)
rb-inotify (0.10.1)
ffi (~> 1.0)
redis (3.3.5)
redis-actionpack (5.0.2)
actionpack (>= 4.0, < 6)
redis-actionpack (5.1.0)
actionpack (>= 4.0, < 7)
redis-rack (>= 1, < 3)
redis-store (>= 1.1.0, < 2)
redis-activesupport (5.0.7)
activesupport (>= 3, < 6)
redis-activesupport (5.2.0)
activesupport (>= 3, < 7)
redis-store (>= 1.3, < 2)
redis-rack (2.0.5)
redis-rack (2.0.6)
rack (>= 1.5, < 3)
redis-store (>= 1.2, < 2)
redis-rails (5.0.2)
......@@ -193,32 +208,31 @@ GEM
redis-store (>= 1.2, < 2)
redis-store (1.6.0)
redis (>= 2.2, < 5)
regexp_parser (1.5.0)
regexp_parser (1.6.0)
ruby-protocol-buffers (1.6.1)
ruby_dep (1.5.0)
rubyzip (1.2.2)
rubyzip (2.0.0)
sass (3.7.4)
sass-listen (~> 4.0.0)
sass-listen (4.0.0)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
sass-rails (5.0.7)
railties (>= 4.0.0, < 6)
sass-rails (5.1.0)
railties (>= 5.2.0)
sass (~> 3.1)
sprockets (>= 2.8, < 4.0)
sprockets-rails (>= 2.0, < 4.0)
tilt (>= 1.1, < 3)
selenium-webdriver (3.142.2)
childprocess (>= 0.5, < 2.0)
rubyzip (~> 1.2, >= 1.2.2)
selenium-webdriver (3.142.6)
childprocess (>= 0.5, < 4.0)
rubyzip (>= 1.2.2)
settingslogic (2.0.9)
sidekiq (4.2.10)
concurrent-ruby (~> 1.0)
connection_pool (~> 2.2, >= 2.2.0)
rack-protection (>= 1.5.0)
redis (~> 3.2, >= 3.2.1)
spring (2.0.2)
activesupport (>= 4.2)
spring (2.1.0)
spring-watcher-listen (2.0.1)
listen (>= 2.7, < 4.0)
spring (>= 1.2, < 3.0)
......@@ -229,29 +243,30 @@ GEM
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
sshkit (1.18.0)
sshkit (1.20.0)
net-scp (>= 1.1.2)
net-ssh (>= 2.8.0)
thor (0.20.3)
thor (1.0.1)
thread_safe (0.3.6)
tilt (2.0.9)
turbolinks (5.2.0)
tilt (2.0.10)
turbolinks (5.2.1)
turbolinks-source (~> 5.2)
turbolinks-source (5.2.0)
tzinfo (1.2.5)
tzinfo (1.2.6)
thread_safe (~> 0.1)
uglifier (4.1.20)
uglifier (4.2.0)
execjs (>= 0.3.0, < 3)
web-console (3.7.0)
actionview (>= 5.0)
activemodel (>= 5.0)
web-console (4.0.1)
actionview (>= 6.0.0)
activemodel (>= 6.0.0)
bindex (>= 0.4.0)
railties (>= 5.0)
websocket-driver (0.7.0)
railties (>= 6.0.0)
websocket-driver (0.7.1)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.3)
websocket-extensions (0.1.4)
xpath (3.2.0)
nokogiri (~> 1.8)
zeitwerk (2.2.2)
PLATFORMS
ruby
......@@ -260,6 +275,7 @@ DEPENDENCIES
bootsnap (>= 1.1.0)
byebug
capistrano (~> 3.11)
capistrano-faster-rails
capistrano-rails (~> 1.4)
capistrano-rvm (~> 0.1.2)
capistrano-sidekiq (~> 1.0, >= 1.0.2)
......@@ -272,9 +288,9 @@ DEPENDENCIES
igetui-ruby
jbuilder (~> 2.5)
listen (>= 3.0.5, < 3.2)
mysql2 (>= 0.3.18, < 0.5)
mysql2 (~> 0.5.3)
puma (~> 3.11)
rails (~> 5.2.2, >= 5.2.2.1)
rails (~> 6.0.0)
rails_param (~> 0.10.2)
redis-rails (~> 5.0, >= 5.0.2)
sass-rails (~> 5.0)
......@@ -289,7 +305,7 @@ DEPENDENCIES
web-console (>= 3.3.0)
RUBY VERSION
ruby 2.6.0p0
ruby 2.6.5p114
BUNDLED WITH
1.17.3
class ApplicationController < ActionController::Base
class ApplicationController < ActionController::Metal
ActionController::API.without_modules(:ForceSSL, :UrlFor).each do |left|
include left
end
include RailsParam::Param
rescue_from Mime::Type::InvalidMimeType, with: :rescue_mime_type
rescue_from StandardError, with: :rescue_all
include TokenValidate
def rescue_all(e)
ErrorLog.error(e)
render json: { code: 500, message: '抱歉~ 系统出错了,攻城狮们已经在修理了!', error: e.class.name.underscore, original_message: e.message }
end
def rescue_mime_type(e)
ErrorLog.error(e)
end
end
module Token
module TokenValidate
extend ActiveSupport::Concern
ACCESS_TOEKN_EXPIRE_TIME = 7200
class << self
def key(app_name)
"push:api:#{app_name}:access_token"
end
def validate_token(app_name, token)
!! (token == get_token(app_name))
end
def token_ttl(app_name)
$redis.ttl(tkey(app_name))
end
def generate_token(app_name)
token = SecureRandom.hex(32)
$redis.set(key(app_name), token, ex: ACCESS_TOEKN_EXPIRE_TIME)
token
end
def generate_token(app_name)
token = SecureRandom.hex(32)
$redis.set(tkey(app_name), token, ex: ACCESS_TOEKN_EXPIRE_TIME)
token
end
def token(app_name)
$redis.get(key(app_name))
end
private
def ttl(app_name)
$redis.ttl(key(app_name))
end
def tkey(app_name)
"push:api:#{app_name}:access_token"
end
def get_token(app_name)
$redis.get(tkey(app_name))
end
end
\ No newline at end of file
class PushsController < ApplicationController
include ActionController::HttpAuthentication::Token
skip_before_action :verify_authenticity_token
def token
param! :app_name, String, required: true
......@@ -9,48 +8,46 @@ class PushsController < ApplicationController
app_setting = Settings.send(params[:app_name].to_sym) rescue {}
if app_setting['app_id'] == params[:app_id] && app_setting['app_secret'] == params[:app_secret]
render json: { code: 0, message: 'success', token: Token.generate_token(params[:app_name]), ttl: Token.ttl(params[:app_name])}
render json: { code: 0, message: 'success', token: generate_token(params[:app_name]), ttl: token_ttl(params[:app_name])}
else
render json: { code: -1, message: '应用不存在或者app_id/app_secret不匹配'}
end
end
# app_name 应用名称
# user_device_ids 设备ids
# message 推送信息的json 字符串
# igetui_opts 个推推送的额外选项
def push
param! :app_name, String, required: true
param! :device_ids_opts, String, required: true
def push_v2
param! :app_name, String, required: true, in: %w(crm)
# param! :device_ids_opts, String, required: true
param! :message, String, required: true
param! :igetui_opts, String
param! :app_type, String
param! :sync_push, String
# param! :igetui_opts, String
param! :sync_push, :boolean
param! :user_ids, Array, required: true
igetui_opts = JSON.parse(params[:igetui_opts]) rescue {}
message = JSON.parse(params[:message]) rescue {}
device_ids_opts = JSON.parse(params[:device_ids_opts]) rescue {}
token = token_and_options(request).first
if token == Token.token(params[:app_name])
# 写入记录
NotificationStatistic.create_by_params(igetui_opts, message, device_ids_opts, params[:app_type])
igetui_opts = message
user_ids = params[:user_ids] rescue []
user_device_exist = UserDevice.where(user_id: user_ids).exists?
unless user_device_exist
return render json: { code: -1, message: 'user_device找不到,user_ids错误'}
end
token_array = token_and_options(request)
if token_array.blank?
return render json: { code: 401, message: 'token错误'}
end
params[:sync_push] ||= false
if validate_token(params[:app_name], token_array.first)
push_sync(params[:sync_push], {user_ids: user_ids, message: message, igetui_opts: igetui_opts.merge(pusher_type: 'push_message_to_list')})
if params.has_key?(:sync_push)
timeout_seconds = $redis.get('push_timeout').to_i
if timeout_seconds > 0
Timeout.timeout(timeout_seconds) {
::PushWorker.new.perform(device_ids_opts, message, igetui_opts, params[:app_type])
}
else
::PushWorker.new.perform(device_ids_opts, message, igetui_opts, params[:app_type])
end
else
::PushWorker.perform_async(device_ids_opts, message, igetui_opts, params[:app_type])
end
render json: { code: 0, message: 'success', describe: '异步任务正在处理'}
else
render json: { code: -1, message: 'token 错误/过期'}
render json: { code: 401, message: 'token 错误/过期'}
end
end
def received
......@@ -65,4 +62,50 @@ class PushsController < ApplicationController
render json: { code: 0, message: "success" }
end
def push
param! :app_name, String, required: true
param! :device_ids_opts, String, required: true
param! :message, String, required: true
param! :sync_push, :boolean
param! :igetui_opts, String
param! :app_type, String
igetui_opts = JSON.parse(params[:igetui_opts]) rescue {}
message = JSON.parse(params[:message]) rescue {}
device_ids_opts = JSON.parse(params[:device_ids_opts]) rescue {}
token_array = token_and_options(request)
if token_array.blank?
return render json: { code: 401, message: 'token错误'}
end
if validate_token(params[:app_name], token_array.first)
params[:sync_push] ||= false
push_sync(params[:sync_push], {device_ids_opts: device_ids_opts, message: message, app_type: params[:app_type], igetui_opts: igetui_opts.merge(pusher_type: 'push_message_to_list')})
NotificationStatistic.create_by_params(igetui_opts, message, device_ids_opts, params[:app_type])
render json: { code: 0, message: 'success', data: {remind: "请使用新的api,此api近期将不再维护,请尽快迁移到新的api,新api地址 http://apidoc.weiwenjia.com/docs/internal-dev-api/internal-dev-api-1boq6ctdm8m57"}}
else
render json: { code: 401, message: 'token 错误/过期'}
end
end
private
def push_sync(sync_push, opts={})
if sync_push
timeout_seconds = $redis.get('push_timeout').to_i
if timeout_seconds > 0
Timeout.timeout(timeout_seconds) {
::PushWorker.new.perform(opts)
}
else
::PushWorker.new.perform(opts)
end
else
::PushWorker.perform_async(opts)
end
end
end
class UserDevicesController < ApplicationController
def create
param! :app_type, String, required: true, in: UserDevice::app_types.keys
param! :client_id, String, required: true
param! :user_id, Integer, required: true
_user_device_params = permit_user_device_params
_user_device_params[:platform] ||= 'igetui'
user_id = _user_device_params[:user_id]
UserDevice.where(user_id: user_id).delete_all
user_device = UserDevice.create!(_user_device_params)
render json: { code: 0, message: "success", data: { user_device: user_device } }
end
def update_by_user_id
param! :old_user_id, Integer, required: true
param! :user_id, Integer, required: true
param! :organization_id, Integer, required: true
user_id = params[:user_id]
old_user_id = params[:old_user_id]
user_device = UserDevice.where(user_id: old_user_id).last
if user_device.present?
UserDevice.where(user_id: user_id).delete_all
UserDevice.where(user_id: old_user_id).delete_all
new_user_device = user_device.dup
new_user_device.update(
user_id: user_id,
organization_id: params[:organization_id],
created_at: Time.now,
updated_at: Time.now
)
end
render json: { code: 0, message: "success" }
end
def destroy_by_user_id
param! :user_id, Integer, required: true
user_id = params[:user_id]
UserDevice.where(user_id: user_id).delete_all
render json: { code: 0, message: "success" }
end
private
def permit_user_device_params
params.permit(:platform, :device_token, :client_id, :device_model, :device_platform,
:device_id, :device_version, :device_phone, :app_type, :user_id, :organization_id, :ip)
end
end
......@@ -36,4 +36,29 @@ class NotificationStatistic < ApplicationRecord
e.backtrace.each { |l| Rails.logger.info l }
end
def self.static_notification(opts, client_ids, platform, device_platform=nil)
::Log.info("统计数据开始 opts is #{opts.to_json} client_ids is #{client_ids} platform is #{platform} device_platform is #{device_platform}")
if client_ids.is_a? Array
client_ids.each do |client_id|
next if opts[:message][:notifiable_id].blank?
NotificationStatistic.create(
organization_id: opts[:igetui_opts][:organization_id],
user_id: opts[:igetui_opts][:user_id],
notification_id: opts[:message][:notifiable_id],
client_id: client_id,
platform: platform,
device_platform: device_platform,
app_type: opts[:app_type],
ip: opts[:igetui_opts][:ip],
)
end
end
rescue => e
::Log.info "exception is #{e}"
e.backtrace.each { |l| ::Log.error l }
end
end
class UserDevice < ApplicationRecord
# 当前app端传递的platform的值:
# android: igetui, xiaomi, huawei
# iso: igetui 目前还不清楚为啥不用apns,暂时不修改
enum platform: %i[igetui apns xiaomi huawei]
enum device_platform: %i[ios android]
# 用于区分当前的应用,为了推送准备, 因为推送需要根据不同的应用使用不同的 id,secret等。
enum app_type: %i[ik_duli lx_duli lx_yun aike_yun]
end
\ No newline at end of file
module Push
module Huawei
ACCESS_TOKEN_KEY = "push:huawei_push:access_token".freeze
module Huawei
class Pusher
ACCESS_TOKEN_KEY_PREFIX = "push:huawei_push:access_token".freeze
TOKEN_URL = 'https://login.cloud.huawei.com/oauth2/v2/token'.freeze
PUSH_URL = 'https://api.push.hicloud.com/pushsend.do'.freeze
ACCESS_TOEKN_EXPIRE_TIME = 3500
BATCH_PUSH_MAX = 80
def initialize(device_ids, message, app_type)
@device_tokens = device_ids
@message = message
@app_type = app_type
@uuid = Random.uuid.to_s
end
def access_token_key
ACCESS_TOKEN_KEY_PREFIX + @app_type.to_s
end
# 4a7d376b47c847634571a86b37e93272 测试使用的device_token
def perform
device_tokens = @device_tokens
message = @message
class << self
# 4a7d376b47c847634571a86b37e93272 测试使用的device_token
def push(device_tokens, message)
handle_token_res if access_token.blank?
device_tokens.each_slice(BATCH_PUSH_MAX) do |device_token_array|
res = res_push(message, device_token_array)
# 容错处理,华为的token异常问题,重新获取发送。
if %w(80300002 80200001).include? res['code']
handle_token_res
res_push(message, device_token_array)
end
handle_token_res if access_token.blank?
device_tokens.each_slice(BATCH_PUSH_MAX) do |device_token_array|
res = res_push(message, device_token_array)
# 容错处理,华为的token异常问题,重新获取发送。
if %w(80300002 80200001).include? res['code']
handle_token_res
res_push(message, device_token_array)
end
rescue StandardError => err
Push::Log.error(err)
end
rescue StandardError => err
::Log.error(err)
end
def res_push(message, device_tokens)
body = message(message, device_tokens)
def res_push(message, device_tokens)
body = message(message, device_tokens)
nsp_ctx = {
ver: '1',
appId: Settings.platform_settings.huawei['app_id']
}
url = PUSH_URL + "?nsp_ctx=#{CGI::escape(nsp_ctx.to_json)}"
post(url, body)
end
nsp_ctx = {
ver: '1',
appId: Settings.send(@app_type).huawei['app_id']
}
url = PUSH_URL + "?nsp_ctx=#{CGI::escape(nsp_ctx.to_json)}"
post(url, body)
end
# 推送信息
def message(message, device_tokens)
payload = {
hps: {
msg: {
type: 1,
body: message
}
# 推送信息
def message(message, device_tokens)
payload = {
hps: {
msg: {
type: 1,
body: message
}
}
Push::Log.info("huawei_payload: #{payload}, device_tokens: #{device_tokens}")
params = {
access_token: CGI.escape(access_token),
nsp_svc: CGI.escape('openpush.message.api.send'),
nsp_ts: CGI.escape(Time.now.to_i.to_s),
device_token_list: CGI.escape(device_tokens.to_s),
payload: CGI.escape(payload.to_json)
}
params_str = ''
params.each_with_index do |(key,value), index|
params_str += "#{key}=#{value}"
params_str += '&' if index + 1 < params.size
end
params_str
}
::Log.info("huawei_payload: #{payload}, device_tokens: #{device_tokens}", @uuid)
params = {
access_token: CGI.escape(access_token),
nsp_svc: CGI.escape('openpush.message.api.send'),
nsp_ts: CGI.escape(Time.now.to_i.to_s),
device_token_list: CGI.escape(device_tokens.to_s),
payload: CGI.escape(payload.to_json)
}
params_str = ''
params.each_with_index do |(key,value), index|
params_str += "#{key}=#{value}"
params_str += '&' if index + 1 < params.size
end
def handle_token_res
loop do
res = req_token
if res['error'].blank? && res['access_token'].present?
$redis.set(ACCESS_TOKEN_KEY, res['access_token'], ex: ACCESS_TOEKN_EXPIRE_TIME)
break
end
params_str
end
def handle_token_res
loop do
res = req_token
if res['error'].blank? && res['access_token'].present?
$redis.set(access_token_key, res['access_token'], ex: ACCESS_TOEKN_EXPIRE_TIME)
break
end
end
end
def req_token
body = {
grant_type: 'client_credentials',
client_id: Settings.platform_settings.huawei['app_id'],
client_secret: Settings.platform_settings.huawei['app_secret']
}
post(TOKEN_URL, body)
end
def req_token
client_id = Settings.send(@app_type).huawei['app_id']
client_secret = Settings.send(@app_type).huawei['app_secret']
def access_token
$redis.get(ACCESS_TOKEN_KEY)
end
body = {
grant_type: 'client_credentials',
client_id: client_id,
client_secret: client_secret
}
post(TOKEN_URL, body)
end
def post(url, body)
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
response = HTTParty.post(url, body: body, headers: headers, timeout: 5)
Push::Log.info("huawei_push: \n access_token: #{access_token} expire_time: #{$redis.ttl(Push::Huawei::ACCESS_TOKEN_KEY)}\n url: #{url}\n body: #{body}\n response: #{response}")
JSON.parse(response.body)
end
def access_token
$redis.get(access_token_key)
end
def post(url, body)
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
response = HTTParty.post(url, body: body, headers: headers, timeout: 5)
::Log.info("huawei_push: \n access_token: #{access_token} expire_time: #{$redis.ttl(access_token_key)}\n url: #{url}\n body: #{body}\n response: #{response}", @uuid)
JSON.parse(response.body)
end
end
end
module Igetui
class Pusher
def initialize(user_device_ids, opts)
opts = HashWithIndifferentAccess.new(opts)
@template_data = opts[:message]
@igetui_opts = opts[:igetui_opts]
@user_device_ids = user_device_ids
@pusher = pusher(opts[:device_platform], opts[:app_type])
@pusher_type = @igetui_opts[:pusher_type]
@uuid = Random.uuid.to_s
end
def perform
@template_data[:push_type] ||= 2
@igetui_opts[:transmission_type] ||= 0
@igetui_opts[:transmission_content] = @template_data.as_json
template_type = 'TransmissionTemplate'
template_data = @igetui_opts
result = push_message_to(@pusher, @pusher_type, template_type, template_data, @user_device_ids)
::Log.info("igetui_push: \n template_data: #{template_data}\n user_device_ids: #{@user_device_ids}\n response: #{result}", @uuid)
end
private
def pusher(device_platform, app_type)
case app_type
when 'lx_duli'
device_platform == 'android' ? $lx_duli_android_pusher : $lx_duli_ios_pusher
when 'lx_yun'
device_platform == 'android' ? $lx_yun_android_pusher : $lx_yun_ios_pusher
when 'aike_yun'
device_platform == 'android' ? $aike_yun_android_pusher : $aike_yun_ios_pusher
else 'ik_duli'
device_platform == 'android' ? $ik_duli_android_pusher : $ik_duli_ios_pusher
end
end
def push_message_to(pusher, pusher_type, template_type, template_data, client_id)
client_id_list = Array(client_id)
template = set_template_data(template_type, template_data)
case pusher_type
when 'push_message_to_single'
message = IGeTui::SingleMessage.new
message.data = template
client_id_list.map do |client_id|
client = IGeTui::Client.new(client_id)
res = pusher.push_message_to_single(message, client)
::Log.info(" push_message_to_single client: #{client.to_json} and message is #{message.to_json} and res is #{res}", @uuid)
end
when 'push_message_to_list'
message = IGeTui::ListMessage.new
message.data = template
content_id = pusher.get_content_id(message)
clients = client_id_list.map { |client_id| IGeTui::Client.new(client_id) }
res = pusher.push_message_to_list(content_id, clients)
::Log.info("push_message_to_list clients: #{clients.to_json} and message is #{message.to_json} and res is #{res}", @uuid)
when 'push_message_to_app'
message = IGeTui::AppMessage.new
message.data = template
message.app_id_list = client_id_list
res = pusher.push_message_to_app(message)
::Log.info("push_message_to_app message is #{message.to_json} and res is #{res}", @uuid)
end
end
def set_template_data(template_type, template_data)
@template ||= "IGeTui::#{template_type}".constantize.new
case template_type
when 'NotificationTemplate', 'NotyPopLoadTemplate', 'LinkTemplate'
template_data.reverse_merge!(Settings.platform_settings.igetui['template_base'])
template_data.each do |k, v|
@template.send("#{k}=", v)
end
@template.set_push_info(*template_data[:push_info]) if template_data.key? :push_info
when 'TransmissionTemplate'
@template.transmission_content = template_data[:transmission_content].is_a?(Hash) ? template_data[:transmission_content].to_json : template_data[:transmission_content]
@template.transmission_type = template_data[:transmission_type] if template_data.key?(:transmission_type)
@template.set_push_info(*template_data[:push_info]) if template_data.key? :push_info
end
@template
end
end
end
module Push
class << self
# 调用推送服务,推送信息
# message 要推送的具体信息
# opts 是hash类型,主要是一些其他的信息。
# 由于历史遗留问题,封装的不够好,这里主要用来处理个推的一些参数。
# 目前华为推送,小米推送不会用到这里的信息。
# device_ids_opts, 用户设备信息是hash数组。
# device_ids_opts = {
# igetui: [],
# apns: [],
# xiaomi: [],
# huawei: []
# }
def push(device_ids_opts, message, igetui_opts = {}, app_type = nil)
Settings.platform = app_type || Settings::DEFAULT
Push::Log.info("*************** push_service ***************:\n device_ids_opts: #{device_ids_opts}, message: #{message}, igetui_opts: #{igetui_opts} platform: #{Settings.platform}")
message = message.with_indifferent_access
igetui_opts = igetui_opts.with_indifferent_access
# igetui
Push::Igetui.push(device_ids_opts['igetui'], message, igetui_opts) if device_ids_opts['igetui'].present?
Push::Igetui.push(device_ids_opts['apns'], message, igetui_opts) if device_ids_opts['apns'].present?
# xiaomi
# https://dev.mi.com/console/doc/detail?pId=1163 文档中心
Push::Xiaomi.push(device_ids_opts['xiaomi'], message) if device_ids_opts['xiaomi'].present?
# huawei
# https://developer.huawei.com/consumer/cn/service/hms/catalog/huaweipush_agent.html?page=hmssdk_huaweipush_api_reference_agent_s1 接入文档
Push::Huawei.push(device_ids_opts['huawei'], message) if device_ids_opts['huawei'].present?
# etc
rescue StandardError => err
Push::Log.error(err)
end
end
end
module Push
module Igetui
class << self
def push(user_device_ids, template_data = {}, opts = {})
# 包装成igetui 真正需要的参数格式
opts[:transmission_content] = template_data
if user_device_ids.size > 1
push_transmission_to_list_igetui(user_device_ids, opts)
else
push_transmission_to_igetui(user_device_ids, opts)
end
rescue StandardError => err
::Push::Log.error(err)
end
def config
{
push_type: 2
}
end
def push_transmission_to_igetui(user_device_id, template_data = {})
template_data = handle_template_data(template_data)
push_igetui_with_asnyc(
user_device_id,
template_data,
template_type: 'TransmissionTemplate'
)
end
def push_transmission_to_list_igetui(user_device_ids, template_data = {})
template_data = handle_template_data(template_data)
push_list_igetui_with_asnyc(
user_device_ids,
template_data,
template_type: 'TransmissionTemplate', pusher_type: 'push_message_to_list'
)
end
private
def handle_template_data(template_data)
template_data = HashWithIndifferentAccess.new(template_data)
transmission_content = HashWithIndifferentAccess.new(template_data.delete(:transmission_content))
transmission_content[:push_type] ||= config[:push_type]
template_data[:transmission_type] ||= 0
template_data[:transmission_content] = transmission_content.as_json
template_data
end
def push_igetui_with_asnyc(user_device_id, template_data = {}, opts = nil)
return if template_data.blank?
opts ||= HashWithIndifferentAccess.new(template_type: 'TransmissionTemplate')
template_data = HashWithIndifferentAccess.new(template_data)
perform(template_data, opts, user_device_id)
end
def push_list_igetui_with_asnyc(user_device_ids, template_data = {}, opts = { pusher_type: 'push_message_to_list' })
return if user_device_ids.blank? || template_data.blank?
opts ||= HashWithIndifferentAccess.new(template_type: 'TransmissionTemplate')
perform(template_data, opts, user_device_ids)
end
def perform(template_data, opts, user_device_ids)
opts = HashWithIndifferentAccess.new(opts)
igetui = Igetui::Push.new(template_data, opts)
result = igetui.push_message_to(user_device_ids)
::Push::Log.info("igetui_push: \n template_data: #{template_data}\n opts: #{opts}\n user_device_ids: #{user_device_ids}\n response: #{result}")
end
end
end
end
\ No newline at end of file
module Push
module Igetui
class Push
attr_accessor :pusher, :pusher_type, :template_type, :template, :template_data
PUSHERTYPES = %w[push_message_to_single push_message_to_list push_message_to_app].freeze
TEMPLATETYPES = %w[LinkTemplate NotificationTemplate TransmissionTemplate NotyPopLoadTemplate].freeze
DEVICEPLATFORMS = %w[android ios].freeze
def initialize(template_data, opts = {})
opts = HashWithIndifferentAccess.new(opts)
@template_data = HashWithIndifferentAccess.new(template_data || {})
@pusher_type = PUSHERTYPES.include?((opts[:pusher_type]).to_s) ? opts[:pusher_type] : 'push_message_to_single'
@template_type = TEMPLATETYPES.include?((opts[:template_type]).to_s) ? opts[:template_type] : 'NotificationTemplate'
::Push::Log.info("@template_data is #{@template_data.to_json}")
set_message
set_template_data
@message.data = @template
end
def push_message_to(client_id)
client_id_list = Array(client_id)
case pusher_type
when 'push_message_to_single'
client_id_list.map do |client_id|
client = IGeTui::Client.new(client_id)
pusher.push_message_to_single(@message, client)
end
when 'push_message_to_list'
content_id = pusher.get_content_id(@message)
clients = client_id_list.map { |client_id| IGeTui::Client.new(client_id) }
pusher.push_message_to_list(content_id, clients)
when 'push_message_to_app'
@message.app_id_list = client_id_list
pusher.push_message_to_app(@message)
end
end
private
def pusher
@pusher ||=
if DEVICEPLATFORMS.include?((@template_data['device_platform'].to_s))
case @template_data['device_platform'].to_s
when 'android'
IGeTui.pusher(
Settings.platform_settings.igetui.android['app_id'],
Settings.platform_settings.igetui.android['app_key'],
Settings.platform_settings.igetui.android['master_secret']
)
when 'ios'
IGeTui.pusher(
Settings.platform_settings.igetui.ios['app_id'],
Settings.platform_settings.igetui.ios['app_key'],
Settings.platform_settings.igetui.ios['master_secret']
)
end
else
::Push::Log.info("设备类型不正确#{@device_platform}")
raise "Failed to create pusher"
end
end
def set_message
@message = case pusher_type
when 'push_message_to_single'
IGeTui::SingleMessage.new
when 'push_message_to_list'
IGeTui::ListMessage.new
when 'push_message_to_app'
IGeTui::AppMessage.new
end
end
def set_template_data
@template = "IGeTui::#{template_type}".constantize.new
case template_type
when 'NotificationTemplate', 'NotyPopLoadTemplate', 'LinkTemplate'
@template_data.reverse_merge!(Settings.platform_settings.igetui['template_base'])
@template_data.each do |k, v|
@template.send("#{k}=", v)
end
@template.set_push_info(*@template_data[:push_info]) if @template_data.key? :push_info
when 'TransmissionTemplate'
@template.transmission_content = @template_data[:transmission_content].is_a?(Hash) ? @template_data[:transmission_content].to_json : @template_data[:transmission_content]
@template.transmission_type = @template_data[:transmission_type] if @template_data.key?(:transmission_type)
@template.set_push_info(*@template_data[:push_info]) if @template_data.key? :push_info
end
end
end
end
end
#push功能的代理选择用哪种推送工具1.个推 2.小米 3.华为
class PushToolClient
def initialize(opts={})
opts = HashWithIndifferentAccess.new(opts)
@user_ids = opts[:user_ids]
@opts = opts
end
def do_push
# Settings.platform = @opts[:app_type] || Settings::DEFAULT
igetui_android_client_ids, igetui_ios_client_ids, xiaomi_client_ids, huawei_client_ids = fetch_client_ids_group
if igetui_android_client_ids.present?
igetui_android_client_ids.each_pair do |app_type, ids|
Igetui::Pusher.new(ids, @opts.merge(device_platform: 'android', app_type: app_type)).perform
NotificationStatistic.static_notification(@opts.merge(app_type: app_type), ids,'igetui', 'android' )
end
end
if igetui_ios_client_ids.present?
igetui_ios_client_ids.each_pair do |app_type, ids|
Igetui::Pusher.new(ids, @opts.merge(device_platform: 'ios', app_type: app_type)).perform
NotificationStatistic.static_notification(@opts.merge(app_type: app_type), ids,'igetui', 'ios' )
end
end
#现在好像不用了
# Push::IgetuiIos.push(@push_collections[:igetui_ios], @opts) if @push_collections[:apns].present?
# Push::IgetuiAndroid.push(@push_collections[:igetui_android], @opts) if @push_collections[:apns].present?
if xiaomi_client_ids.present?
xiaomi_client_ids.each_pair do |app_type, ids|
message = @opts[:message].merge(@opts[:message][:transmission_content] || {})
Xiaomi::Pusher.new(ids, message, app_type).perform
NotificationStatistic.static_notification(@opts.merge(app_type: app_type), ids,'xiaomi')
end
end
if huawei_client_ids.present?
huawei_client_ids.each_pair do |app_type, ids|
message = @opts[:message].merge(@opts[:message][:transmission_content] || {})
Huawei::Pusher.new(ids, message, app_type).perform
NotificationStatistic.static_notification(@opts.merge(app_type: app_type), ids,'huawei')
end
end
end
def fetch_client_ids_group
igetui_android_client_ids = {}; igetui_ios_client_ids = {}; xiaomi_client_ids = {}; huawei_client_ids = {}
if (@opts[:device_ids_opts].is_a? Hash) && @user_ids.blank? && @opts[:app_type].present?
push_devices = @opts[:device_ids_opts].keys.map(&:to_s)
if push_devices.include? "igetui"
igetui_android_client_ids = {"#{@opts[:app_type]}" => @opts[:device_ids_opts][:igetui]} if @opts[:igetui_opts][:device_platform] == 'android'
igetui_ios_client_ids = {"#{@opts[:app_type]}" =>@opts[:device_ids_opts][:igetui]} if @opts[:igetui_opts][:device_platform] == 'ios'
end
huawei_client_ids = {"#{@opts[:app_type]}" => @opts[:device_ids_opts][:huawei]} if push_devices.include? "huawei"
xiaomi_client_ids = {"#{@opts[:app_type]}" => @opts[:device_ids_opts][:xiaomi]} if push_devices.include? "xiaomi"
else
push_device_collections = UserDevice.where(user_id: @user_ids).group_by(&:platform)
igetui_push_device_collections = push_device_collections['igetui'].group_by(&:device_platform) if push_device_collections['igetui'].is_a? Array
if igetui_push_device_collections.is_a? Hash
if igetui_push_device_collections['android'].is_a? Array
igetui_app_type_group = igetui_push_device_collections['android'].group_by(&:app_type)
igetui_app_type_group.each_pair{|k,v| igetui_android_client_ids.merge!("#{k}"=> v.map(&:client_id))}
end
if igetui_push_device_collections['ios'].is_a? Array
igetui_app_type_group = igetui_push_device_collections['ios'].group_by(&:app_type)
igetui_app_type_group.each_pair{|k,v| igetui_ios_client_ids.merge!("#{k}"=> v.map(&:client_id))}
end
end
if push_device_collections['xiaomi'].is_a? Array
xiaomi_client_group = push_device_collections['xiaomi'].group_by(&:app_type)
xiaomi_client_group.each_pair{|k,v| xiaomi_client_ids.merge!("#{k}"=> v.map(&:client_id))}
end
if push_device_collections['huawei'].is_a? Array
huawei_client_ids = push_device_collections['huawei'].group_by(&:app_type)
huawei_client_ids.each_pair{|k,v| huawei_client_ids.merge!("#{k}"=> v.map(&:client_id))}
end
end
[igetui_android_client_ids, igetui_ios_client_ids, xiaomi_client_ids, huawei_client_ids]
end
end
\ No newline at end of file
module Push
module Xiaomi
module Xiaomi
class Pusher
PUSH_URL = 'https://api.xmpush.xiaomi.com/v3/message/regid'.freeze
BATCH_PUSH_MAX = 80
class << self
def initialize(device_ids, message, app_type)
@registration_ids = device_ids
@payload = message
@app_type = app_type
@uuid = Random.uuid.to_s
end
def push(registration_ids, payload)
registration_ids.each_slice(BATCH_PUSH_MAX) do |registration_ids_array|
registration_id = registration_ids_array.join(',')
post(message(payload, registration_id))
end
rescue StandardError => err
Push::Log.error(err)
end
def perform
registration_ids = @registration_ids
payload = @payload
def message(payload, registration_id)
message = config
message[:registration_id] = registration_id
message[:payload] = payload.to_json
message
registration_ids.each_slice(BATCH_PUSH_MAX) do |registration_ids_array|
registration_id = registration_ids_array.join(',')
post(message(payload, registration_id))
end
rescue StandardError => err
::Log.error(err)
end
# notify_type
# DEFAULT_ALL = -1;
# DEFAULT_SOUND = 1; // 使用默认提示音提示;
# DEFAULT_VIBRATE = 2; // 使用默认震动提示;
# DEFAULT_LIGHTS = 4; // 使用默认led灯光提示;
def message(payload, registration_id)
message = config
message[:registration_id] = registration_id
message[:payload] = payload.to_json
message
end
# pass_through
# 0 表示通知栏消息, 1 表示透传消息
def config
{
restricted_package_name: Settings.platform_settings.xiaomi['package_name'],
pass_through: 1,
title: 'xiaomi push',
description: 'xiaomi push',
notify_type: 1
}
end
# notify_type
# DEFAULT_ALL = -1;
# DEFAULT_SOUND = 1; // 使用默认提示音提示;
# DEFAULT_VIBRATE = 2; // 使用默认震动提示;
# DEFAULT_LIGHTS = 4; // 使用默认led灯光提示;
def post(params)
response = HTTParty.post(PUSH_URL, query: params,
headers: {
'Accept' => 'application/json;',
"Authorization": "key=#{Settings.platform_settings.xiaomi['app_secret']}"
},
timeout: 5)
Push::Log.info("xiaomi_push: \n url: #{PUSH_URL}\n params: #{params}\n response: #{response}")
response
end
# pass_through
# 0 表示通知栏消息, 1 表示透传消息
def config
restricted_package_name = Settings.send(@app_type).xiaomi['package_name']
{
restricted_package_name: restricted_package_name,
pass_through: 1,
title: 'xiaomi push',
description: 'xiaomi push',
notify_type: 1
}
end
def post(params)
key = Settings.send(@app_type).xiaomi['app_secret']
response = HTTParty.post(PUSH_URL, query: params,
headers: {
'Accept' => 'application/json;',
"Authorization": "key=#{key}"
},
timeout: 5)
::Log.info("xiaomi_push: \n url: #{PUSH_URL}\n params: #{params}\n response: #{response}", @uuid)
response
end
end
end
......@@ -2,8 +2,9 @@ class PushWorker
include Sidekiq::Worker
sidekiq_options queue: :push
def perform(device_ids_opts, message, igetui_opts, platform = nil)
Push.push(device_ids_opts, message, igetui_opts, platform)
def perform(opts)
::PushToolClient.new(opts).do_push
# Push.push(user_ids, message, igetui_opts, platform)
rescue StandardError => e
ErrorLog.error(e)
end
......
......@@ -9,7 +9,7 @@ Bundler.require(*Rails.groups)
module AppPush
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
config.load_defaults 6.0
require_relative '../app/services/settings'
# Settings in config/environments/* take precedence over those specified here.
......@@ -34,5 +34,6 @@ module AppPush
config.active_job.queue_adapter = :sidekiq
config.api_only = true
end
end
default: &default
adapter: mysql2
encoding: utf8
pool: 3
host: rm-m5ef10gzq1n5e7b9abo.mysql.rds.aliyuncs.com
username: crm_dev
password: 4LwSJlWiM9Krlb8g
username: crm_rw
password: pHB+!*Uv9Rl9
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
<<: *default
database: crm_dev
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: db/test.sqlite3
production:
<<: *default
database: crm_dev
\ No newline at end of file
database: db/production.sqlite3
......@@ -8,9 +8,11 @@ set :god_sidekiq_group, 'push_service'
# 当前服务器有app 这个角色。
# gem capistrano-sidekiq 默认值 set :sidekiq_roles, fetch(:sidekiq_role, :app)
# 因此会造成执行cap sidekiq:start,但是生产环境因为使用了god,不需要执行这个任务
set :sidekiq_roles, 'sidekiq' #生产环境没有这个角色。
set :sidekiq_roles, :sidekiq #生产环境没有这个角色。
set :puma_role, 'app'
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
set :sidekiq_default_hooks, true
set :pty, false
set :linked_files, %w[
config/credentials.yml.enc
......@@ -67,12 +69,15 @@ namespace :deploy do
end
end
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
invoke 'sidekiq:god_restart'
end
end
# desc 'Restart application'
# task :restart do
# on roles(:app), in: :sequence, wait: 5 do
# # invoke 'sidekiq:god_restart'
# puts "restart sidekiq."
# invoke 'sidekiq:restart'
# sleep 10
# end
# end
before :starting, :check_revision
after :finishing, :compile_assets
after :finishing, :restart
......
......@@ -12,11 +12,13 @@ set :rails_env, :production
set :port, 40022
set :repo_url, 'ssh://gitlab@gitlab.ikcrm.com:40022/ikcrm_server/app_push.git'
set :application, 'app_push'
set :rvm_ruby_version, '2.6.5'
set :deploy_to, deploy_config['deploy_to']
set :shared_path, -> { fetch(:deploy_to) + '/shared' }
# Don't change these unless you know what you're doing
set :pty, true
set :pty, false
set :use_sudo, false
set :stage, :production
set :deploy_via, :remote_cache
......
......@@ -2,7 +2,7 @@ require 'json'
file = File.read("config/server.json")
deploy_config = JSON.parse(file)
branch = deploy_config['branch'] || 'master'
branch = 'master'
set :branch, branch
append :linked_files, 'config/server.json'
......@@ -12,6 +12,7 @@ set :rails_env, :production
set :port, 40022
set :repo_url, 'ssh://gitlab@gitlab.ikcrm.com:40022/ikcrm_server/app_push.git'
set :application, 'app_push'
set :rvm_ruby_version, '2.6.5'
set :deploy_to, deploy_config['deploy_to']
set :shared_path, -> { fetch(:deploy_to) + '/shared' }
......
......@@ -12,6 +12,8 @@ set :rails_env, :production
set :port, 40022
set :repo_url, 'ssh://gitlab@gitlab.ikcrm.com:40022/ikcrm_server/app_push.git'
set :application, 'app_push'
set :rvm_ruby_version, '2.6.5'
set :deploy_to, deploy_config['deploy_to']
set :shared_path, -> { fetch(:deploy_to) + '/shared' }
......
......@@ -58,5 +58,5 @@ Rails.application.configure do
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
......@@ -64,6 +64,7 @@ Rails.application.configure do
# config.active_job.queue_name_prefix = "app_push_#{Rails.env}"
config.action_mailer.perform_caching = false
config.active_record.cache_versioning = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
......
module Push
module Log
class << self
def info(info)
logger.tagged(Time.zone.now) { logger.info info }
end
module Log
class << self
def info(info, uuid= Random.uuid.to_s)
logger.tagged(uuid + " " + Time.zone.now.to_s) { logger.info info }
end
def error(e)
logger.tagged(Time.zone.now) { logger.error e.message.to_s }
e.backtrace.each { |message| logger.tagged(Time.zone.now) { logger.error message.to_s } }
end
def error(e)
logger.tagged(Time.zone.now) { logger.error e.message.to_s }
e.backtrace.each { |message| logger.tagged(Time.zone.now) { logger.error message.to_s } }
end
private
private
def logger
@logger ||= ActiveSupport::TaggedLogging.new(::Logger.new("#{Rails.root}/log/various_push.log", 'weekly'))
end
def logger
@logger ||= ActiveSupport::TaggedLogging.new(::Logger.new("#{Rails.root}/log/various_push.log", 'weekly'))
end
end
end
end
\ No newline at end of file
$ik_duli_android_pusher ||=
IGeTui.pusher(
Settings.ik_duli.igetui.android['app_id'],
Settings.ik_duli.igetui.android['app_key'],
Settings.ik_duli.igetui.android['master_secret']
)
$ik_duli_ios_pusher ||=
IGeTui.pusher(
Settings.ik_duli.igetui.ios['app_id'],
Settings.ik_duli.igetui.ios['app_key'],
Settings.ik_duli.igetui.ios['master_secret']
)
$lx_duli_android_pusher ||=
IGeTui.pusher(
Settings.lx_duli.igetui.android['app_id'],
Settings.lx_duli.igetui.android['app_key'],
Settings.lx_duli.igetui.android['master_secret']
)
$lx_duli_ios_pusher ||=
IGeTui.pusher(
Settings.lx_duli.igetui.ios['app_id'],
Settings.lx_duli.igetui.ios['app_key'],
Settings.lx_duli.igetui.ios['master_secret']
)
$lx_yun_android_pusher ||=
IGeTui.pusher(
Settings.lx_yun.igetui.android['app_id'],
Settings.lx_yun.igetui.android['app_key'],
Settings.lx_yun.igetui.android['master_secret']
)
$lx_yun_ios_pusher ||=
IGeTui.pusher(
Settings.lx_yun.igetui.ios['app_id'],
Settings.lx_yun.igetui.ios['app_key'],
Settings.lx_yun.igetui.ios['master_secret']
)
$aike_yun_android_pusher ||=
IGeTui.pusher(
Settings.aike_yun.igetui.android['app_id'],
Settings.aike_yun.igetui.android['app_key'],
Settings.aike_yun.igetui.android['master_secret']
)
$aike_yun_ios_pusher ||=
IGeTui.pusher(
Settings.aike_yun.igetui.ios['app_id'],
Settings.aike_yun.igetui.ios['app_key'],
Settings.aike_yun.igetui.ios['master_secret']
)
require 'json'
file = File.read('config/server.json')
deploy_config = JSON.parse(file)
port deploy_config['http_port']
environment 'production'
workers 2
threads 0, 16
bind "unix://#{deploy_config['deploy_to']}/shared/tmp/sockets/push-puma.sock"
pidfile "#{deploy_config['deploy_to']}/shared/tmp/pids/puma.pid"
state_path "#{deploy_config['deploy_to']}/shared/tmp/pids/puma.state"
stdout_redirect "#{deploy_config['deploy_to']}/current/log/puma_error.log", "#{deploy_config['deploy_to']}/current/log/puma_access.log", true
plugin :tmp_restart
unless ENV['RAILS_ENV'] == 'development'
file = File.read('config/server.json')
deploy_config = JSON.parse(file)
port deploy_config['http_port']
environment 'production'
workers 4
threads 0, 16
bind "unix://#{deploy_config['deploy_to']}/shared/tmp/sockets/push-puma.sock"
pidfile "#{deploy_config['deploy_to']}/shared/tmp/pids/puma.pid"
state_path "#{deploy_config['deploy_to']}/shared/tmp/pids/puma.state"
stdout_redirect "#{deploy_config['deploy_to']}/current/log/puma_error.log", "#{deploy_config['deploy_to']}/current/log/puma_access.log", true
plugin :tmp_restart
else
port 8094
environment 'development'
workers 1
threads 0, 16
bind "unix://tmp/sockets/push-puma.sock"
pidfile "tmp/pids/puma.pid"
state_path "tmp/pids/puma.state"
plugin :tmp_restart
worker_timeout 7200
end
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post 'api/v1/token', to: 'pushs#token'
post 'api/v1/push', to: 'pushs#push'
put 'api/v1/received', to: 'pushs#received'
post 'api/v1/push_v2', to: 'pushs#push_v2'
post 'api/v1/push', to: 'pushs#push'
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'
Sidekiq::Web.use Rack::Auth::Basic do |username, password|
username == "sidekiqadmin" && password == "5529d99a"
end if Rails.env.production?
resources :user_devices do
collection do
post :update_by_user_id
post :destroy_by_user_id
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment