PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label notifications. Show all posts
Showing posts with label notifications. Show all posts

Sunday, November 6, 2022

[FIXED] How to get changed contacts using Contacts Framework in iOS

 November 06, 2022     contacts, ios, notifications, swift     No comments   

Issue

I can monitor contacts change using:

NotificationCenter.default.addObserver(
            self, selector: #selector(contactStoreDidChange), name: .CNContactStoreDidChange, object: nil)
    }

@objc func contactStoreDidChange(notification: NSNotification) {

}

But how can I get the changed contacts from the notification? Things like which contact is added/removed/changed etc?


Solution

You just can get notify in the method.and you have to then refetch all objects and create your dataSource again for updated data!!



Answered By - Tanvi Jain
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 21, 2022

[FIXED] How to get changed contacts using Contacts Framework in iOS

 October 21, 2022     contacts, ios, notifications, swift     No comments   

Issue

I can monitor contacts change using:

NotificationCenter.default.addObserver(
            self, selector: #selector(contactStoreDidChange), name: .CNContactStoreDidChange, object: nil)
    }

@objc func contactStoreDidChange(notification: NSNotification) {

}

But how can I get the changed contacts from the notification? Things like which contact is added/removed/changed etc?


Solution

You just can get notify in the method.and you have to then refetch all objects and create your dataSource again for updated data!!



Answered By - Tanvi Jain
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] How to get the message from a PyQt5 notification message?

 July 11, 2022     balloon, message, notifications, pyqt5, python     No comments   

Issue

I'd like to write an application using PyQt5 that has various notification messages. Is it possible to get the text from a balloon message when a user clicked on it?

I wrote a sample code that simulate my question. A thread sending signals every 10 seconds. When a signal sent, two types of messages pops up. When a user clicks on the message tray_msg_clicked method activates. But this is where I stuck. I can't identify what was the message.

from PyQt5 import QtCore, QtWidgets
from time import sleep


class Ui_MainWindow(QtWidgets.QMainWindow):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1218, 502)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(827, 500))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.mythread = ExecuteThread()
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.initUI()

    def initUI(self):
        self.tray()
        self.start_thread()

    def start_thread(self):
        self.mythread.start()
        self.mythread.my_signal.connect(self.thread_signal)

    def thread_signal(self, msg):
        if msg == "message1":
            self.tray_icon.showMessage("Message1", "This is message one.",
                                       QtWidgets.QSystemTrayIcon.Information, 5000)
        elif msg == "message2":
            self.tray_icon.showMessage("Message2", "This is message two.",
                                       QtWidgets.QSystemTrayIcon.Information, 5000)

    def tray_msg_clicked(self):
        print("Tray message clicked!")
        tray_msg = ""
        if tray_msg == "This is message one.":
            print("'Message one' code activated.")
            # Some code
        elif tray_msg == "This is message two.":
            print("'Message two' code activated.")
            # Some code

    def tray(self):
        self.tray_icon = QtWidgets.QSystemTrayIcon(self)
        self.tray_icon.messageClicked.connect(self.tray_msg_clicked)
        self.tray_icon.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ComputerIcon))
        tray_menu = QtWidgets.QMenu()
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()


class ExecuteThread(QtCore.QThread):
    my_signal = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(ExecuteThread, self).__init__(parent)

    def run(self):
        while True:
            self.my_signal.emit("message1")
            sleep(10)
            self.my_signal.emit("message2")
            sleep(10)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Anyone have any idea or workaround to identify the text from these notification messages? Thank You for your help!


Solution

The responsible module for show this messages the QBalloonTip class that doesn't have public interface, so unfortunately this is unavailable from python.

https://code.woboq.org/qt5/qtbase/src/widgets/util/qsystemtrayicon_p.h.html#QBalloonTip

Try to modifiy the toolTip attribute of the QSystemTrayIcon instance or introduce a new variable with the text of the last message.



Answered By - birorichard
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 19, 2022

[FIXED] How to change notification mail ->action function button default color Laravel?

 April 19, 2022     email, laravel, notifications, php     No comments   

Issue

I have a task. And in Notifications mail file I need to add a button in public function toMail():

I have done it, but by default, the background color of the button is black, and I need to make it blue. How do I change the color in this function and code of the button?

Here is the code exampple:

public function toMail(): MailMessage
{
return (new MailMessage())
->action('Button name', rout('route.name'))
}

SO how to change the button color that the background color change from default black to my choosing (for example blue)?

Thank you.


Solution

The SimpleMessage class is designed for creating simple messages that have one call to action button, you can find the code that powers the functionality in Illuminate/Notifications/Messages/SimpleMessage.php and the template for the SimpleMessage emails can be found in Illuminate/Notifications/resources/views/email.blade.php — note the single button.

You can create more complex messages using the Markdown Mail Notifications feature, which will allow you to include as many buttons as you like. You can implement this like so:

Run the command to generate a new notification and pass in the markdown option, e.g: php artisan make:notification InvoicePaid --markdown=mail.invoice.paid Open the newly created template, e.g: views/mail/invoice/paid.blade.php Add as many buttons as you like, e.g:

@component('mail::message')
  # Introduction

  @component('mail::button', ['url' => $url1])
  Button 1 Text
  @endcomponent

  @component('mail::button', ['url' => $url2])
  Button 2 Text
  @endcomponent

  @component('mail::button', ['url' => $url3])
  Button 3 Text
  @endcomponent

Thanks,
{{ config('app.name') }} @endcomponent Replace your calls to SimpleMessage methods with a reference to your markdown template when constructing your email, e.g:

return (new MailMessage)
  ->subject($this->options['subject'])
  ->markdown('mail.invoice.paid', $this->options);

The second parameter in the markdown method is an array to pass into your view, through this you can include the various values you'd like to include in your email, such as contentParagraph1, greeting and salutation.



Answered By - Bilal sagheer Awan
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, April 18, 2022

[FIXED] how to send mail to all users when new post data is entered in database in laravel 8

 April 18, 2022     laravel, laravel-8, notifications     No comments   

Issue

i want to send all users notification when a user create a new post in database the notification should go to all the users as new post created

<?php
    
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Notifications\PostNotificationforAll;

class Postnotification extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'post:notification';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Post notification for all users';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $users= User::all();
        foreach ($users as $user) {
            $user->notify(new PostNotificationforAll());
        }
    }
}

can any help me out what condition should i use


Solution

<?php

namespace App\Observers;

use App\Models\Post;
use App\Models\User;

class PostObserver
{
      public function created(Post $post)
      {
          $users = User::where(...)->get();

          // Send the notifications
          Notification::send($users, new Postnotification($post));
      }
}


Answered By - Jahongir Tursunboyev
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 27, 2022

[FIXED] PHP SDK Facebook graph API send App-to-User Notifications using CRON job

 February 27, 2022     cron, facebook-graph-api, facebook-php-sdk, notifications     No comments   

Issue

Trying to send a scheduled notification to an app user.

The user specify a reminder time that is stored in a MySQL database and using a cron job. I want to send notification 3 times a day; upon user prefered time (using local time).

I setup the cron to run once every 30 min.

<?php
function runCurl($path)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $path);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $output = curl_exec($ch);
    return $output;
    curl_close($ch);
}
function getAppUsers()
{
}
function build_batch_request()
{
}
$graph_url    = "https://graph.facebook.com/oauth/access_token?client_id=xxx&client_secret=xxx&grant_type=client_credentials&redirect_uri=https://www.example.com/app/";
$result       = runCurl($graph_url);
$access_token = json_decode($result)->access_token;
$graph_url    = "https://graph.facebook.com/me/notifications?access_token=$access_token&template=Test Message";
$result       = runCurl($graph_url);
print_r($result); // for debug only
?>

I am getting error that says that something went wrong from Facebook graph API.

Update: question clarified.


Solution

I found my code mistakes:

  • message template needs to be URL Encoded:
  • Also I needed to make sure I am getting the app access token.
  • I needed to debug and find out if database is returning values

Here is a tested and working code: I am include the whole cron code; please feel free to edit for optimization and add your input.

<?php



 if(isset($_GET["key"]) || !empty($_GET["key"]) )
            {

    //  will be used later when creating a cron job; to prevent direct access to file
    if($_GET["key"]=='YOUR_KEY_HERE')
        {
                            require_once 'Facebook/autoload.php';


                            define('APPID', 'YOUR_APP_ID_HERE');
                            define('APPSECRET', 'YOUR_APP_SECRET_HERE');
                            define('CANVASURL', 'YOUR_CANVAS_URL_HERE');


                            // function to run CURL
                            function runCurl($path)
                            {
                                    $ch = curl_init();
                                    curl_setopt($ch, CURLOPT_URL, $path);
                                    curl_setopt($ch, CURLOPT_HEADER, 0);
                                    curl_setopt($ch, CURLOPT_POST, 1);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                                    $output = curl_exec($ch);
                                    return $output;
                                    curl_close($ch);
                            }

                            // function to send batch notification to app user
                            function notify()
                            {
                                    $fb = new Facebook\Facebook(
                                    ['app_id' => 'APPID',
                                    'app_secret' => 'APPSECRET',
                                    'default_graph_version' => 'v2.10']);





                                    $gmt_time = gmdate("H:i:s", time());


                                    include_once 'db.php';
                                    // include your database configuration
                                    // recommending using PDO
                                    $db=connect();

                                    $get_users_list="select fb_userid, morning, afternoon, night ,utc_time from alarm where time_format(morning, '%H:%i') = time_format(UTC_TIME, '%H:%i') OR time_format(afternoon, '%H:%i') = time_format(UTC_TIME, '%H:%i') OR time_format(night, '%H:%i') = time_format(UTC_TIME, '%H:%i')";
                                    // getting a list of users that expecting a reminder notification;
                                    // as the server's is using UTC, we convert saved local time into UTC time
                                    // I can directly save in UTC when user input reminder time; but this is intended
                                    // echo $get_users_list; //DEBUG


                                    $result= $db->getDataListFromQuery($get_users_list);
                                    //var_dump('Query Result= '. $result[0]); // DEBUG
                                    if($result[0]>0)
                                    {
                                    // check if $result return data and not empty
                                            $graph_url= "https://graph.facebook.com/oauth/access_token?client_id=". APPID . "&client_secret=" . APPSECRET . "&grant_type=client_credentials&redirect_uri=" . CANVASURL;

                                            echo $graph_url;


                                            $curlResult = runCurl($graph_url);
                                            $access_token = json_decode($curlResult)->access_token;
                                            var_dump($access_token); //DEBUG


                                    $fb->setDefaultAccessToken($access_token);
                                    $fb_usersList= []; // an arry to hold the users' IDs to wich notification will go.
                                    $tmpbatch = []; // an array to hold all requests in batch


                            foreach ($result as $row) {
                                         $fbUserID = $row['fb_userid'];
                                         $morning_alarm = $row['morning'];
                                         $afternoon_alarm = $row['afternoon'];
                                         $night_alarm = $row['night'];


                                         $morning_med = $row['morningmed'];
                                         $afternoon_med = $row['afternoonmed'];
                                         $night_med= $row['nightmed'];

                                         $now_utc= $row['utc_time'];


$now_utc = date('H:i', strtotime($now_utc));     // remove seconds from UTC TIME
$morning_alarm = date('H:i', strtotime($morning_alarm ));
$afternoon_alarm = date('H:i', strtotime($afternoon_alarm ));
$night_alarm=  date('H:i', strtotime($night_alarm));

if($morning_alarm ==$now_utc)
{
$template="Good Morning! Please remember to take your medicine: ($morning_med)";
}

if($afternoon_alarm==$now_utc)
{
$template="Good Afternoon! Please remember to take your medicine: ($afternoon_med)";
}

if($night_alarm==$now_utc)
{
$template="Good Evening! Please remember to take your medicine: ($night_med)";
}


$template=urlencode($template) . "&href=page.php";  // this will redirect users to page.php once they click on noticiation
//echo $template; //DEBUG






                                        $batch[]=$fb->request('POST', "/".$fbUserID."/notifications?template=$template");

                            }


                            try {
                              $responses = $fb->sendBatchRequest($batch);
                            } catch(Facebook\Exceptions\FacebookResponseException $e) {
                              // When Graph returns an error
                              echo 'Graph returned an error: ' . $e->getMessage();
                              exit;
                            } catch(Facebook\Exceptions\FacebookSDKException $e) {
                              // When validation fails or other local issues
                              echo 'Facebook SDK returned an error: ' . $e->getMessage();
                              exit;
                            }

                            foreach ($responses as $key => $response) {
                              if ($response->isError()) {
                                $e = $response->getThrownException();
                                echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
                                echo '<p>Graph Said: ' . "\n\n";
                                var_dump($e->getResponse());
                              } else {
                                echo "<p> HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
                                echo "Response: " . $response->getBody() . "</p>\n\n";
                                echo "<hr />\n\n";
                              }
                            }
                            }

                            }

                             notify();
                             exit;
    }
}
exit;
?>

