0

Есть:

// Push при удалении фотографии в админке у пользователя
var sendPhotoRemovePush = function (user) {
    var message = {
        to: user.gcmId,
        notification: {
            title: user.locale == 'en' ? 'Photo deleted (No face)' : 'Фото удалено (Без лица)',
            body: user.locale == 'en' ? 'Upload your photo with a face. Your profile will be deleted with in 24 hours' :
                                 'Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа',
            sound: 'obyjvlenie.mp3'
        }
    };
    sendPush(message);
};

Задача состоит в том, чтобы можно было из админки менять текст сообщений.

Коллекцию я в базе со всеми сообщениями создал, в админке страничку сделал, связал админку с базой (уже можно менять текст через админку и меняется в базе).

Но вот что и как вписать в этот .js файл вместо этих сообщений, чтобы при отправке данные брались из базы, я не знаю, а попытки пока не дали результатов.

Вот простой запрос в MongoDB, который мне выдает первое сообщение:

//db.notices.find({name: "sendPhotoRemovePush"},{titleEn: 1, _id:0})

Как в коллекции:

{
"_id" : ObjectId("5b1055bab772d4a8c93dc0cf"),
"name" : "sendPhotoRemovePush",
"titleEn" : "Photo deleted (No face)",
"titleRu" : "Фото удалено (Без лица)",
"bodyEn" : "Upload your photo with a face. Your profile will be deleted with in 24 hours",
"bodyRu" : "Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа",
"sound" : "obyjvlenie.mp3",
"createdAt" : ISODate("2018-05-31T21:02:39.547Z"),
"updatedAt" : ISODate("2018-06-01T07:09:29.791Z")
}

Для более точного представления, вот полная версия файла с сообщениями:

{
(function () {
var path = require('path');
var config = require('nconf');
var FCM = require('fcm-push');
var mongoose = require('mongoose');
require('../models');
var User = mongoose.model('User');
var Notice = mongoose.model('Notice'); // подключаем коллекцию Notice

config.file({
    file: path.join(__dirname, '../../config/google-services.json')
});

var gcmApiKey = config.get('client:0:api_key:0:current_key');
var fcmSender = new FCM(gcmApiKey);

var getUser = function (userId, callback) {
    User.findOne({_id: userId}).exec(function (err, user) {
        callback(user);
    });
};

var sendPush = function (message) {
    fcmSender.send(message, function (err, response) {
        console.log(message);
        if (err) {
            console.log("sendFcmPush ---> Error:", err);
        } else {
            console.log("sendFcmPush ---> Success: ", response);
        }
    });
};

// Push при удалении фотографии в админке у пользователя
var sendPhotoRemovePush = function (user) {
    var message = {
        to: user.gcmId,
        notification: {
            title: user.locale == 'en' ? 'Photo deleted (No face)' : 'Фото удалено (Без лица)',
            body: user.locale == 'en' ? 'Upload your photo with a face. Your profile will be deleted with in 24 hours' :
                'Загрузите своё фото с лицом. Ваш профиль будет удалён в течении 24 часа',
            sound: 'obyjvlenie.mp3'
        }
    };
    sendPush(message);
};

// Push о напоминании что нужно поставить фотографию в профиле
var sendAboutProfilePhoto = function (user) {
    var message = {
        to: user.gcmId,
        notification: {
            title: user.locale == 'en' ? 'Profile will be deleted' : 'Профиль будет удалён',
            body: user.locale == 'en' ? 'You did not put your photo with a face' : 'Вы не поставили своё фото с лицом',
            sound: 'obyjvlenie.mp3'
        }
    };
    sendPush(message);
};

// 1. Push - это находка целей когда происходит запись в БД в hunts
var sendHunterSignal = function (user) {
    var message = {
        to: user.gcmId,
        notification: {
            title: user.locale == 'en' ? 'Catch or release!' : 'Поймай или отпусти',
            body: user.locale == 'en' ? 'The goal for dating is found!' : 'Найдена цель для знакомства!',
            sound: 'hunterlove.mp3',
            screenState: 'hunter_signal'
        }
    };
    sendPush(message);
};

// 2. Заявка на чат кто рядом
var sendChatInvite = function (userId) {
    getUser(userId, function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'Application for dating!' : 'Заявка на знакомства',
                body: user.locale == 'en' ? 'They want to meet you!' : 'С тобой хотят познакомиться!',
                sound: 'obyjvlenie.mp3',
                screenState: 'invite_near'
            }
        };
        sendPush(message);
    });
};

