pushkin-library 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +28 -0
  4. data/Rakefile +36 -0
  5. data/app/assets/config/pushkin_manifest.js +2 -0
  6. data/app/assets/javascripts/pushkin/application.js +14 -0
  7. data/app/assets/javascripts/pushkin/firebase/push_notifications.js +100 -0
  8. data/app/assets/javascripts/pushkin/main.js +5 -0
  9. data/app/assets/stylesheets/pushkin/application.css +15 -0
  10. data/app/controllers/pushkin/api/v1/concerns/api_helper.rb +43 -0
  11. data/app/controllers/pushkin/api/v1/concerns/tokens_helper.rb +94 -0
  12. data/app/controllers/pushkin/application_controller.rb +5 -0
  13. data/app/fabrics/pushkin/notification_fabric.rb +83 -0
  14. data/app/helpers/pushkin/application_helper.rb +4 -0
  15. data/app/jobs/pushkin/application_job.rb +4 -0
  16. data/app/jobs/pushkin/send_job.rb +11 -0
  17. data/app/mailers/pushkin/application_mailer.rb +6 -0
  18. data/app/models/pushkin/application_record.rb +5 -0
  19. data/app/models/pushkin/concerns/pushkin_user.rb +10 -0
  20. data/app/models/pushkin/notification.rb +42 -0
  21. data/app/models/pushkin/payload.rb +21 -0
  22. data/app/models/pushkin/push_sending_result.rb +13 -0
  23. data/app/models/pushkin/token.rb +19 -0
  24. data/app/models/pushkin/token_result.rb +39 -0
  25. data/app/models/pushkin/tokens_provider.rb +22 -0
  26. data/app/models/pushkin/tokens_provider_user.rb +12 -0
  27. data/app/services/pushkin/fcm/send_android_push_service.rb +22 -0
  28. data/app/services/pushkin/fcm/send_fcm_push_service.rb +120 -0
  29. data/app/services/pushkin/fcm/send_ios_push_service.rb +22 -0
  30. data/app/services/pushkin/fcm/send_web_push_service.rb +22 -0
  31. data/app/services/pushkin/send_push_service.rb +39 -0
  32. data/app/services/pushkin/token_filters/android_token_filter.rb +15 -0
  33. data/app/services/pushkin/token_filters/ios_token_filter.rb +15 -0
  34. data/app/services/pushkin/token_filters/token_filter.rb +24 -0
  35. data/app/services/pushkin/token_filters/web_token_filter.rb +15 -0
  36. data/app/views/layouts/pushkin/application.html.erb +14 -0
  37. data/lib/generators/pushkin/setup_generator.rb +27 -0
  38. data/lib/generators/pushkin/templates/create_pushkin_tables.rb +89 -0
  39. data/lib/generators/pushkin/templates/tokens_controller.rb +16 -0
  40. data/lib/pushkin-library.rb +1 -0
  41. data/lib/pushkin.rb +29 -0
  42. data/lib/pushkin/engine.rb +5 -0
  43. data/lib/pushkin/version.rb +3 -0
  44. data/lib/tasks/pushkin_tasks.rake +4 -0
  45. metadata +128 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: f94c98f27e6c326b25532cd82f02081f6abe841e
4
+ data.tar.gz: 41617fbbbcf2204c5f4a82fa30703ae6cfae6739
5
+ SHA512:
6
+ metadata.gz: 426e924b8f4827bc186f1b02b2dc1449758b8fec44781579543498233f829dd30f14604be93581cee980695cf5bd1e79a1cdf6062ec2f6edeeccb9eaf8e85c6e
7
+ data.tar.gz: 4c4a43ade098878b8723c13accd318d375bb5a8342b3434b8ac6e49f6c00cae1589ef6ad3f2d3e7157f723abe1a789f79026aa7b4a4ae689104b0984724cef66
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2018 Bazov Peter
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # Pushkin
2
+ Short description and motivation.
3
+
4
+ ## Usage
5
+ How to use my plugin.
6
+
7
+ ## Installation
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'pushkin'
12
+ ```
13
+
14
+ And then execute:
15
+ ```bash
16
+ $ bundle
17
+ ```
18
+
19
+ Or install it yourself as:
20
+ ```bash
21
+ $ gem install pushkin
22
+ ```
23
+
24
+ ## Contributing
25
+ Contribution directions go here.
26
+
27
+ ## License
28
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,36 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'Pushkin'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.md')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+ APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
18
+ load 'rails/tasks/engine.rake'
19
+
20
+
21
+ load 'rails/tasks/statistics.rake'
22
+
23
+
24
+
25
+ require 'bundler/gem_tasks'
26
+
27
+ require 'rake/testtask'
28
+
29
+ Rake::TestTask.new(:test) do |t|
30
+ t.libs << 'test'
31
+ t.pattern = 'test/**/*_test.rb'
32
+ t.verbose = false
33
+ end
34
+
35
+
36
+ task default: :test
@@ -0,0 +1,2 @@
1
+ //= link_directory ../javascripts/pushkin .js
2
+ //= link_directory ../stylesheets/pushkin .css
@@ -0,0 +1,14 @@
1
+ // This is a manifest file that'll be compiled into application.js, which will include all the files
2
+ // listed below.
3
+ //
4
+ // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5
+ // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6
+ //
7
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8
+ // compiled file. JavaScript code in this file should be added after the last require_* statement.
9
+ //
10
+ // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11
+ // about supported directives.
12
+ //
13
+ //= require ./main
14
+ //= require_tree .
@@ -0,0 +1,100 @@
1
+ Pushkin.prototype.initNotifications = function() {
2
+ this.trackTokenRefreshing();
3
+ this.initNotificationsShow();
4
+ }
5
+
6
+ Pushkin.prototype.trackTokenRefreshing = function() {
7
+ var _this = this;
8
+
9
+ _this.messaging.onTokenRefresh(function() {
10
+ _this.messaging.getToken().then(function(refreshedToken) {
11
+ console.log('Token refreshed.');
12
+ _this.setTokenSentToServer(false);
13
+ _this.sendTokenToServerIfNeeds(refreshedToken);
14
+ }).catch(function(err) {
15
+ console.log('Unable to retrieve refreshed token ', err);
16
+ _this.showToken('Unable to retrieve refreshed token ', err);
17
+ });
18
+ });
19
+ }
20
+
21
+ Pushkin.prototype.requestPermission = function() {
22
+ var _this = this;
23
+ console.log('Requesting permission...');
24
+ _this.messaging.requestPermission().then(function() {
25
+ console.log('Notification permission granted.');
26
+ _this.getToken();
27
+ }).catch(function(err) {
28
+ console.log('Unable to get permission to notify.', err);
29
+ });
30
+ }
31
+
32
+ Pushkin.prototype.getToken = function() {
33
+ var _this = this;
34
+ _this.messaging.getToken().then(function(currentToken) {
35
+ if (currentToken) {
36
+ _this.sendTokenToServerIfNeeds(currentToken);
37
+ } else {
38
+ console.log('No Instance ID token available. Request permission to generate one.');
39
+ _this.setTokenSentToServer(false);
40
+ }
41
+ }).catch(function(err) {
42
+ console.log('An error occurred while retrieving token. ', err);
43
+ _this.setTokenSentToServer(false);
44
+ });
45
+ }
46
+
47
+ Pushkin.prototype.sendTokenToServerIfNeeds = function(currentToken) {
48
+ var _this = this;
49
+ if (!_this.isTokenSentToServer()) {
50
+ console.log('Sending token to server...');
51
+ _this.sendFirebaseTokenToServer(currentToken);
52
+ } else {
53
+ console.log('Token already sent to server so won\'t send it again unless it changes');
54
+ }
55
+ }
56
+
57
+ Pushkin.prototype.isTokenSentToServer = function() {
58
+ return window.localStorage.getItem('sentToServer') === '1';
59
+ }
60
+
61
+ Pushkin.prototype.setTokenSentToServer = function(sent) {
62
+ window.localStorage.setItem('sentToServer', sent ? '1' : '0');
63
+ }
64
+
65
+ Pushkin.prototype.initNotificationsShow = function() {
66
+ var _this = this;
67
+ _this.messaging.onMessage(function(payload) {
68
+ console.log('Message received. ', payload);
69
+ _this.showFirebaseMessage(payload);
70
+ });
71
+ }
72
+
73
+ Pushkin.prototype.showFirebaseMessage = function(payload) {
74
+ var _this = this;
75
+ var notificationInfo = payload.notification;
76
+
77
+ if(notificationInfo === undefined) {
78
+ return undefined;
79
+ }
80
+
81
+ var notificationTitle = notificationInfo.title;
82
+ var notificationOptions = {
83
+ body: notificationInfo.body,
84
+ icon: notificationInfo.icon,
85
+ tag: notificationInfo.tag
86
+ };
87
+
88
+ var notification = new Notification(notificationTitle, notificationOptions);
89
+ notification.onclick = function(event) {
90
+ event.preventDefault();
91
+
92
+ var clickAction = notificationInfo.click_action;
93
+ if(clickAction !== undefined && window.location.pathname !== clickAction) {
94
+ window.location = clickAction;
95
+ }
96
+
97
+ window.focus();
98
+ notification.close();
99
+ }
100
+ }
@@ -0,0 +1,5 @@
1
+ Pushkin = function() {
2
+
3
+ }
4
+
5
+ PUSHKIN = new Pushkin();
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10
+ * files in this directory. Styles in this file should be added after the last require_* statement.
11
+ * It is generally better to create a new file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,43 @@
1
+ # Базовый контроллер для всех остальных контроллеров Пушкина
2
+ module Pushkin::Api::V1::Concerns::ApiHelper
3
+
4
+ extend ActiveSupport::Concern
5
+
6
+ included do
7
+ WRONG_API_KEY = "Wrong API key"
8
+
9
+ # Проверяет переданный ключ API и возвращает ошибку в случае несовпадения.
10
+ # Для минимальной защиты от несанкционированного доступа.
11
+ def check_api_key!
12
+ api_key = ENV["PUSHKIN_API_KEY"]
13
+ raise Exception.new("No PUSHKIN_API_KEY in ENV") if api_key.blank?
14
+
15
+ if api_key != params[:push_api_key]
16
+ render :status => 403, :json => { :success => false, :info => WRONG_API_KEY }
17
+ end
18
+ end
19
+
20
+ def render_bad_request(info, errors = nil)
21
+ render_error(400, info, errors)
22
+ return nil
23
+ end
24
+
25
+ def render_unprocessable_entity(info, errors = nil)
26
+ render_error(422, info, errors)
27
+ return nil
28
+ end
29
+
30
+ def render_error(status, info, errors)
31
+ render :status => status, :json => { :success => false, :info => info, errors: errors }
32
+ return nil
33
+ end
34
+
35
+ def render_success(info = nil, data = nil)
36
+ response = { :success => true, info: info }
37
+ response[:data] = data unless data.nil?
38
+ render :json => response
39
+ return nil
40
+ end
41
+ end
42
+
43
+ end
@@ -0,0 +1,94 @@
1
+ # Контроллер по управлению PUSH токенами
2
+ module Pushkin::Api::V1::Concerns::TokensHelper
3
+
4
+ extend ActiveSupport::Concern
5
+
6
+ included do
7
+
8
+ include Pushkin::Api::V1::Concerns::ApiHelper
9
+
10
+ before_action :check_api_key!
11
+ before_action :init_creation_params!, only: [:create]
12
+
13
+ EMPTY_TOKEN_ERROR = "param 'token' is empty"
14
+ EMPTY_PLATFORM_ERROR = "params 'platform' is empty"
15
+ TOKEN_NOT_CREATED_ERROR = "token not created"
16
+ USER_NOT_SAVED_ERROR = "user not saved"
17
+ OLD_TOKEN_ERROR = "old token not disactivated"
18
+ TOKEN_NOT_ACTIVATED = "token not activated"
19
+
20
+ # Создает токен, если он не существует.
21
+ # Прикрепляет токен к пользователю, если пользователь авторизован.
22
+ # Помечает старый токен неактивным, если передана соответствующая информация.
23
+ def create
24
+ @token = Pushkin::Token.unscoped.where(token_attributes).first
25
+
26
+ # Сохранение токена в БД, если его еще не существует
27
+ if @token.nil?
28
+ @token = Pushkin::Token.create(token_attributes)
29
+ return render_token_not_created if @token.errors.present?
30
+ end
31
+
32
+ # Привязка/Отвязка пользователя с токеном.
33
+ if @token.user_id != @user_id
34
+ @token.update_attributes(user_id: @user_id)
35
+ return render_user_not_saved if @token.errors.present?
36
+ end
37
+
38
+ # Если вдруг каким-то обрабом токен помечен как неактивный, это нужно исправить
39
+ unless @token.is_active
40
+ @token.update_attributes(is_active: true)
41
+ return render_token_not_activated if @token.errors.present?
42
+ end
43
+
44
+ # Если передана информация о старом токене, его нужно деактивировать.
45
+ if @old_token_string.present?
46
+ if @old_token = Pushkin::Token.unscoped.where(token_attributes(@old_token_string)).first
47
+ @old_token.update_attributes(is_active: false)
48
+ return render_old_token_error if @old_token.errors.present?
49
+ end
50
+ end
51
+
52
+ render_success("Done")
53
+ end
54
+
55
+ def init_creation_params!
56
+ @token_string = token_params[:token]
57
+ @platform = token_params[:platform]
58
+ @old_token_string = token_params[:old_token]
59
+ @user_id = current_pushkin_user ? current_pushkin_user.id : nil
60
+
61
+ return render_bad_request(EMPTY_TOKEN_ERROR) if @token_string.blank?
62
+ return render_bad_request(EMPTY_PLATFORM_ERROR) if @platform.blank?
63
+ end
64
+
65
+ def token_params
66
+ @token_params ||= params.require(:push_token_info).permit(:token, :platform, :old_token)
67
+ end
68
+
69
+ def token_attributes(token_string = @token_string)
70
+ { token: token_string, platform: @platform }
71
+ end
72
+
73
+ def render_token_not_created
74
+ render_unprocessable_entity(TOKEN_NOT_CREATED_ERROR, @token.errors.messages)
75
+ end
76
+
77
+ def render_user_not_saved
78
+ render_unprocessable_entity(USER_NOT_SAVED_ERROR, @token.errors.messages)
79
+ end
80
+
81
+ def render_token_not_activated
82
+ render_unprocessable_entity(TOKEN_NOT_ACTIVATED, @token.errors.messages)
83
+ end
84
+
85
+ def render_old_token_error
86
+ render_unprocessable_entity(OLD_TOKEN_ERROR, @old_token.errors.messages)
87
+ end
88
+
89
+ def current_pushkin_user
90
+ nil
91
+ end
92
+ end
93
+
94
+ end
@@ -0,0 +1,5 @@
1
+ module Pushkin
2
+ class ApplicationController < ActionController::Base
3
+ protect_from_forgery with: :exception
4
+ end
5
+ end
@@ -0,0 +1,83 @@
1
+ # Создает уведомления в БД по переданным данным
2
+ module Pushkin
3
+ class NotificationFabric
4
+
5
+ # Создает уведомление со статическими данными.
6
+ # Актуальный список устройств, на которые нужно отправить уведомления,
7
+ # будут получены из пользователей в момент отправки.
8
+ def simple_notification_to_users(users: [], title: [], body: [],
9
+ is_data_message: false, click_action: nil, icon: nil,
10
+ data: {}, notification_type: nil)
11
+ return nil if users.blank?
12
+
13
+ payload_attrs = { title: title, body: body, data: data }
14
+ payload_attrs = payload_attrs.merge(self.is_data_message_attrs(is_data_message))
15
+ payload_attrs = payload_attrs.merge(self.click_action_attrs(click_action))
16
+ payload_attrs = payload_attrs.merge(self.icon_attrs(icon))
17
+ payload = Payload.create(payload_attrs)
18
+
19
+ tokens_provider = TokensProvider.create(users: users)
20
+
21
+ Notification.create(notification_type: notification_type,
22
+ payload: payload,
23
+ tokens_provider: tokens_provider)
24
+ end
25
+
26
+ def is_data_message_attrs(is_data_message = false)
27
+ if is_data_message.is_a? Hash
28
+ is_android_data_message = is_data_message[:android]
29
+ is_ios_data_message = is_data_message[:ios]
30
+ is_web_data_message = is_data_message[:web]
31
+
32
+ is_android_data_message = false if is_android_data_message.nil?
33
+ is_ios_data_message = false if is_ios_data_message.nil?
34
+ is_web_data_message = false if is_web_data_message.nil?
35
+
36
+ return {
37
+ is_android_data_message: is_android_data_message,
38
+ is_ios_data_message: is_ios_data_message,
39
+ is_web_data_message: is_web_data_message
40
+ }
41
+ else
42
+ return {
43
+ is_android_data_message: is_data_message,
44
+ is_ios_data_message: is_data_message,
45
+ is_web_data_message: is_data_message
46
+ }
47
+ end
48
+ end
49
+
50
+ def click_action_attrs(click_action = nil)
51
+ if click_action.is_a? Hash
52
+ return {
53
+ android_click_action: click_action[:android],
54
+ ios_click_action: click_action[:ios],
55
+ web_click_action: click_action[:web]
56
+ }
57
+ else
58
+ return {
59
+ android_click_action: click_action,
60
+ ios_click_action: click_action,
61
+ web_click_action: click_action
62
+ }
63
+ end
64
+ end
65
+
66
+ def icon_attrs(icon = nil)
67
+ if icon.is_a? Hash
68
+ return {
69
+ android_icon: icon[:android],
70
+ ios_icon: icon[:ios],
71
+ web_icon: icon[:web]
72
+ }
73
+ else
74
+ return {
75
+ android_icon: icon,
76
+ ios_icon: icon,
77
+ web_icon: icon
78
+ }
79
+ end
80
+ end
81
+
82
+ end
83
+ end