1
0
Fork 0

new api for notifications

/api/friendica/notification
returns first 50 notifications for current user

/api/friendica&notification/<id>
set note <id> as seen and return item object if possible

new class NotificationsManager to query for notifications and set seen
state
This commit is contained in:
fabrixxm 2016-02-07 14:27:13 +01:00
parent d6cf791677
commit 44592611e1
4 changed files with 223 additions and 55 deletions

View file

@ -0,0 +1,113 @@
<?php
require_once("include/datetime.php");
class NotificationsManager {
private $a;
public function __construct() {
$this->a = get_app();
}
private function _set_extra($notes) {
$rets = array();
foreach($notes as $n) {
$local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
$n['timestamp'] = strtotime($local_time);
$n['date_rel'] = relative_date($n['date']);
$rets[] = $n;
}
return $rets;
}
/**
* @brief get all notifications for local_user()
*
* @param array $filter optional Array "column name"=>value: filter query by columns values
* @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
* @param string $limit optional Query limits
*
* @return array of results or false on errors
*/
public function getAll($filter = array(), $order="-date", $limit="") {
$filter_str = array();
$filter_sql = "";
foreach($filter as $column => $value) {
$filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
}
if (count($filter_str)>0) {
$filter_sql = "AND ".implode(" AND ", $filter_str);
}
$aOrder = explode(" ", $order);
$asOrder = array();
foreach($aOrder as $o) {
$dir = "asc";
if ($o[0]==="-") {
$dir = "desc";
$o = substr($o,1);
}
if ($o[0]==="+") {
$dir = "asc";
$o = substr($o,1);
}
$asOrder[] = "$o $dir";
}
$order_sql = implode(", ", $asOrder);
if ($limit!="") $limit = " LIMIT ".$limit;
$r = q("SELECT * from notify where uid = %d $filter_sql order by $order_sql $limit",
intval(local_user())
);
if ($r!==false && count($r)>0) return $this->_set_extra($r);
return false;
}
/**
* @brief get one note for local_user() by $id value
*
* @param int $id
* @return array note values or null if not found
*/
public function getByID($id) {
$r = q("select * from notify where id = %d and uid = %d limit 1",
intval($id),
intval(local_user())
);
if($r!==false && count($r)>0) {
return $this->_set_extra($r)[0];
}
return null;
}
/**
* @brief set seen state of $note of local_user()
*
* @param array $note
* @param bool $seen optional true or false, default true
* @return bool true on success, false on errors
*/
public function setSeen($note, $seen = true) {
return q("update notify set seen = %d where ( link = '%s' or ( parent != 0 and parent = %d and otype = '%s' )) and uid = %d",
intval($seen),
dbesc($note['link']),
intval($note['parent']),
dbesc($note['otype']),
intval(local_user())
);
}
/**
* @brief set seen state of all notifications of local_user()
*
* @param bool $seen optional true or false. default true
* @return bool true on success, false on error
*/
public function setAllSeen($seen = true) {
return q("update notify set seen = %d where uid = %d",
intval($seen),
intval(local_user())
);
}
}

View file