// 3.1 Принятие заявки
var sendAcceptInvite = function (userId) {
    getUser(userId, function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'Rather, in a chat dating!' : 'Скорее в чат знакомств',
                body: user.locale == 'en' ? 'Your application for dating is accepted!' : 'Твоя заявка на знакомства принята!',
                sound: 'obyjvlenie.mp3',
                screenState: 'newnear_message'
            }
        };
        sendPush(message);
    });
};

// 3.2 Отказ от чата
var sendDeclineInvite = function (userId) {
    getUser(userId, function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'LoveHunting!' : 'Охота любви',
                body: user.locale == 'en' ? 'Your application for dating has been deported!' : 'Твоя заявка на знакомства отклонена!',
                sound: 'obyjvlenie.mp3',
                screenState: null
            }
        };
        sendPush(message);
    });
};

// 4. Новое сообщение в чате с кем были встречи
var newMessageInChat = function (userId) {
    getUser(userId, function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'LoveHunting!' : 'Охота любви',
                body: user.locale == 'en' ? 'You have messages from chat!' : 'Тебе сообщения из чата!',
                sound: 'sms.mp3',
                screenState: 'new_message'
            }
        };
        sendPush(message);
    });
}

// 5. Новое сообщение в чате "Кто рядом"
var newMessageInChatNear = function (userId) {
    getUser(userId, function (user) {
        var message = {
            to: user.gcmId,
            notification: {
                title: user.locale == 'en' ? 'LoveHunting!' : 'Охота любви',
                body: user.locale == 'en' ? 'You have messages from chat!' : 'Тебе сообщения из чата!',
                sound: 'sms.mp3',
                screenState: 'newnear_message'
            }
        };
        sendPush(message);
    });
}

// 6. Создание видеочата
var createVideoChat = function () {
    var message = {
        to: '/topic/all', // Как отправить всем?
        notification: {
            title:'LoveHunting! / Охота любви',
            body: 'Meet the video chat! / Успей познакомиться в видеочате!',
            sound: 'default',
            screenState: 'video_chat'
        }
    };
    sendPush(message);
}

module.exports = {
    sendPhotoRemovePush: sendPhotoRemovePush,
    sendAboutProfilePhoto: sendAboutProfilePhoto,
    sendHunterSignal: sendHunterSignal,
    sendChatInvite: sendChatInvite,
    sendAcceptInvite: sendAcceptInvite,
    sendDeclineInvite: sendDeclineInvite,
    newMessageInChat: newMessageInChat,
    newMessageInChatNear: newMessageInChatNear,
    createVideoChat: createVideoChat,
};

}).call(this); }

2 ответа 2

0

Попробуйте:

const express = require('express');
const router = express.Router();

router.route('/photo-remove-push')
  .delete((req, res) => {
    db.notices.find({name: %REQ_PARAMS%},{titleEn: 1, _id:0}, (err, mess) => {
        if (err) return res.status(200).json(err).end();

        const {titleEn, titleRu, bodyEn, bodyRu} = mess;
        sendPhotoRemovePush(titleEn, titleRu, bodyEn, bodyRu)
        res.status(200).json(mess).end();
    });
});

sendPhotoRemovePush (...args) {
const message = {
    to: user.gcmId,
    notification: {
        title: user.locale == 'en' ? titleEn : titleRu,
        body: user.locale == 'en' ? bodyEn : bodyRu,
        sound: 'obyjvlenie.mp3'
    }
  };
sendPush(message);
};
2
  • Спасибо, почти рядом, пока не работает, я для наглядности добавил в тему файл с сообщениями целиком. Также нужно менять не только сами сообщения, но и 'sound' 18 июн 2018 в 18:57
  • Что именно не работает? Ошибка вернулась? Больше информации, пожалуйста. 20 июн 2018 в 9:26
0

Решение найдено:

var ObjectId = mongoose.Types.ObjectId; // объявляем ObjectId

Сама функция :

var sendPhotoRemovePush = function (user) {
   return mongoose.model('Notice')
       .findById(ObjectId("5b1055bab772d4a8c93dc0cf"), function (err, notice) {
           var message = {
               to: user.gcmId,
               notification: {
                   title: user.locale == 'en' ? notice.titleEn : notice.titleRu,
                   body: user.locale == 'en' ? notice.bodyEn : notice.bodyRu,
                   sound: notice.sound
               }
           };
           sendPush(message);
       });
};

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.