Notification Api System Correct Process - php

I built a small notification api system that has id, user_id, subject, text, status, created_at columns in the data base.
My current process is that when a user requests for her notifications i get the most recent 100 unread messages and send to the user, then wait for the front end to send me a list of ids of those that have been read by the user so that i can change their status to read.
but sometimes this does not happen meaning the when the user requests for another set of messages they will get back their already read messages.
So i am thinking of marking the messages as read once i retrieve them for the user rather than wait for update from the frontend.
but i am not sure if this is the best way to handle this! is there a better process for api notification systems please advice me. Thanks.

I would think about it like this: What is that listing of unread items depicting? What the state understands to have been left unread. Is pulling a listing of unread items really meant to denote all those items were read? I think not. You may allow a bulk mark read, but reading the list is just a stateful representation, of fact. Read the list, and authoritatively mark read when touched by a visible interface component by sending a per-item request to thing/mark-read.
If you're having issues with the (central) store not representing state accurately because you think they should be read, debug your interface. I would not mark read on pulling the list, though. That would be a flawed approach.
If you do directly insert all 100 into the display where you consider them read, create an endpoint in your api for thing/mark-items-read and pass it those 100 item ID's.

We can't see your code here, but I would suggest the following:
Store the ids of messages displayed to the use in an array on the frontend, so when a user views a message, you add the id to that array. I'm not sure what your frontend is using so can't really make a code suggestions.
Create an endpoint that receives this array on the backend in your routes file
Route::post('somepath/read-messages', 'MessageController#readMessages');
Then, in your message controller:
public function readMessages(Request $request) {
if ($request->has('read_messages') {
$messages = Message::whereIn('id', $request->read_messages)->get();
$messages->update(array('staus' => 'read');
}
}

Related

Should GET requests store to database?

I’ve read that you should not use GET requests if you are modifying the database. How would you record analytics about your website then?
For example, I want to record page views whenever someone visits a page. I would need to update views = views + 1 in the database. Is this OK, despite using a GET request, or is there another technique? Surely, not every request should be a POST request.
The general advice about how to use POST vs. GET shows up in RFC 1945 from 23 years ago:
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.
 
POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Providing a block of data, such as the result of submitting a form [3], to a data-handling process;
Extending a database through an append operation.
These guidelines remain in effect to this day, but they cover the primary purpose of the user's page request.
The act of incrementing a view counter is incidental to the primary purpose of the request, which is to view the page content. Indeed, the user is likely unaware that this database update is occurring.
(Of course, you must expect that you will receive duplicate requests as users move through browser history, caches are populated, or spiders crawl your pages. This wouldn't be the case if a POST request was made.)
It's ok.
When you make POST request, you actually wait for POST params to come and you build your database insert query based on parameters which you've got from browser.
On GET request you actually implement your own business logic, so user won't ever know what is going on the side.
And for the finish, actually sometimes you can do something, what's going against rules, rules are good, but we are able not to follow them, that's what makes us human, if we would strictly follow all the rules, it would be cumbersome.

Updating a changing Friend List that currently only gets called from an Activity's onCreate?

I'll try to keep this as simple as possible. Bear with me as I'm still quite inexperienced with Android.
I've created a side panel drawerLayout that displays a Friend List for users of my application. This includes sent requests and received requests:
So far, every time the activity is created, a PHP request to the remote server is populating this list with friend of all status types, like so:
MyAdapter adapter = new MyAdapter(this, populateFriendList());
I'm going to have buttons beside each friend in the list that can accept requests, decline them, etc. As an example: when confirming a friend, I've been able to remove them from the 'Sent Requests' section of the list view, and even update the database to reflect this.
But how am I supposed to update the ListView to then see the most up-to-date friendList, with the newly confirmed friend as a friend?
Worth noting is that rotating the device causes the friend list to update as the onCreate method is called again, meaning populateFriendList() gets called once more. I appreciate that this way probably isn't wise, but I'm not sure what I'm supposed to do instead.
There are a couple ways to handle this. You could use GCM to send a push notification when there is a new friend request, or you can do long polling in a service pinging your server every interval to see if there is a new request.
your rotation is calling onCreate() every time because thats what's happening in the activity. You can override OnConfigurationChanged() and that should handle rotation changes.
You can call onNotifyDataSetChanged() to let the adapter know there there is new data to be viewed.

Creating custom status codes

I'm having an API on which I need to set custom status code. Apart from the normal standard http status codes, is it the best practice to create our own status code?
i.e, If my client is sending a blank parameter (orderID), can I set a random status code number of my own say 123? Or is there any standard way to create customer status codes?
There are quite a lot of existing codes, so usually you won't need to invent new ones. You might, though, but when you do, make sure to use the right ranges.
For instance, the 200+ range indicates success of any kind, 300+ is a redirect, 400+ range is a client error (bad url format, target not found), and 500+ is a server error.
By following these guidelines, you can use all kinds of clients to communicate to your api. A browser should normally display the results of any 2XX status code, and treat it as a succesful request, even if the particular XX is unknown to it.
For a rather complete list of status codes and their normal meaning, as well as a general description of each of the ranges, see this:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
599 is the highest assigned status code. I wouldn't know if it's allowed to use the 600+ range, but I cannot find anything about it. I cannot imagine that your status wouldn't fit in any of the existing categories, though.
REST:
Aside from the return code, you can (should?) also have a look at the different methods. You probably know GET (sending data in url) and POST (sending extra data with the request), because they are commonly used. But you also got PUT and DELETE, which are especially useful for an api like this. If you search for terms like Restfull API, you should get plenty of documentation about this subject. Also, see this W3 link for an overview of request methods.
Bringing it together:
For creating a customer through the api, you could send a PUT request with the data of the new customer. The api can return 201 Created with an ID (or slug) for the customer. If you want to delete the customer, send a DELETE request and return 204 No content, since you just need to confirm that the delete succeeded, without sending any content.
Or is there any standard way to create customer status codes?
No. I'd go for a generic HTTP error as 400 Bad Request and provide a meaningful error message in the response body. This wasy you don't have to make up HTTP codes as you go, and your consumers can process different error responses identically.
Don't define custom status codes unless you're willing to going through the process of standardizing them (http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p2-semantics-26.html#considerations.for.new.status.codes).
Otherwise just use a generic one and send additional details in the response body.

Most efficient method to check whether user has new mail?

I have a simple and generic internal messaging service on one of my PHP/MySQL sites, with a unique messageID, from, to, subject, message, time, and isRead.
In general, what is the best way to check that a user has new mail?
Should I store a simple binary trigger on the main Users table that gets switched to 1 when anyone sends them a message, and then have the user check for that 1 on every pageload, and if there is one, alert them to the new mail (and set it to 0 whenever they go to their Inbox)? But what if it was spam and we deleted it before the user read it?
Or should I store the messageid of the last message the user read, and then do a check for the latest message and see if it's more recent than the last one that he read, and if so alert him? But then how and where should I store this info?
Is there another, more efficient method considering we would have to check for new messages on every pageload?
If the user goes to his Inbox, it should no longer show him that he has "New Mail" for any of the messages that were in his Inbox at the time he checked it, regardless of whether he's actually clicked to read them or not.
Thanks!
EDIT: Some of my users access my site from very basic phones that don't have cookies or even Javascript, so please keep that in mind.
Best way would be push notification from server, like stackoverflow does, using html sockets.
jquery plugin
But keep in mind that is not supported by all browser, so will need to fall back to ajax polling.
About spam i would suggest only notify user after spam checking if done, if possible.
Your solution to store next to user with set bit sounds right, (also you could store number of new message, instead of bit)
In your users table, store the count of new messages, and update when needed.
AJAX polling can be expensive in serverside (the select count(*) from ... can be expensive when your DB became large, and you need to do it, for example, one check per minute).
If the user just browsing in your website, and have no new messages, you can just skip select more information about messages.

Model PHP/Ajax Notification System?

I'm making a website similar to Facebook - with things such as Notifications which make it similar. I don't really see how I can get notifications working. Well, I figured out how I could get them from the database, with a query.
The structure I think the site will follow would be multiple tables for different applications - ie: Photos would add in an ID for the picture, a filename, and a few user IDs if 'tagged' or something, and how to send that information to the user in real time.. is beyond me.
So I would have to run several queries every few seconds scanning the database tables for the $_SESSION['id'] of the user being found in all the applications tables with a status of unread?
Another possibility is that every user has their own table? That's .. a lot. lol.
Or just a notifications table with the most recent notification being pushed to the table with a unique id and a user id?
I really can't wrap my head around this, lol.
Also, displaying notifications in real time? I understand Facebook uses long-polling and gets the notifications in real time, but I don't think I could leave about 5-10 queries (for each app) running on a long poll for multiple clients, or that'd completely crash my server, right?
Any advice/code on how I could try and make a notification system for a social networking-ish site? If not, I think i'll go with static notifications rather than any sort of realtime.
Then again, that'd be too much load querying the server every few seconds for a new notification on every page load? Using ajax would mean long polling, so it's a lose-lose.
I would say Long polling is the answer. Gmail and Facebook both use this method for real-time notifications. Your only other alternative is Flex with a dataservice, but that is not PHP.
In terms of performance, the query is only going to pull from 0-5 notifications at a time, and if the tables are indexed properly, and the query is written well, then 5 of these queries will not be a significant impact on your server.
Furthermore, if Gmail and facebook are doing it, then it stands to reason you can also do this. Granted, they have a ton of servers to support all their users, but I am going to go out on a limb and say you don't have as many users as they do, so as a result the server technology will work for now. And when you get so many users your current servers can't handle the load, then you invest in newer more powerful ones.
Well here is my take on it.
You could create different tables for status, photos and videos.
Everytime somebody comments on a video or something you can do the query to store the notification along with the information of the user who liked it, you should set a status field too, so you can query based on which has been seen and which has not been seen by the user.
You can put the url of the page where the photo is or status is located so when the user is logged in you do a query every five minutes checking for unread notifications, if there are any you display them in a tiny toast message on left bottom side of the screen like facebook.
On click of the toast message you can do an ajax call to update that status of the notifcation to read so it does not show up again and in the success call back you can take the user to the page where the status update is.

Categories