Closed tjaoc closed 6 years ago
Hey @tiacruz,
You could use http://docs.php-http.org/en/latest/integrations/symfony-bundle.html and then register this library as a service and pass the httplug client.
httplug:
clients:
acme:
factory: 'httplug.factory.guzzle6'
services:
app.onesignal_config:
class: OneSignal\Config
calls:
- ["setApplicationId", ["your_app_id"]]
- ["setApplicationAuthKey", ["your_app_auth_key"]]
- ["setUserAuthKey", ["your_auth_key"]]
app.onesignal:
class: OneSignal\OneSignal
arguments:
- "@app.onesignal_config"
- "@httplug.client.acme"
Very Thanks, but i´m please other help.
This is my 3 files on my config. Before i´m ionic push service, and i´m interesed in change to OneSginal, it´s posible verify my files and help me the changes to integrate OneSignal Pease?
I´m sorry for my bad English.
OneSginalPushService.php
`<?php
namespace AppBundle\Services;
use GuzzleHttp\Client; use Monolog\Logger; use Http\Adapter\Guzzle6\Client as GuzzleAdapter; use Http\Client\Common\HttpMethodsClient as HttpClient; use Http\Message\MessageFactory\GuzzleMessageFactory; use OneSignal\Config; use OneSignal\Devices; use OneSignal\OneSignal;
class OneSignalPushService {
protected $client;
protected $logger;
public function __construct(Client $client, Logger $logger)
{
$this->client = $client;
$this->logger = $logger;
}
/**
* Get the list of push sent so far
*/
public function getPushList()
{
$response = $this->client->get("/push/notifications");
}
/**
* @param string $message
* Send push to all registered devices
*/
public function sendPushToAll($message)
{
$this->logger->info("sending push to all users");
$json = [
"notification" => ["message" => $message],
"profile" => "prod",
"send_to_all" => true,
"tokens" => []
];
$this->client->post("/push/notifications", ["json" => $json]);
}
public function sendPushToUsers($message, $tokens)
{
$this->logger->info("sending push to selected users");
$this->logger->critical("Sending push");
$json = [
"notification" => ["message" => $message],
"profile" => "prod",
"tokens" => $tokens
];
$this->client->post("/push/notifications", ["json" => $json]);
}
}`
ComunicationsManager.php
`<?php
namespace AppBundle\Comunications;
use AppBundle\Entity\Comunication; use AppBundle\Entity\User; use AppBundle\Entity\View; use AppBundle\Services\WNSPushService; use Doctrine\ORM\EntityManager; use Knp\Component\Pager\Paginator; use AppBundle\Services\OneSignalPushService;
class ComunicationsManager {
protected $em;
private $logger;
private $pusher;
private $paginator;
private $windowsPusher;
public function __construct(EntityManager $em, OneSignalPushService $pusher, Paginator $paginator, WNSPushService $windowsPusher)
{
$this->em = $em;
$this->pusher = $pusher;
$this->paginator = $paginator;
$this->windowsPusher = $windowsPusher;
}
public function getGroupComunicates($group)
{
if ($this->em) {
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$qb = $comunicationsRepository->createQueryBuilder("com");
$qb->where("com.type = 2")
->andWhere("com.workgroup = :group")
->orderBy("com.date", "DESC")
->setParameter("group", $group);
return $qb->getQuery()->getResult();
} else {
return null;
}
}
public function getGeneralComunicatesPaginator($page = 1, $limit = 10)
{
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$qb = $comunicationsRepository->createQueryBuilder("com");
$qb = $qb->where("com.type = 1")->orderBy("com.date", "DESC");;
return $this->paginator->paginate($qb->getQuery(), $page, $limit, array('pageParameterName' => 'general_com_page'));
}
public function getGroupComunicatesPaginator($user, $group, $page = 1, $limit = 10)
{
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$qb = $comunicationsRepository->createQueryBuilder("com");
$qb->where("com.type = 2")->andWhere("com.workgroup = :group OR com.author = :user")->setParameters(["group" => $group, "user" => $user])->orderBy("com.date", "DESC");
return $this->paginator->paginate($qb->getQuery(), $page, $limit, array('pageParameterName' => 'group_com_page'));
}
/**
* @param User $user
* @param int $page
* @param int $limit
* @return \Knp\Component\Pager\Pagination\PaginationInterface
*/
public function getDirectComunicatesPaginator(User $user, $page = 1, $limit = 10)
{
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$qb = $comunicationsRepository->createQueryBuilder("com")->where("com.type = 3")->andWhere(":u MEMBER OF com.users OR com.author = :u")->setParameter("u", $user)->orderBy("com.date", "DESC");
return $this->paginator->paginate($qb->getQuery(), $page, $limit, array('pageParameterName' => 'direct_com_page'));
}
public function getGeneralComunicates()
{
if ($this->em) {
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$qb = $comunicationsRepository->createQueryBuilder("com")->orderBy("com.date", "DESC");
$qb->where("com.type = 1");
return $qb->getQuery()->getResult();
} else {
return null;
}
}
public function getUnreadGeneralComunicates(User $user)
{
$dql = "SELECT com from AppBundle:Comunication com WHERE com.type = 1 AND com.id NOT IN ( SELECT IDENTITY(view.message) FROM AppBundle:View view WHERE view.user = :user) ORDER BY com.date DESC";
$query = $this->em->createQuery($dql);
$query->setParameter("user", $user);
$messages = $query->getResult();
return $messages;
}
public function getUnreadGroupComunicates(User $user, $group)
{
$dql = "SELECT com from AppBundle:Comunication com WHERE com.type = 2 AND com.workgroup = :group AND com.id NOT IN ( SELECT IDENTITY(view.message) FROM AppBundle:View view WHERE view.user = :user) ORDER BY com.date DESC";
$query = $this->em->createQuery($dql);
$query->setParameters(["group" => $group, 'user' => $user]);
$messages = $query->getResult();
return $messages;
}
public function getUnreadDirectComunicates(User $user)
{
$dql = "SELECT com from AppBundle:Comunication com WHERE com.type = 3 AND :user MEMBER OF com.users AND com.id NOT IN ( SELECT IDENTITY(view.message) FROM AppBundle:View view WHERE view.user = :user) ORDER BY com.date DESC";
$query = $this->em->createQuery($dql);
$query->setParameter("user", $user);
$messages = $query->getResult();
return $messages;
}
public function save($comunicate)
{
$this->em->persist($comunicate);
$this->em->flush();
$this->notifyUsers($comunicate);
}
/**
* @param Comunication $comunicate
*/
protected function notifyUsers($comunicate)
{
switch ($comunicate->getType()) {
case Comunication::TYPE_GENERAL: {
$users = $this->em->getRepository(User::class)->findBy(["device_type" => [User::DEVICE_WP, User::DEVICE_WEB]]);
$this->pusher->sendPushToAll($comunicate->getTitle());
$this->windowsPusher->sendPushToUsers($comunicate, $users);
break;
}
case Comunication::TYPE_GROUP: {
$group = $comunicate->getWorkgroup();
$users = $group->getMembers();
$tokens = $this->tokenFromUsers($users);
$this->pusher->sendPushToUsers($comunicate->getTitle(), $tokens);
$this->windowsPusher->sendPushToUsers($comunicate, $users);
break;
}
case Comunication::TYPE_DIRECT: {
$tokens = $this->tokenFromUsers($comunicate->getUsers());
$this->pusher->sendPushToUsers($comunicate->getTitle(), $tokens);
$this->windowsPusher->sendPushToUsers($comunicate, $comunicate->getUsers());
}
}
}
/**
* @param $users
* @return array $tokens
*/
protected function tokenFromUsers($users)
{
$tokens = [];
foreach ($users as $user) {
if ($user->getDeviceToken() != null) {
$tokens[] = $user->getDeviceToken();
}
}
return $tokens;
}
/**
* @param User $user
* @brief Get the comunicates the user is into
* and the user, if it was the only user, the comunicate gets deleted as well
*
*/
public function removeUserFromComunicates(User $user)
{
$user_comunicates = $this->getDirectComunicates($user);
//remove the user for all the comunicates
foreach ($user_comunicates as $comunicate) {
$comunicate->removeUser($user);
if (count($comunicate->getUsers()) == 0) {
//this was the only user, delete as well the comunicate
$this->em->remove($comunicate);
} else {
//save it with less users
$this->em->persist($comunicate);
}
}
$comunicates = $this->getUserComunicates($user);
if (count($comunicates) > 0) {
foreach ($comunicates as $comunicate) {
$this->em->remove($comunicate);
}
}
$this->em->flush();
}
public function getDirectComunicates(User $user)
{
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$qb = $comunicationsRepository->createQueryBuilder("com")
->where("com.type = 3")
->andWhere(":u MEMBER OF com.users")
->orderBy("com.date", "DESC")
->setParameter("u", $user);
$messages = $qb->getQuery()->getResult();
return $messages;
}
public function getUserComunicates(User $user)
{
$comunicationsRepository = $this->em->getRepository(Comunication::class);
$comunications = $comunicationsRepository->findBy(["author" => $user]);
return $comunications;
}
/**
* Register the user in the list of persons that saw the comunicate
* @param Comunication $comunication
* @param User $user
*/
public function addView(Comunication $comunication, User $user)
{
// if ($comunication->getAuthor() == $user) return; $qb = $this->em->getRepository(View::class)->createQueryBuilder("view");
$qb->where("view.user = :u")
->andWhere("view.message = :com")->setParameters(["u" => $user, "com" => $comunication]);
$results = $qb->getQuery()->getResult();
if (count($results) != 0) return;
$view = new View();
$view->setUser($user);
$view->setMessage($comunication);
$view->setViewAt(new \DateTime());
$this->em->persist($view);
$this->em->flush();
}
} `
ComunitacionsController.php
`<?php
namespace AppBundle\Controller;
use AppBundle\Comunications\ComunicationsManager; use AppBundle\Entity\Attachment; use AppBundle\Entity\Comunication; use AppBundle\Entity\ComunicationReply; use AppBundle\Entity\User; use AppBundle\Entity\Workgroup; use AppBundle\Form\ComunicationType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Bridge\Twig\Extension\RoutingExtension; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class ComunicationsController extends Controller { /**
@Route("/comunications/list", name="comunications") */ public function listAction(Request $request) { //get all comunications
$comunications = $this->getDoctrine()->getRepository(Comunication::class)->findBy([], ['date' => 'desc']);
// replace this example code with whatever you need
return $this->render('default/comunications.html.twig', [
"comunications" => $comunications
]
);
}
/**
@return \Symfony\Component\HttpFoundation\Response */ public function showAction($id) { $message = $this->getDoctrine()->getRepository(Comunication::class)->find($id); /* @var ComunicationsManager $comunicationsManager / $comunicationsManager = $this->get("comunications.manager"); if ($message) {
$comunicationsManager->addView($message, $this->getUser());
if ($message->getAcceptsReplies()) {
$form = $this->getReplyForm();
return $this->render("default/comunications/show.html.twig", ["item" => $message, "form" => $form->createView()]);
}
return $this->render("default/comunications/show.html.twig", ["item" => $message]);
} else {
throw new NotFoundHttpException("Comunication not found with id " . $id);
}
}
/**
@return \Symfony\Component\Form\Form|\Symfony\Component\Form\FormInterface */ public function getReplyForm() { $reply = new ComunicationReply(); $form = $this->createFormBuilder($reply) ->add("content", TextType::class) ->getForm(); return $form; }
/**
@return \Symfony\Component\HttpFoundation\Response */ public function showViewsAction($id){ /* @var Comunication $comunication / $comunication = $this->getDoctrine()->getRepository(Comunication::class)->find($id); if($comunication){ $views = $comunication->getViews();
return $this->render("default/comunications/views.html.twig",[
"item" => $comunication,
"views" => $views
]);
}else{
throw new NotFoundHttpException("page not found for comunicate");
}
}
/**
@Route("/comunications/create", name="comunications_create") */ public function createAction(Request $request) {
$comunication = new Comunication();
$form = $this->createForm(ComunicationType::class, $comunication, ["locale" => $request->getLocale()]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->processComunicateForm($form, Comunication::TYPE_GENERAL);
return $this->redirectToRoute("comunications");
}
return $this->render('default/comunications/create.html.twig',
["form" => $form->createView()]
);
}
/**
@param $form */ protected function processComunicateForm($form, $type) { /* @var Comunication $comunication / $comunication = $form->getData(); $attachments = $comunication->getAttachments();
if ($attachments) {
/** @var Attachment $item */
foreach ($attachments as $item) {
/** @var UploadedFile $file */
$file = $item->getFileName();
$item->setSourceName($file->getClientOriginalName());
$item->setMimeType($file->getMimeType());
$item->setSize($file->getSize());
$realFilename = $this->get('attachment_uploader')->upload($file);
// $type = $file->guessExtension(); $item->setFilename($this->getParameter("attachments_rel_directories") . '/' . $realFilename); $item->setCreatedAt(new \DateTime()); $item->setEnabled(true);
}
}
$comunication->setDate(new \DateTime());
$comunication->setAuthor($this->getUser());
$comunication->setType($type);
$comunication->setContent(str_replace("\n", "", $comunication->getContent()));
$this->get('comunications.manager')->save($comunication);
//send push to all people on comunicate creation
}
/**
@Route("/comunications/workgroup/{groupid}/create", name="comunications_workgroup_create") */ public function createWorkgroupComunicateAction($groupid, Request $request) {
$workgroup = $this->getDoctrine()->getEntityManager()->getRepository(Workgroup::class)->find($groupid);
if ($workgroup) {
$comunication = new Comunication();
$comunication->setWorkgroup($workgroup);
$form = $this->createForm(ComunicationType::class, $comunication, ["locale" => $request->getLocale()]);
$form->add("workgroup", TextType::class, ['label' => 'Grupo de trabajo de destino', "data" => $workgroup->getName(), "mapped" => false]);
$form->add("acceptsReplies", CheckboxType::class, ["required" => false, "label" => "comunication.response.accept.label"]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->processComunicateForm($form, Comunication::TYPE_GROUP);
return $this->redirectToRoute("homepage");
} elseif ($form->isSubmitted()) {
dump($form->getErrors(true));
die();
}
return $this->render('default/comunications/group_comunicate_create.html.twig',
["form" => $form->createView()]
);
} else {
throw new NotFoundHttpException("Invalid workgroup");
}
}
/**
@Route("/comunications/workgroup/{groupid}/users/create", name="comunications_workgroup_users_create") */ public function createWorkgroupUsersComunicateAction($groupid, Request $request) {
$workgroup = $this->getDoctrine()->getEntityManager()->getRepository(Workgroup::class)->find($groupid);
if ($workgroup) {
$comunication = new Comunication();
$users = $this->getDoctrine()->getRepository(User::class)->findBy(["workgroup" => $workgroup]);
$form = $this->createForm(ComunicationType::class, $comunication, ["locale" => $request->getLocale()]);
$form->add("workgroup", TextType::class, ['label' => 'Grupo de trabajo de destino', "data" => $workgroup->getName(), "mapped" => false]);
$form->add("users", EntityType::class,
["label" => "Destinatarios",
"choices" => $users,
"class" => User::class,
"multiple" => true,
"property" => "fullName"
]
);
$form->add("acceptsReplies", CheckboxType::class, ["required" => false, "label" => "comunication.response.accept.label"]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->processComunicateForm($form, Comunication::TYPE_DIRECT);
return $this->redirectToRoute("homepage");
} elseif ($form->isSubmitted()) {
dump($form->getErrors(true));
die();
}
return $this->render('default/comunications/group_users_comunicate_create.html.twig',
["form" => $form->createView()]
);
} else {
throw new NotFoundHttpException("Invalid workgroup");
}
}
/**
@Route("comunications/workgroup/{groupid}/manager/create", name="comunications_workgroup_manager_create") */
public function createWorkgroupManagerComunicateAction($groupid, Request $request) {
/** @var Workgroup $group */
$group = $this->getDoctrine()->getRepository(Workgroup::class)->find($groupid);
if ($group) {
$comunication = new Comunication();
/** @var User $manager */
$manager = $group->getManager();
if ($manager == null) {
throw new NotFoundHttpException("The workgroup does not have a manager");
}
$comunication->addUser($manager);
$comunication->setType(Comunication::TYPE_DIRECT);
$form = $this->createForm(ComunicationType::class, $comunication, ["locale" => $request->getLocale()]);
$form->add("workgroup", TextType::class, ['label' => 'Grupo de trabajo de destino', "data" => $group->getName(), "mapped" => false]);
$form->add("acceptsReplies", CheckboxType::class, ["required" => false, "label" => "comunication.response.accept.label"]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->processComunicateForm($form, Comunication::TYPE_DIRECT);
return $this->redirectToRoute("homepage");
}
return $this->render("default/comunications/group_manager_comunicate_create.html.twig", ["form" => $form->createView()]);
}
}
/**
@Route("/comunications/{id}/reply/create", name="comunications_replay_create") */ public function addReplyAction($id) {
$comunication = $this->getDoctrine()->getRepository(Comunication::class)->find($id);
if ($comunication) {
if (!$comunication->getAcceptsReplies()) {
return new NotFoundHttpException("Can't add reply to this comunicate");
}
$form = $this->getReplyForm();
$form->handleRequest($this->get("request"));
if ($form->isSubmitted() && $form->isValid()) {
$reply = $form->getData();
$reply->setAuthor($this->getUser());
$reply->setCreatedAt(new \DateTime());
$reply->setComunication($comunication);
$em = $this->getDoctrine()->getManager();
$em->persist($reply);
$em->flush();
// send push when the reply is sent
$author = $comunication->getAuthor();
$message = $this->getUser()->getFirstname();
$message = $message . " respondió a tu mensaje";
if ($author->getDeviceToken()) {
$this->get("httplug.client.acme")->sendPushToUsers($message, [$author->getDeviceToken()]);
}
return $this->redirectToRoute("comunications_show", ["id" => $id]);
}
return $this->redirectToRoute("comunications_show", ["id" => $id]);
} else {
throw new NotFoundHttpException("Comunication not found");
}
}
}`
To make less changes as possible I think you'll need to pass the OneSignal
library to your OneSignalPushService
and then replace usage with it
Okay, thanks, I'll try. It's just that I'm new to this.
Hello,
How integrate with symfony 2?
The bundle dizda/OnesignalApiBundle work with version 0.1.0 and i´m version 1 with Guzzle 6.
Thanks