@ -23,6 +23,7 @@
require_once('include/message.php'); require_once('include/message.php');
require_once('include/group.php'); require_once('include/group.php');
require_once('include/like.php'); require_once('include/like.php');
require_once('include/NotificationsManager.php');
define('API_METHOD_ANY','*'); define('API_METHOD_ANY','*');
@ -680,6 +681,29 @@
} }
/**
* @brief transform $data array in xml without a template
*
* @param array $data
* @return string xml string
*/
function api_array_to_xml($data, $ename="") {
$attrs="";
$childs="";
foreach($data as $k=>$v) {
$k=trim($k,'$');
if (!is_array($v)) {
$attrs .= sprintf('%s="%s" ', $k, $v);
} else {
if (is_numeric($k)) $k=trim($ename,'s');
$childs.=api_array_to_xml($v, $k);
}
}
$res = $childs;
if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
return $res;
}
/** /**
* load api $templatename for $type and replace $data array * load api $templatename for $type and replace $data array
*/ */
@ -692,13 +716,17 @@
case "rss": case "rss":
case "xml": case "xml":
$data = array_xmlify($data); $data = array_xmlify($data);
$tpl = get_markup_template("api_".$templatename."_".$type.".tpl"); if ($templatename==="<auto>") {
if(! $tpl) { $ret = api_array_to_xml($data);
header ("Content-Type: text/xml"); } else {
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>'; $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
killme(); if(! $tpl) {
header ("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
killme();
}
$ret = replace_macros($tpl, $data);
} }
$ret = replace_macros($tpl, $data);
break; break;
case "json": case "json":
$ret = $data; $ret = $data;
@ -3386,6 +3414,43 @@
api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST); api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST); api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
/**
* returns notifications
* if called with note id set note seen and returns associated item (if possible)
*/
function api_friendica_notification(&$a, $type) {
if (api_user()===false) throw new ForbiddenException();
$nm = new NotificationsManager();
if ($a->argc==3) {
$notes = $nm->getAll(array(), "+seen -date", 50);
return api_apply_template("<auto>", $type, array('$notes' => $notes));
}
if ($a->argc==4) {
$note = $nm->getByID(intval($a->argv[3]));
if (is_null($note)) throw new BadRequestException("Invalid argument");
$nm->setSeen($note);
if ($note['otype']=='item') {
// would be really better with a ItemsManager and $im->getByID() :-P
$r = q("SELECT * FROM item WHERE id=%d AND uid=%d",
intval($note['iid']),
intval(local_user())
);
if ($r===false) throw new NotFoundException();
$user_info = api_get_user($a);
$ret = api_format_items($r,$user_info);
$data = array('$statuses' => $ret);
return api_apply_template("timeline", $type, $data);
} else {
return api_apply_template('test', $type, array('ok' => $ok));
}
}
throw new BadRequestException("Invalid argument count");
}
api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
/* /*
To.Do: To.Do:
[pagename] => api/1.1/statuses/lookup.json [pagename] => api/1.1/statuses/lookup.json

View file

@ -1,43 +1,34 @@
<?php <?php
require_once('include/NotificationsManager.php');
if(! function_exists('notify_init')) { if(! function_exists('notify_init')) {
function notify_init(&$a) { function notify_init(&$a) {
if(! local_user()) if(! local_user()) return;
return;
$nm = new NotificationsManager();
if($a->argc > 2 && $a->argv[1] === 'view' && intval($a->argv[2])) { if($a->argc > 2 && $a->argv[1] === 'view' && intval($a->argv[2])) {
$r = q("select * from notify where id = %d and uid = %d limit 1", $note = $nm->getByID($a->argv[2]);
intval($a->argv[2]), if ($note) {
intval(local_user()) $nm->setSeen($note);
);
if(count($r)) {
q("update notify set seen = 1 where ( link = '%s' or ( parent != 0 and parent = %d and otype = '%s' )) and uid = %d",
dbesc($r[0]['link']),
intval($r[0]['parent']),
dbesc($r[0]['otype']),
intval(local_user())
);
// The friendica client has problems with the GUID. this is some workaround // The friendica client has problems with the GUID. this is some workaround
if ($a->is_friendica_app()) { if ($a->is_friendica_app()) {
require_once("include/items.php"); require_once("include/items.php");
$urldata = parse_url($r[0]['link']); $urldata = parse_url($note['link']);
$guid = basename($urldata["path"]); $guid = basename($urldata["path"]);
$itemdata = get_item_id($guid, local_user()); $itemdata = get_item_id($guid, local_user());
if ($itemdata["id"] != 0) if ($itemdata["id"] != 0)
$r[0]['link'] = $a->get_baseurl().'/display/'.$itemdata["nick"].'/'.$itemdata["id"]; $note['link'] = $a->get_baseurl().'/display/'.$itemdata["nick"].'/'.$itemdata["id"];
} }
goaway($r[0]['link']); goaway($note['link']);
} }
goaway($a->get_baseurl(true)); goaway($a->get_baseurl(true));
} }
if($a->argc > 2 && $a->argv[1] === 'mark' && $a->argv[2] === 'all' ) { if($a->argc > 2 && $a->argv[1] === 'mark' && $a->argv[2] === 'all' ) {
$r = q("update notify set seen = 1 where uid = %d", $r = $nm->setAllSeen();
intval(local_user())
);
$j = json_encode(array('result' => ($r) ? 'success' : 'fail')); $j = json_encode(array('result' => ($r) ? 'success' : 'fail'));
echo $j; echo $j;
killme(); killme();
@ -47,38 +38,37 @@ function notify_init(&$a) {
if(! function_exists('notify_content')) { if(! function_exists('notify_content')) {
function notify_content(&$a) { function notify_content(&$a) {
if(! local_user()) if(! local_user()) return login();
return login();
$notif_tpl = get_markup_template('notifications.tpl'); $nm = new NotificationsManager();
$not_tpl = get_markup_template('notify.tpl'); $notif_tpl = get_markup_template('notifications.tpl');
require_once('include/bbcode.php');
$r = q("SELECT * from notify where uid = %d and seen = 0 order by date desc", $not_tpl = get_markup_template('notify.tpl');
intval(local_user()) require_once('include/bbcode.php');
);
if (count($r) > 0) { $r = $nm->getAll(array('seen'=>0));
foreach ($r as $it) { if ($r!==false && count($r) > 0) {
$notif_content .= replace_macros($not_tpl,array( foreach ($r as $it) {
'$item_link' => $a->get_baseurl(true).'/notify/view/'. $it['id'], $notif_content .= replace_macros($not_tpl,array(
'$item_image' => $it['photo'], '$item_link' => $a->get_baseurl(true).'/notify/view/'. $it['id'],
'$item_text' => strip_tags(bbcode($it['msg'])), '$item_image' => $it['photo'],
'$item_when' => relative_date($it['date']) '$item_text' => strip_tags(bbcode($it['msg'])),
)); '$item_when' => relative_date($it['date'])
} ));
} else {
$notif_content .= t('No more system notifications.');
} }
} else {
$notif_content .= t('No more system notifications.');
}
$o .= replace_macros($notif_tpl, array( $o .= replace_macros($notif_tpl, array(
'$notif_header' => t('System Notifications'), '$notif_header' => t('System Notifications'),
'$tabs' => '', // $tabs, '$tabs' => false, // $tabs,
'$notif_content' => $notif_content, '$notif_content' => $notif_content,
)); ));
return $o; return $o;
} }
} }

View file

@ -206,8 +206,8 @@ function ping_init(&$a) {
$local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']); $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
call_hooks('ping_xmlize', $n); call_hooks('ping_xmlize', $n);
$notsxml = '<note href="%s" name="%s" url="%s" photo="%s" date="%s" seen="%s" timestamp="%s" >%s</note>'."\n"; $notsxml = '<note id="%d" href="%s" name="%s" url="%s" photo="%s" date="%s" seen="%s" timestamp="%s" >%s</note>'."\n";
return sprintf ( $notsxml, return sprintf ( $notsxml, intval($n['id']),
xmlify($n['href']), xmlify($n['name']), xmlify($n['url']), xmlify($n['photo']), xmlify($n['href']), xmlify($n['name']), xmlify($n['url']), xmlify($n['photo']),
xmlify(relative_date($n['date'])), xmlify($n['seen']), xmlify(strtotime($local_time)), xmlify(relative_date($n['date'])), xmlify($n['seen']), xmlify(strtotime($local_time)),
xmlify($n['message']) xmlify($n['message'])