Please refer to this answer to learn how to setup a cron task in linux server.

I used this one :

curl --silent https://www.example.com/cron.php?key=somekey

Thanks for all hints; appreciated.



Answered By - wpcoder
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 28, 2022

[FIXED] Laravel - should send notification method

 January 28, 2022     laravel, notifications     No comments   

Issue

I have this configuration where the user can set which notification it wants to receive, I don't want to do an If on every method that I call notify.

I'd like to know if is there a method inside my notification class that I can do this validation, or how could I do that.

I thought about a solution, but it seens durty, I could validate inside via and just return an empty array if the user setted to not receive

And I also find out a method inside Illuminate\Notifications\NotificationSender called shouldSendNotification but I don't know how I could overwrite it, or even if it is using this class, cause it seens to be only for queue

OBS: Laravel 7


Solution

via would previously have been the best place for this, but Laravel now supports shouldSend on the notification for exactly this behaviour.

/**
 * Determine if the notification should be sent.
 *
 * @param  mixed  $notifiable
 * @param  string  $channel
 * @return bool|null
 */
public function shouldSend($notifiable, $channel)
{
    if ($user->isUnsubscribed()) {
        return false;
    }
}


Answered By - Dwight
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 13, 2022

[FIXED] Running a script when I receive PayPal payment

 January 13, 2022     notifications, paypal, php     No comments   

Issue

I want to set things up so that when a user pays me through PayPal, a PHP script will be run. How can I set up this kind of notification?


Solution

It's called an IPN. You just need to go into your settings, enable the IPN, tell it what file will be handling the call back and then write your php file.



Answered By - HTMLGuy
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 8, 2022

[FIXED] Laravel - Multiple Arrays for Multiple Recipients (Mailable/Notifications)

 January 08, 2022     email, laravel, laravel-5, notifications     No comments   

Issue

I'm looking for advice for a project and an interesting predicament I've put myself in.

I have multiple fields in my shipment model, they are:

  • shipto_id
  • shipfrom_id
  • billto_id

They all link (through different relationships) to my customer model:

public function billtoAccount()
{
    return $this->belongsTo('App\Customer', 'bill_to');
}

public function shiptoAccount()
{
    return $this->belongsTo('App\Customer', 'ship_to');
}

public function shipfromAccount()
{
    return $this->belongsTo('App\Customer', 'ship_from');
}

and these customers (in reality would likely be better described as customer accounts (these are NOT USER ACCOUNTS, they're more just like a profile for each company that business is done with)) can have a multitude of users associated with them.

 public function users()
{
    return $this->belongsToMany(User::class);
}

Now, while I know how to send off mailables and notifications, I was curious to know how I would go about sending off those to multiple user's emails. So let me describe the following: Something is created and the following customers (and in turn, their users) are referenced.

  • (billto_id) - Customer Account 1 - User 1 (email1@example.com)
  • (shipto_id) - Customer Account 2 - User 2 (email2@example.com) & User 3 (email3@example.com)
  • (shipfrom_id) - Customer Account 37 - User 6 (email4@example.com)

Now, how would I go about moving the emails of the users over to an array of emails to have a notification or mailable sent to them?

So it should pop out: email1@example.com, email2@example.com, email3@example.com, email4@examples.com


Solution

Elaborating on @Devon 's comment: This is business logic. You could have a method on your Shipment model that returns the customer instances to be notified as an array, e.g. getNotifiables() : array

Then in your Customer model you may use the Notifiable trait

use Illuminate\Notifications\Notifiable;

And looping over your Notifiables, i.e. Customers

$notification = new ShipmentWasCreated()
foreach ($shipment->getNotifiables() as $notifiable) {
    $notifiable->notify($notification);
}


Answered By - macghriogair
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing