Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.36 KB | None | 0 0
  1. /**
  2. * @author: danyal
  3. * @date: 10/2/17.
  4. * @licence: The MIT License (MIT) all copies or substantial portions of the Software
  5. * @copyright: Tractive Sdn. Bhd.
  6. *
  7. * Copyright (c) 2016 Tractive Sdn. Bhd.
  8. * All rights reserved.
  9. *
  10. */
  11. const utilities = require('../helpers/utilities');
  12. const admin = require('firebase-admin');
  13. const serviceAccount = require('../mrt-app-9af67-firebase-adminsdk-v4jdx-d437786efe.json');
  14. const Subscription = require("../models/Subscription");
  15.  
  16. admin.initializeApp({
  17. credential: admin.credential.cert(serviceAccount),
  18. databaseURL: 'https://mrt-app-9af67.firebaseio.com'
  19. });
  20.  
  21. exports.sendSMS = function (request, response) {
  22.  
  23. console.log("request.body", request.body)
  24. var responseJSON = {success: true, messages: [], result: []};
  25. var message = request.body.message;
  26. var phone = request.body.phone;
  27.  
  28. if (message === undefined || message === '') {
  29. responseJSON.messages.push('message is not exist or not string');
  30. }
  31.  
  32. if (phone === undefined || phone === '') {
  33. responseJSON.messages.push('phone is not exist or not string');
  34. }
  35.  
  36. phone = parseInt(request.body.phone);
  37.  
  38. if (!utilities.isInt(phone)) {
  39. responseJSON.messages.push('phone_no is not exist or not integer');
  40. }
  41.  
  42. if (responseJSON.messages.length > 0) {
  43.  
  44. response.status(422).json(responseJSON);
  45. } else {
  46.  
  47. var requestApi = require("request");
  48.  
  49. var options = {
  50. method: 'GET',
  51. url: 'http://api.gosms.com.my/eapi/sms.aspx',
  52. qs:
  53. {
  54. company: 'xmt',
  55. user: 'xmt',
  56. password: 'PUYCRT',
  57. gateway: 'L',
  58. mode: 'BUK',
  59. type: 'TX',
  60. hp: phone.toString(),
  61. mesg: message.toString(),
  62. charge: '0',
  63. maskid: '1234abcd',
  64. convert: '0'
  65. },
  66. headers:
  67. {'cache-control': 'no-cache', 'content-type': 'application/x-www-form-urlencoded'}
  68. };
  69.  
  70. requestApi(options, function (error, res, body) {
  71. if (error) {
  72. console.log(error);
  73. } else {
  74.  
  75. console.log("body", body);
  76. responseJSON.success = true;
  77. responseJSON.result = body;
  78. response.status(200).json(responseJSON);
  79.  
  80. }
  81. });
  82.  
  83. }
  84. };
  85.  
  86. exports.fcmSubscribe = function (req, res) {
  87. var responseJSON = {success: false, messages: [], result: []};
  88.  
  89. var data = req.body.data;
  90.  
  91. if (data.key === undefined || data.key === '') {
  92. responseJSON.messages.push("'key' is missing");
  93. }
  94.  
  95. if (data.mobile === undefined || data.mobile === '') {
  96. responseJSON.messages.push("'mobile' is missing");
  97. }
  98.  
  99.  
  100. if (responseJSON.messages.length > 0) {
  101. res.status(422).json(responseJSON);
  102. } else {
  103. var registrationToken = data.key;
  104. var mobileNumber = data.mobile;
  105.  
  106. addToken(mobileNumber, registrationToken).then(function (result) {
  107. admin.messaging().subscribeToTopic([registrationToken], 'test').then(function (response) {
  108. console.log('Successfully subscribed to topic:', response);
  109. }).catch(function (error) {
  110. console.log('Error subscribing to topic:', error);
  111. });
  112. console.log('Successfully subscribed:', result);
  113. responseJSON.success = true;
  114. res.json(responseJSON);
  115. }).catch(function (error) {
  116. console.log('Error subscribing:', error);
  117. responseJSON.messages.push(error.messages);
  118. res.json(responseJSON);
  119. });
  120. }
  121. };
  122.  
  123. exports.fcmPushToTopic = function (req, res) {
  124. var responseJSON = {success: false, messages: [], result: []};
  125.  
  126. var data = req.body.data;
  127.  
  128. if (data.topic === undefined || data.topic === '') {
  129. responseJSON.messages.push("'topic' is missing");
  130. }
  131.  
  132. if (responseJSON.messages.length > 0) {
  133. res.status(422).json(responseJSON);
  134. } else {
  135.  
  136. var topic = data.topic;
  137. var text = data.message;
  138.  
  139. var message = {
  140. data: {
  141. message: text,
  142. time: (new Date()).toISOString()
  143. },
  144. android: {
  145. ttl: 3600 * 1000,
  146. priority: 'normal',
  147. notification: {
  148. title: 'Test Notifications',
  149. body: topic + ': ' + text,
  150. color: '#f45342'
  151. }
  152. },
  153. "webpush": {
  154. "notification": {
  155. "title": 'Friend Invitation',
  156. "body": topic + ': ' + text,
  157. "icon": 'https://freeiconshop.com/wp-content/uploads/edd/notification-flat.png'
  158. }
  159. },
  160. topic: topic
  161. };
  162. admin.messaging().send(message).then(function (response) {
  163. console.log('Successfully sent message:', response);
  164. responseJSON.success = true;
  165. responseJSON.result = [response];
  166. res.json(responseJSON);
  167. }).catch(function (error) {
  168. console.log('Error sending message:', error);
  169. responseJSON.messages.push(error.messages);
  170. res.json(responseJSON);
  171. });
  172. }
  173. };
  174.  
  175. exports.fcmPushToDevice = function (req, res) {
  176. var responseJSON = {success: false, messages: [], result: []};
  177.  
  178. var data = req.body.data;
  179.  
  180. if (data.mobile === undefined || data.mobile === '') {
  181. responseJSON.messages.push("'mobile' is missing");
  182. }
  183.  
  184. if (responseJSON.messages.length > 0) {
  185. res.status(422).json(responseJSON);
  186. } else {
  187. var mobile = data.mobile;
  188. var text = data.message;
  189.  
  190. findToken(mobile).then(function (subscription) {
  191. var content = {
  192. "data": {
  193. "message": "hello",
  194. "date": (new Date()).toISOString()
  195. },
  196. android: {
  197. ttl: 3600 * 1000,
  198. priority: 'normal',
  199. notification: {
  200. title: 'Invitation',
  201. body: 'This is a sample notification for you',
  202. color: '#f45342'
  203. }
  204. },
  205. "webpush": {
  206. "notification": {
  207. "title": 'Invitation',
  208. "body": 'This is a sample notification for you',
  209. "icon": 'https://freeiconshop.com/wp-content/uploads/edd/notification-flat.png'
  210. }
  211. },
  212. "token": subscription.token
  213. };
  214. admin.messaging().send(content).then(function (response) {
  215. console.log('Successfully sent message:', response);
  216. responseJSON.success = true;
  217. responseJSON.result = [response];
  218. res.json(responseJSON);
  219. }).catch(function (error) {
  220. console.log('Error sending message:', error);
  221. responseJSON.messages.push(error.messages);
  222. res.json(responseJSON);
  223. });
  224. }).catch(function (error) {
  225. console.log('Error sending message:', error);
  226. responseJSON.messages.push(error);
  227. res.json(responseJSON);
  228. })
  229. }
  230. };
  231.  
  232. function addToken(mobile, token) {
  233. return new Promise(function (resolve, reject) {
  234. Subscription.findOne({mobile: mobile}, function (err, subscription) {
  235. if (err) {
  236. reject(err.message)
  237. } else {
  238. if (subscription) {
  239. subscription.token = token;
  240. subscription.save();
  241. resolve(subscription);
  242. } else {
  243. Subscription.create({mobile: mobile, token: token}, function (err, subscription) {
  244. if (err) {
  245. reject(err.message)
  246. } else {
  247. resolve(subscription);
  248. }
  249. })
  250. }
  251. }
  252. })
  253. });
  254. }
  255.  
  256. function findToken(mobile) {
  257. return new Promise(function (resolve, reject) {
  258. Subscription.findOne({mobile: mobile}, function (err, subscription) {
  259. if (err) {
  260. reject(err.message)
  261. } else {
  262. resolve(subscription);
  263. }
  264. })
  265. });
  266. }
  267.  
  268. exports.internalPush = function (req, res) {
  269. var responseJSON = {success: false, messages: [], result: []};
  270.  
  271. var type = req.body.type; // feedback / / / questionnaire / MRT_station / transferred_promo / suggested_promo
  272. var push_type = ''; // device | topic
  273. var msg_recipient = ''; // phone number or topic name
  274. var msg_data = {
  275. type: '',
  276. feedback: '',
  277. friend_request: '',
  278. friend_respond: '',
  279. questionnaire: '',
  280. MRT_station: '',
  281. transferred_promo: '',
  282. suggested_promo: ''
  283. };
  284.  
  285.  
  286. var notification = {
  287. title: '',
  288. body: '',
  289. icon: 'https://lh3.googleusercontent.com/W_LH18eHqeKtN5t0_QAI9u-CxkRmMX_cgN4YpCQErxPpP-a7W2MTr1pF_wQDs9ZAZ68=s180-rw'
  290. };
  291.  
  292. switch (type) {
  293. case 'feedback':
  294. push_type = 'device';
  295. msg_recipient = req.body.recipient;
  296. msg_data.type = 'feedback';
  297. msg_data.feedback = JSON.stringify(req.body.data); // {image: "", title: "", description: "", feedback_rate: ""}
  298. notification.title = "Promotion Redeem";
  299. notification.body = req.body.data.title + ' has been redeemed.';
  300. break;
  301. case 'friend_request':
  302. push_type = 'device';
  303. msg_recipient = req.body.recipient;
  304. msg_data.type = 'friend_request';
  305. msg_data.friend_request = JSON.stringify(req.body.data); // {user_id: "", name: ""}
  306. notification.title = "Friend Request";
  307. notification.body = req.body.data.name + ' wants to connect with you on MyMRT.';
  308. break;
  309. case 'friend_respond':
  310. push_type = 'device';
  311. msg_recipient = req.body.recipient;
  312. msg_data.type = 'friend_respond';
  313. msg_data.friend_respond = JSON.stringify(req.body.data); // {message: ""}
  314. notification.title = "Friend Request";
  315. notification.body = req.body.data.message;
  316. break;
  317. case 'questionnaire':
  318. break;
  319. case 'MRT_station':
  320. push_type = 'topic';
  321. msg_recipient = 'mrt_station';
  322. msg_data.type = 'MRT_station';
  323. msg_data.MRT_station = JSON.stringify(req.body.data); // {title: "", description: ""}
  324. notification.title = "MRT Station";
  325. notification.body = req.body.data.description;
  326. break;
  327. case 'transferred_promo':
  328. push_type = 'device';
  329. msg_recipient = req.body.recipient;
  330. msg_data.type = 'transferred_promo';
  331. msg_data.transferred_promo = JSON.stringify(req.body.data); // {promotion: "", message: ""}
  332. notification.title = "Promotion Transfer";
  333. notification.body = req.body.data.message;
  334. break;
  335. case 'suggested_promo':
  336. break;
  337. }
  338.  
  339. if (push_type === 'device') {
  340.  
  341. var mobile = msg_recipient;
  342.  
  343. findToken(mobile).then(function (subscription) {
  344.  
  345. var content = {
  346. "data": msg_data,
  347. "android": {
  348. "ttl": 3600 * 1000,
  349. "priority": 'normal',
  350. "notification": notification
  351. },
  352. "webpush": {
  353. "notification": notification
  354. },
  355. "token": subscription.token
  356. };
  357. admin.messaging().send(content).then(function (response) {
  358. console.log('Successfully sent message:', response);
  359. responseJSON.success = true;
  360. responseJSON.result = [response];
  361. res.json(responseJSON);
  362. }).catch(function (error) {
  363. console.log('Error sending message:', error);
  364. responseJSON.messages.push(error.messages);
  365. res.json(responseJSON);
  366. });
  367. }).catch(function (error) {
  368. console.log('Error sending message:', error);
  369. responseJSON.messages.push(error);
  370. res.json(responseJSON);
  371. })
  372.  
  373. } else if (push_type === 'topic') {
  374. var topic = msg_recipient;
  375.  
  376. var content = {
  377. data: msg_data,
  378. android: {
  379. ttl: 3600 * 1000,
  380. priority: 'normal',
  381. notification: notification
  382. },
  383. "webpush": {
  384. "notification": notification
  385. },
  386. topic: topic
  387. };
  388. admin.messaging().send(content).then(function (response) {
  389. console.log('Successfully sent message:', response);
  390. responseJSON.success = true;
  391. responseJSON.result = [response];
  392. res.json(responseJSON);
  393. }).catch(function (error) {
  394. console.log('Error sending message:', error);
  395. responseJSON.messages.push(error.messages);
  396. res.json(responseJSON);
  397. });
  398. } else {
  399.  
  400. }
  401. };
  402.  
  403. //"icon": 'https://freeiconshop.com/wp-content/uploads/edd/notification-flat.png'
  404. /*
  405. *
  406. * var topic = data.topic;
  407. admin.messaging().subscribeToTopic([registrationToken], topic)
  408. .then(function (response) {
  409. console.log('Successfully subscribed to topic:', response);
  410. responseJSON.success = true;
  411. responseJSON.result = [response];
  412. res.json(responseJSON);
  413. })
  414. .catch(function (error) {
  415. console.log('Error subscribing to topic:', error);
  416. responseJSON.messages.push(error.messages);
  417. res.json(responseJSON);
  418. });*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement