api.rb
2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
require_dependency 'api/helpers'
require_relative 'api_entities'
class PushNotificationPlugin::Api < Grape::API
include Api::Helpers
resource :push_notification_plugin do
helpers do
def target
if params.has_key?(:target_id)
target_user = environment.users.detect{|u|u.id == params[:target_id].to_i}
else
target_user = current_user
end
if !current_person.is_admin? && (target_user.nil? || target_user!=current_user)
render_api_error!(_('Unauthorized'), 401)
end
return target_user
end
end
get 'device_tokens' do
authenticate!
target_user = target
tokens = target_user.device_token_list || []
present tokens
end
post 'device_tokens' do
authenticate!
target_user = target
bad_request!("device_name") unless params[:device_name]
token = PushNotificationPlugin::DeviceToken.new({:device_name => params[:device_name], :token => params[:token], :user => target_user}) if !target_user.device_token_list.include?(params[:token])
target_user.device_tokens.push(token)
unless target_user.save
render_api_errors!(target_user.errors.full_messages)
end
present target_user, :with => PushNotificationPlugin::Entities::DeviceUser
end
delete 'device_tokens' do
authenticate!
target_user = target
PushNotificationPlugin::DeviceToken.delete_all(["token = ? AND user_id = (?)", params[:token],target_user.id])
present target_user, :with => PushNotificationPlugin::Entities::DeviceUser
end
get 'notification_settings' do
authenticate!
target_user = target
present target_user, with: PushNotificationPlugin::Entities::DeviceUser
end
get 'possible_notifications' do
result = {:possible_notifications => PushNotificationPlugin::NotificationSettings::NOTIFICATIONS.keys}
present result, with: Grape::Presenters::Presenter
end
post 'notification_settings' do
authenticate!
target_user = target
PushNotificationPlugin::NotificationSettings::NOTIFICATIONS.keys.each do |notification|
next unless params.keys.include?(notification)
state = params[notification]
target_user.notification_settings.set_notification_state notification, state
end
target_user.save!
present target_user, with: PushNotificationPlugin::Entities::DeviceUser
end
get 'active_notifications' do
authenticate!
target_user = target
present target_user.notification_settings.active_notifications, with: Grape::Presenters::Presenter
end
get 'inactive_notifications' do
authenticate!
target_user = target
present target_user.notification_settings.inactive_notifications, with: Grape::Presenters::Presenter
end
end
end