src/Controller/NotificationController.php line 241

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Bridge\Twig\Mime\BodyRenderer;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Component\EventDispatcher\EventDispatcher;
  10. use Symfony\Component\Mailer\EventListener\MessageListener;
  11. use Symfony\Component\Mailer\Mailer;
  12. use Symfony\Component\Mailer\Transport;
  13. use Twig\Environment as TwigEnvironment;
  14. use Twig\Loader\FilesystemLoader;
  15. use Doctrine\ODM\MongoDB\DocumentManager;
  16. use Symfony\Component\Mime\Address;
  17. use App\Document\Notification;
  18. use App\Controller\SmsIRController;
  19. use Symfony\Component\HttpFoundation\File\UploadedFile;
  20. use Symfony\Component\String\Slugger\SluggerInterface;
  21. use Symfony\Component\HttpFoundation\Request;
  22. class NotificationController extends AbstractController  
  23. {
  24.         private $slugger;
  25.     private  $slug
  26.    public function __constructSluggerInterface $slugger )
  27.     {
  28.         
  29.         $this->slug $slugger ;
  30.         
  31.       
  32.        
  33.     }
  34.    private function saveFile(UploadedFile $file ): string
  35.     {
  36.         $directory 'notifications'// Specify the directory to save the file
  37.         try {
  38.       
  39.           
  40.           
  41.             $safeFilename $this->slug->slug($file);
  42.             $newFilename $safeFilename.'-'.uniqid().'.'.$file->guessExtension();
  43.             $file->move($directory,$newFilename);
  44.             return $newFilename;
  45.         } catch (Exception $e) {
  46.             throw new \RuntimeException('Failed to save file: ' $e->getMessage());
  47.         }
  48.     }
  49.     #[Route('/api/admin/sendNotification'methods: ['POST'], name'send_notification')]
  50.     public function sendNotification(DocumentManager $doctrineRequest $request): JsonResponse
  51.     {
  52.         // Handle JSON fields
  53.         $title $request->get('title');
  54.         $message $request->get('message');
  55.         $backgroundColor $request->get('backgroundColor');
  56.         $titleColor $request->get('titleColor');
  57.         $textColor $request->get('textColor');
  58.         $recipients json_decode($request->get('recipients'), true);
  59.            $status $request->get('status');
  60.         $user $this->getUser(); // Current logged-in user
  61.         $user_id $user->getId();
  62.         // Handle image file upload
  63.         $image null;
  64.         
  65.         
  66.         /** @var UploadedFile $uploadedFile */
  67.         $uploadedFile $request->files->get('image');
  68.         if ($uploadedFile) {
  69.      
  70.      
  71.      $image $this->saveFile($uploadedFile);
  72.      
  73.      
  74.        
  75.         }
  76.         // Create new notification document
  77.         $notification = new Notification();
  78.         $notification->setUserid($user_id);
  79.         $notification->setTitle($title);
  80.         $notification->setMessage($message);
  81.         $notification->setBackgroundColor($backgroundColor);
  82.         $notification->setTitleColor($titleColor);
  83.         $notification->setTextColor($textColor);
  84.         $notification->setRecipients($recipients);
  85.         $notification->setCreateTime(date('Y-m-d H:i:s'));
  86.         $notification->setStatus($status); // 0 for unread
  87.         if ($image) {
  88.             $notification->setImage($image);
  89.         }
  90.         // Persist the notification document
  91.         $doctrine->persist($notification);
  92.         $doctrine->flush();
  93.         return new JsonResponse(['status' => 200'msg' => 'Notification sent']);
  94.     }
  95. #[Route('/api/admin/updateNotification/{id}'methods: ['POST'], name'update_notification')]
  96. public function updateNotification(DocumentManager $doctrineRequest $requeststring $id): JsonResponse
  97. {
  98.     // Get the current user (assuming you have a user system)
  99.     $user $this->getUser();
  100.     $userId $user->getId();
  101.     // Find the notification by its ID
  102.     $notification $doctrine->getRepository(Notification::class)->findOneBy(['_id' => new \MongoDB\BSON\ObjectId($id)]);
  103.     // If the notification doesn't exist, return an error
  104.     if (!$notification) {
  105.         return new JsonResponse(['status' => '404''msg' => 'Notification not found'], 404);
  106.     }
  107.     // Retrieve form data
  108.     $title $request->request->get('title');
  109.     $message $request->request->get('message');
  110.     $status $request->request->get('status');
  111.     $backgroundColor $request->request->get('backgroundColor');
  112.     $titleColor $request->request->get('titleColor');
  113.     $textColor $request->request->get('textColor');
  114.     $recipientsJson $request->request->get('recipients'); // Get the recipients as a JSON string
  115.     // Decode the recipients JSON into an array
  116.     $recipients json_decode($recipientsJsontrue);
  117.     // Update the notification fields based on input
  118.     if ($title) {
  119.         $notification->setTitle($title);
  120.     }
  121.     if ($message) {
  122.         $notification->setMessage($message);
  123.     }
  124.     if ($status) {
  125.         $notification->setStatus($status);
  126.     }
  127.     if ($backgroundColor) {
  128.         $notification->setBackgroundColor($backgroundColor);
  129.     }
  130.     if ($titleColor) {
  131.         $notification->setTitleColor($titleColor);
  132.     }
  133.     if ($textColor) {
  134.         $notification->setTextColor($textColor);
  135.     }
  136.     // Handle file upload (if an image is uploaded)
  137.     if ($request->files->has('image')) {
  138.         $imageFile $request->files->get('image');
  139.         if ($imageFile) {
  140.             $imagePath $this->saveFile($imageFile);
  141.             $notification->setImage($imagePath);
  142.         }
  143.     }
  144.     // If recipients are provided, update them (assuming you have a way to store recipients)
  145.     if (is_array($recipients)) {
  146.         $notification->setRecipients($recipients); // Assuming you have a `setRecipients()` method in the Notification entity
  147.     }
  148.     // Persist changes to the database
  149.     $doctrine->persist($notification);
  150.     $doctrine->flush();
  151.     // Return a success response
  152.     return new JsonResponse(['status' => '200''msg' => 'Notification updated successfully']);
  153. }
  154.   #[Route('/api/admin/delete/notifications/{id}'methods: ['DELETE'], name'delete_notification')]
  155.     public function delete_notification(string $idDocumentManager $doctrine): JsonResponse
  156.     {
  157.         // Fetch the notification by ID
  158.         $notification $doctrine->getRepository(Notification::class)->find($id);
  159.         // If the notification does not exist, return a 404 error
  160.         if (!$notification) {
  161.             return new JsonResponse(['status' => '404''msg' => 'Notification not found'], 404);
  162.         }
  163.         // Remove the notification from the database
  164.         $doctrine->remove($notification);
  165.         $doctrine->flush();
  166.         // Return a success response
  167.         return new JsonResponse(['status' => '200''msg' => 'Notification deleted successfully']);
  168.     }
  169.     #[Route('/api/admin/notifications',methods: ['POST'], name'admin_get_notifications')]
  170.    public function admin_get_notifications(DocumentManager  $doctrine Request $request ): JsonResponse
  171.    {
  172.    
  173.    
  174.        $data =  json_decode($request->getContent(), false);
  175.    
  176.        
  177.        $notifications $doctrine->createQueryBuilder(Notification::class)
  178.  
  179.        ->hydrate(false)
  180.        ->getQuery()
  181.        ->execute()
  182.        ->toArray();
  183.        $res = ["status" => "200" "msg" => "OK" "notifications" => $notifications ] ;
  184.  
  185.        return new JsonResponse($res);
  186.    }
  187. #[Route('/api/notifications/get'methods: ['POST'], name'get_notifications')]
  188. public function get_notifications(DocumentManager $doctrineRequest $request): JsonResponse
  189. {
  190.     // Get the current user (assuming you have a user system)
  191.     $user $this->getUser();
  192.     $user_id $user->getId();
  193.     // Fetch notifications where the user's ID exists in the recipients array
  194.     $notifications $doctrine->createQueryBuilder(Notification::class)
  195.         ->field('recipients')->in([$user_id]) // Check if user_id exists in the recipients array
  196.         ->hydrate(false)
  197.         ->getQuery()
  198.         ->execute()
  199.         ->toArray();
  200.     // Prepare the response
  201.     $res = [
  202.         "status" => "200",
  203.         "msg" => "OK",
  204.         "notifications" => $notifications
  205.     ];
  206.     return new JsonResponse($res);
  207. }
  208.    public function sms_send_deposit(String  $amount String $pair String $number  ): Response
  209.    {
  210.        $curl curl_init();
  211.        
  212.        curl_setopt_array($curl, array(
  213.          CURLOPT_URL => 'https://api.kavenegar.com/v1/69434D6E304943427752544A587755343546775650334452444C4D46522F5A4F32516B4B75634A6A6E75413D/verify/lookup.json',
  214.          CURLOPT_RETURNTRANSFER => true,
  215.          CURLOPT_ENCODING => '',
  216.          CURLOPT_MAXREDIRS => 10,
  217.          CURLOPT_TIMEOUT => 0,
  218.          CURLOPT_FOLLOWLOCATION => true,
  219.          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  220.          CURLOPT_CUSTOMREQUEST => 'POST',
  221.          CURLOPT_POSTFIELDS => 'receptor='.$number.'&template=deposit&token='.$pair.'&token2='.$amount,
  222.          CURLOPT_HTTPHEADER => array(
  223.            'Content-Type: application/x-www-form-urlencoded',
  224.            'Cookie: cookiesession1=678A8C31QRSTUVXZBEGIKMOQSUWY60AF'
  225.          ),
  226.        ));
  227.        
  228.        $response curl_exec($curl);
  229.        
  230.        curl_close($curl);
  231.    
  232.    
  233.         return new Response($response);
  234.    } 
  235.    public function sms_send_withdraw(String  $amount String $pair String $number  ): Response
  236.    {
  237.        $curl curl_init();
  238.        
  239.        curl_setopt_array($curl, array(
  240.          CURLOPT_URL => 'https://api.kavenegar.com/v1/69434D6E304943427752544A587755343546775650334452444C4D46522F5A4F32516B4B75634A6A6E75413D/verify/lookup.json',
  241.          CURLOPT_RETURNTRANSFER => true,
  242.          CURLOPT_ENCODING => '',
  243.          CURLOPT_MAXREDIRS => 10,
  244.          CURLOPT_TIMEOUT => 0,
  245.          CURLOPT_FOLLOWLOCATION => true,
  246.          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  247.          CURLOPT_CUSTOMREQUEST => 'POST',
  248.          CURLOPT_POSTFIELDS => 'receptor='.$number.'&template=withdraw&token='.$pair.'&token2='.$amount,
  249.          CURLOPT_HTTPHEADER => array(
  250.            'Content-Type: application/x-www-form-urlencoded',
  251.            'Cookie: cookiesession1=678A8C31QRSTUVXZBEGIKMOQSUWY60AF'
  252.          ),
  253.        ));
  254.        
  255.        $response curl_exec($curl);
  256.        
  257.        curl_close($curl);
  258.    
  259.    
  260.         return new Response($response);
  261.    }
  262.    public function sms_send_kyc(String  $name String $number  ): Response
  263.    {
  264.        $curl curl_init();
  265.        
  266.        curl_setopt_array($curl, array(
  267.          CURLOPT_URL => 'https://api.kavenegar.com/v1/69434D6E304943427752544A587755343546775650334452444C4D46522F5A4F32516B4B75634A6A6E75413D/verify/lookup.json',
  268.          CURLOPT_RETURNTRANSFER => true,
  269.          CURLOPT_ENCODING => '',
  270.          CURLOPT_MAXREDIRS => 10,
  271.          CURLOPT_TIMEOUT => 0,
  272.          CURLOPT_FOLLOWLOCATION => true,
  273.          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  274.          CURLOPT_CUSTOMREQUEST => 'POST',
  275.          CURLOPT_POSTFIELDS => 'receptor='.$number.'&template=kyc&token20='.$name,
  276.          CURLOPT_HTTPHEADER => array(
  277.            'Content-Type: application/x-www-form-urlencoded',
  278.            'Cookie: cookiesession1=678A8C31QRSTUVXZBEGIKMOQSUWY60AF'
  279.          ),
  280.        ));
  281.        
  282.        $response curl_exec($curl);
  283.        
  284.        curl_close($curl);
  285.    
  286.    
  287.         return new Response($response);
  288.    }  
  289.  
  290.     public function get_token(){
  291.         
  292.       
  293. $curl curl_init();
  294. curl_setopt_array($curl, array(
  295.   CURLOPT_URL => 'http://RestfulSms.com/api/Token',
  296.   CURLOPT_RETURNTRANSFER => true,
  297.   CURLOPT_ENCODING => '',
  298.   CURLOPT_MAXREDIRS => 10,
  299.   CURLOPT_TIMEOUT => 0,
  300.   CURLOPT_FOLLOWLOCATION => true,
  301.   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  302.   CURLOPT_CUSTOMREQUEST => 'POST',
  303.   CURLOPT_POSTFIELDS =>'{
  304.   "UserApiKey": "d35f3ad2c7d6b1a0ea753ad3",
  305.   "SecretKey": "4xG3WYwR1lt"
  306. }',
  307.   CURLOPT_HTTPHEADER => array(
  308.     'Content-Type: application/json'
  309.   ),
  310. ));
  311. $response curl_exec($curl);
  312. curl_close($curl);
  313. return  $response;
  314.         
  315.         
  316.         
  317.     }
  318.     public function sms_send_otp(String  $msg String $number  ): JsonResponse
  319.     {
  320.         
  321.         
  322.         
  323. $curl curl_init();
  324. curl_setopt_array($curl, array(
  325.   CURLOPT_URL => 'https://api.sms.ir/v1/send/verify',
  326.   CURLOPT_RETURNTRANSFER => true,
  327.   CURLOPT_ENCODING => '',
  328.   CURLOPT_MAXREDIRS => 10,
  329.   CURLOPT_TIMEOUT => 0,
  330.   CURLOPT_FOLLOWLOCATION => true,
  331.   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  332.   CURLOPT_CUSTOMREQUEST => 'POST',
  333.   CURLOPT_POSTFIELDS =>'{
  334.   "mobile": "'.$number.'",
  335.   "templateId": 9012,
  336.   "parameters": [
  337.     {
  338.       "name": "VERIFICATIONCODE",
  339.       "value": "'.$msg.'"
  340.     }
  341.   ]
  342. }',
  343.   CURLOPT_HTTPHEADER => array(
  344.     'Content-Type: application/json',
  345.     'Accept: text/plain',
  346.     'x-api-key: 5otSfVo5m8yWhzYafPGmulSxM7dUbxoNeSZVnx0VzHb6tpsb'
  347.   ),
  348. ));
  349. $response curl_exec($curl);
  350. curl_close($curl);
  351.         $res = ["status" => "200" "msg" => "sms sent"] ;
  352.         return new JsonResponse($res);
  353.     }  
  354.     
  355.     
  356.     public function sendemail(string $subject string $text ,  string $html ): JsonResponse
  357.     {
  358.         $loader = new FilesystemLoader(dirname(__DIR__2).'/templates');
  359.         $twig = new TwigEnvironment($loader);
  360.         $messageListener = new MessageListener(null, new BodyRenderer($twig));
  361.         
  362.         $eventDispatcher = new EventDispatcher();
  363.         $eventDispatcher->addSubscriber($messageListener);
  364.         
  365.         $transport Transport::fromDsn('gmail+smtp://h68ablog:xgjnvzkhevapoliu@default'$eventDispatcher);
  366.         $mailer = new Mailer($transportnull$eventDispatcher);
  367.         
  368.         $email = (new TemplatedEmail())
  369.         ->from('h68ablog@gmail.com')
  370.         ->to(new Address('h6688a@gmail.com'))
  371.         ->subject('Thanks for signing up!')
  372.             ->htmlTemplate('emails/main.html.twig')
  373.             ->context([
  374.                 'expiration_date' => new \DateTime('+7 days'),
  375.                 'username' => 'foo',
  376.             ])
  377.         ;
  378.         $mailer->send($email);
  379.      
  380.         $res = ["status" => "200" "msg" => "Email sent"] ;
  381.         return new JsonResponse($res);
  382.     }  
  383. }