When to send Laravel notifications (prevent duplicates) - notifications

My project uses the native Laravel notifications (stored in a db table). I want to send a notification to all users when a new article is created, however the article model has a boolean attribute 'published', so I only want to send the notifications when a new article has been created and this attribute has been set to true.
So using an observer to send the messages when a new article is created is not going to work, because it has nog been published at that point. Another option is listening to the 'updated' event and sending notifications when the 'published' attribute is true, but only the first save, otherwise you keep sending notifications on each save.
The only solution seems to be to keep track of what notifications are sent for each related model, but it's hard to use the notification table to do this, since you have to use a json object to store a reference to the related model. So what's the best practice? Creating additional columns to the notification table? Creating a seperate table for this?

Specifically to your issue I'd check if the field published is dirty when the attribute is about to be updated. Because, if it's already posted, then that state won't change so it will basically ignore all subsequent updates. You can do this like so:
class PostObserver
{
// ...
public function updating(Post $post)
{
if($post->isDirty('published')){
// status has been changed -> fire notification
Notification::send(User::all(), new PostPublished($post));
}
}
}

Related

Kotlin for Volley, how can I check the JSON request for newer data in the API?

I'm working on an app that gets a list of documents/source URL from an api. I'd like to periodically check for new or updated contents within that API so users can update saved items in the database. I'm at a loss on the correct wording to search, thus Google and Stack Overflow have both failed me. My fetching function is below:
The URL for the API is https://api.afiexplorer.com
private fun fetchPubs() {
_binding.contentMain.loading.visibility = View.VISIBLE
request = JsonArrayRequest(
Request.Method.GET,
Config.BASE_URL,
JSONArray(),{ response ->
val items: List<Pubs> =
Gson().fromJson(response.toString(), object : TypeToken<List<Pubs>>() {}.type)
val sortedItems = items.sortedWith(compareBy { it.Number })
pubsList?.clear()
pubsList?.addAll(sortedItems)
// Hardcoded pubs moved to Publications Gitlab Repo
// https://gitlab.com/afi-explorer/pubs
_binding.contentMain.recyclerView.recycledViewPool.clear()
adapter?.notifyDataSetChanged()
_binding.contentMain.loading.visibility = View.GONE
setupData()
Log.i("LENGTH OF DATA", "${items.size}")
},
{error ->
println(error.printStackTrace())
Toasty.error(applicationContext, getString(string.no_internet), Toast.LENGTH_SHORT, true).show()
}
)
MyApplication.instance.addToRequestQueue(request!!)
}
private fun setupData(){
adapter = MainAdapter(applicationContext, pubsList!!, this)
_binding.contentMain.recyclerView.adapter = adapter
}
I tried using ChatGPT to see if that would get me started and that failed miserably. Also searched Google, Reddit and Stack Overflow for similar projects, but mine is a unique scenario I guess. I'm just a hobbyist and intermediate dev I guess. First time working with Volley, everything works, but I would like to find a way to send a notification (preferably not Firebase) if there is updated info within the API listed above. I'm not sure if this is actually doable.
Are you asking if you can somehow find if the remote API has changed its content? If so, how would that service advise you? If the service provider provides a web hook or similar callback you could write a server-based program to send a push notification to your Android app.
Perhaps you intent to poll the API periodically, and then you want to know if there is a change?
If you use a tool such as Postman or curl to easily see the headers of the API https://api.afiexplorer.com you will see, unfortunately, there is no Last-Modified header or ETag header which would allow you to easily determine if there was a change.
Next looking at the content of the API, the author does not provide an obvious version/change date, so no luck there.
What you could do is receive the content as a String, and perform a checksum operation on it, and if it differs you know there has been a change
or if you are deserialising the received JSON in Kotlin data classes, then out of the box, Kotlin will enable you to perform an equality operation on a previous copy of the data to know if there was a change.
This looks like an android app; if so, why don't you create a background service that makes requests to the API and updates the data as needed? You can use an AlarmManager class to set the interval threshold for polling by using the setInexactRepeating() method.
Most apps are updated in this fashion; sometimes, a separate table is created to catalog changesets.
Let me know if this helps.

How to queue requests in React Native without Redux?

Let's say I have a notes app. I want to enable the user to make changes while he is offline, save the changes optimistically in a Mobx store, and add a request to save the changes (on the server) to a queue.
Then when the internet connection is re-established I want to run the requests in the queue one by one so the data in the app syncs with data on the server.
Any suggestions would help.
I tried using react-native-job-queue but it doesn't seem to work.
I also considered react-native-queue but the library seems to be abandoned.
You could create a separate store (or an array in AsyncStorage) for pending operations, and add the operations to an array there when the network is disconnected. Tell your existing stores to look there for data, so you can render it optimistically. Then, when you detect a connection, run the updates in array order, and clear the array when done.
You could also use your existing stores, and add something like pending: true to values that haven't posted to your backend. However, you'll have less control over the order of operations, which sounds like it is important.
As it turns out I was in the wrong. The react-native-job-queue library does work, I just made a mistake by trying to pass a function reference (API call) to the Worker instead of just passing an object that contains the request URL and method and then just implement the Worker to make the API call based on those parameters.

IBM Worklight: Extend Server-side Java Code

Can I extend the server-side Java Code in Worklight?
For example, there is a class called JavaScriptIntegrationLibraryImplementation under com.worklight.integration.js. Inside this class, there is a method broadcastNotification and I would like to override this method. Is it possible to do so?
EDIT
The reason is that:
When I make the subscription in client side with option field (e.g. add customType: A), I would like to retrieve a list of devices which have been subscribed to this event source. Base on the option field in deviceSubscrpition, I would like to have some business logic to determine who to send the notification message. For example, I will only submit the message to the user which 'customType=A'.
However, there is no API in Worklight which can retrieve a list of devices which make me to retrieve the list first. Then do the logic in JavaScript and called WL.Server.notifyDevice..
Therefore, I would like to check whether there is any method to retrieve a list of devices (through API / Adapter which connects to DB) which have subscribed to an event source.
Thanks.
This part of Worklight is not extendable. You can try and override this method as you say, but do note this is not supported and we cannot help in this case.
Edit
Now that it is clear what you're trying to achieve... what you are looking for currently not available. I will open a feature request for it and it will get evaluated at some point (if you are a customer of IBM, I suggest to get in touch with your contact...).
My suggestion (somewhat hackish in form): you could perhaps use multiple Event Sources, where each event source represents an iOS version. On the client-side, upon app initialization, you can retrieve the iOS version and use it to register to the correct event source (this would be very generic code to allow re-use). In case a new iOS version is released (you will likely know of this in advance), you simply add this event source to the adapter code and re-deploy the adapter. Users of the new iOS version could still register for notification, because you get the iOS version upon init, and use this information to register to the correct event source...
To reiterate:
The adapter contains: ES_iOS5 ES_iOS6
The client:
fetches iOS version, stores it in some variable.
registers to event source, where event source name is ES_${iOSVersion}
if a new iOS version is released, simply create a new event source and re-deploy
the adapter; the client is already equipped to handle this.
#Red23jordon,
i had similar case, i created a custom table where at the time of subscription, I was saving
user ID and event type in custom table. and when user unsubscribe then i also remove details from custom table.
For sending push to users subscribed to a particular "even type" i look into custom table to get list of user IDs subscribed to particular event type, and then i went into Notification user/device tables and fetching corresponding devices and sending Push.
Hope it may help you.
thanks

Core Data NSManagedObject - tracking if attribute was changed

I have an object - Config. I want to know if the Account attribute on Config has changed. When this happens, I want to send a NSNotification so that all code that cares about when the Account changes will know. My initial thought was in my NSManagedObject subclass that I would override the setAccount method to set a transient attribute AccountDidChange to true. Then in didSave if AccountDidChange was true I would send the notification and then set it back to false. Is there a better way? My issue though is that from what I've read, by changing AccountDidChange back to false, I would have dirtied my object and need to save again.
A little more info:
The Config object is the current configuration of the application. Account could actually be changed to ActiveAccount. There is a relationship to the Account Entity that has a list of all Accounts. The idea is that the user can change the active account of the application. So we have a set of servers and the user can only be logged into one at a time. Config.Account points to that active account and it is used to setup connections to the server to retrieve information. I am using this notification that Config.Account has changed to tell other objects to clean up their information - like list of alerts. Basically, all information is per Account so it needs to be removed and then refetched on its next load with the new active account.
Also, the given names are not my actual object names - just trying to make the example easier to follow.
Take a look at KVO (Key-Value Observing): Key-Value Observing Programming Guide. That's the standard way to do this in Cocoa, and is a fundamental technology that you need to understand to be a good Cocoa programmer.
KVO will let objects that care about changes to the Account property (which you should probably name account, not Account) register to be notified when the property is changed. KVO will "just work" for standard NSManagedObjects, without any additional work on your part.
The relevant methods are as follows:
-addObserver:forKeyPath:options:context: which you call on your Config object to set up the observation
-observeValueForKeyPath:ofObject:change:context: which will be called on the observer object anytime an observed value is changed
-removeObserver:forKeyPath: which you need to make sure you call when the observer no longer needs change notifications (including before the observer is deallocated).
This is all described in a lot more detail in the linked documentation.
EDIT BELOW:
Without knowing anything about your application, it's hard to know why you'd want to be notified only upon save. NSManagedObjectContext posts NSManagedObjectContextWillSaveNotification and NSManagedObjectContextDidSaveNotification. The notification's userInfo has arrays containing inserted, updated and deleted objects, but the notifications aren't as fine-grained as individual properties. I suppose you could manually keep track of changed accounts between didSave notifications. That'll probably get inefficient if you have lots of Configs in your store.
Changes to NSManagedObjects are immediate, they're just not saved to the persistent store until you call save: on the managed object context. Perhaps if you explain more about exactly what you're trying to accomplish and why, I can better help.

WorkflowCreationEndpoint ResumeBookmark with a filled response

I've spend days trying to find a solution the problem i'm going to try to describe, i've googled alot and even looked at the .NET 4 reference source for SendReply and InternalSendReply activity. But until now i'm stuck.
To make the life of our end customers simpler i want to replace the Receive and SendReply activities with custom activites and use bookmarks instead.
I'm implementing a central webservice which can route to a correct workflow instance, that workflow modifies the bookmark value and finaly it creates a new bookmark while returning the modified bookmark value. It's rather complex already with a WorkflowServiceHostFactory which adds Behaviours and Attach a DataContractResolver to the endpoint.
The endpoint is derived from WorkflowHostingEndpoint which resolves a bookmark created in a custom activity (instead of a receive). And i want another activity instead of a sendreply. Those 2 should correlate and the custom sendreply does send a response on the open channel through the endpoint while creating a new bookmark.
The problem is that i didn't find a way yet to access the endpoint responseContext from within my custom send activity. On the other side, at the workflowcreating endpoint side, it seems that i'm not able to be notified whenever the workflow becomes Idle and as well i don't seem to be able to access the WorkflowExtensions from the host. i'm missing something?
A possible solution i've in mind might be not using a WorkflowServiceHost, but then i loose alot of AppFabric functionaly.
The workflowapplication in platform update 1 has some extension methods called RunEpisode with an overload Func called idleEventCallback. There it's possible to hook into the OnIdle and get a workflowextension to get the object to send back as response.
To answer my own question, i ended up in a workaround using the servicebroker functionality of sql server. The SqlDependency class where the workflow listens for the event to be fired whenever the workflow reach the activity that creates a new bookmark in another state.