From 44592611e1582fd97ae1988343418a0dae1ae2a0 Mon Sep 17 00:00:00 2001 From: fabrixxm Date: Sun, 7 Feb 2016 14:27:13 +0100 Subject: [PATCH 1/7] new api for notifications /api/friendica/notification returns first 50 notifications for current user /api/friendica¬ification/ set note as seen and return item object if possible new class NotificationsManager to query for notifications and set seen state --- include/NotificationsManager.php | 113 +++++++++++++++++++++++++++++++ include/api.php | 79 +++++++++++++++++++-- mod/notify.php | 82 ++++++++++------------ mod/ping.php | 4 +- 4 files changed, 223 insertions(+), 55 deletions(-) create mode 100644 include/NotificationsManager.php diff --git a/include/NotificationsManager.php b/include/NotificationsManager.php new file mode 100644 index 0000000000..8b0ca9e13d --- /dev/null +++ b/include/NotificationsManager.php @@ -0,0 +1,113 @@ +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()) + ); + } +} diff --git a/include/api.php b/include/api.php index 4d206da28e..5acc816575 100644 --- a/include/api.php +++ b/include/api.php @@ -23,6 +23,7 @@ require_once('include/message.php'); require_once('include/group.php'); require_once('include/like.php'); + require_once('include/NotificationsManager.php'); define('API_METHOD_ANY','*'); @@ -250,7 +251,7 @@ */ function api_call(&$a){ GLOBAL $API, $called_api; - + $type="json"; if (strpos($a->query_string, ".xml")>0) $type="xml"; if (strpos($a->query_string, ".json")>0) $type="json"; @@ -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"; + return $res; + } + /** * load api $templatename for $type and replace $data array */ @@ -692,13 +716,17 @@ case "rss": case "xml": $data = array_xmlify($data); - $tpl = get_markup_template("api_".$templatename."_".$type.".tpl"); - if(! $tpl) { - header ("Content-Type: text/xml"); - echo ''."\n".'not implemented'; - killme(); + if ($templatename==="") { + $ret = api_array_to_xml($data); + } else { + $tpl = get_markup_template("api_".$templatename."_".$type.".tpl"); + if(! $tpl) { + header ("Content-Type: text/xml"); + echo ''."\n".'not implemented'; + killme(); + } + $ret = replace_macros($tpl, $data); } - $ret = replace_macros($tpl, $data); break; case "json": $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/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("", $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: [pagename] => api/1.1/statuses/lookup.json diff --git a/mod/notify.php b/mod/notify.php index 7acac1084a..7c367708bb 100644 --- a/mod/notify.php +++ b/mod/notify.php @@ -1,43 +1,34 @@ argc > 2 && $a->argv[1] === 'view' && intval($a->argv[2])) { - $r = q("select * from notify where id = %d and uid = %d limit 1", - intval($a->argv[2]), - intval(local_user()) - ); - 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()) - ); - + $note = $nm->getByID($a->argv[2]); + if ($note) { + $nm->setSeen($note); + // The friendica client has problems with the GUID. this is some workaround if ($a->is_friendica_app()) { require_once("include/items.php"); - $urldata = parse_url($r[0]['link']); + $urldata = parse_url($note['link']); $guid = basename($urldata["path"]); $itemdata = get_item_id($guid, local_user()); 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)); } if($a->argc > 2 && $a->argv[1] === 'mark' && $a->argv[2] === 'all' ) { - $r = q("update notify set seen = 1 where uid = %d", - intval(local_user()) - ); + $r = $nm->setAllSeen(); $j = json_encode(array('result' => ($r) ? 'success' : 'fail')); echo $j; killme(); @@ -47,38 +38,37 @@ function notify_init(&$a) { if(! function_exists('notify_content')) { function notify_content(&$a) { - if(! local_user()) - return login(); + if(! local_user()) return login(); - $notif_tpl = get_markup_template('notifications.tpl'); + $nm = new NotificationsManager(); + + $notif_tpl = get_markup_template('notifications.tpl'); - $not_tpl = get_markup_template('notify.tpl'); - require_once('include/bbcode.php'); + $not_tpl = get_markup_template('notify.tpl'); + require_once('include/bbcode.php'); - $r = q("SELECT * from notify where uid = %d and seen = 0 order by date desc", - intval(local_user()) - ); - - if (count($r) > 0) { - foreach ($r as $it) { - $notif_content .= replace_macros($not_tpl,array( - '$item_link' => $a->get_baseurl(true).'/notify/view/'. $it['id'], - '$item_image' => $it['photo'], - '$item_text' => strip_tags(bbcode($it['msg'])), - '$item_when' => relative_date($it['date']) - )); - } - } else { - $notif_content .= t('No more system notifications.'); + $r = $nm->getAll(array('seen'=>0)); + if ($r!==false && count($r) > 0) { + foreach ($r as $it) { + $notif_content .= replace_macros($not_tpl,array( + '$item_link' => $a->get_baseurl(true).'/notify/view/'. $it['id'], + '$item_image' => $it['photo'], + '$item_text' => strip_tags(bbcode($it['msg'])), + '$item_when' => relative_date($it['date']) + )); } + } else { + $notif_content .= t('No more system notifications.'); + } - $o .= replace_macros($notif_tpl, array( - '$notif_header' => t('System Notifications'), - '$tabs' => '', // $tabs, - '$notif_content' => $notif_content, - )); + $o .= replace_macros($notif_tpl, array( + '$notif_header' => t('System Notifications'), + '$tabs' => false, // $tabs, + '$notif_content' => $notif_content, + )); return $o; } } + diff --git a/mod/ping.php b/mod/ping.php index 0d1659a763..adff0912f4 100644 --- a/mod/ping.php +++ b/mod/ping.php @@ -206,8 +206,8 @@ function ping_init(&$a) { $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']); call_hooks('ping_xmlize', $n); - $notsxml = '%s'."\n"; - return sprintf ( $notsxml, + $notsxml = '%s'."\n"; + return sprintf ( $notsxml, intval($n['id']), 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($n['message']) From 102c06a41f3fb6308a75a748a347ebc84b7362dd Mon Sep 17 00:00:00 2001 From: fabrixxm Date: Sun, 7 Feb 2016 14:29:07 +0100 Subject: [PATCH 2/7] fix error in template in notifications page --- view/templates/notifications.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/templates/notifications.tpl b/view/templates/notifications.tpl index 0b7e77a07b..54f9de0c7a 100644 --- a/view/templates/notifications.tpl +++ b/view/templates/notifications.tpl @@ -2,7 +2,7 @@

{{$notif_header}}

-{{include file="common_tabs.tpl"}} +{{if $tabs }}{{include file="common_tabs.tpl"}}{{/if}}
{{$notif_content}} From 756b90a4e073c5f1e7cfb0314262b90f408b8f83 Mon Sep 17 00:00:00 2001 From: Fabrixxm Date: Mon, 8 Feb 2016 09:47:59 +0100 Subject: [PATCH 3/7] add docs, rewrite part of the notification api list notifications and set note as seen functionalities are now splitted in two functions, with correct http method requirement. Fixed returned value from `notification/seen` --- include/NotificationsManager.php | 30 +++++++++++-- include/api.php | 74 +++++++++++++++++++++----------- 2 files changed, 76 insertions(+), 28 deletions(-) diff --git a/include/NotificationsManager.php b/include/NotificationsManager.php index 8b0ca9e13d..b7e31d4f65 100644 --- a/include/NotificationsManager.php +++ b/include/NotificationsManager.php @@ -1,6 +1,13 @@ a = get_app(); } + /** + * @brief set some extra note properties + * + * @param array $notes array of note arrays from db + * @return array Copy of input array with added properties + * + * Set some extra properties to note array from db: + * - timestamp as int in default TZ + * - date_rel : relative date string + * - msg_html: message as html string + * - msg_plain: message as plain text string + */ 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']); + $n['msg_html'] = bbcode($n['msg'], false, false, false, false); + $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0]; + $rets[] = $n; } return $rets; @@ -57,7 +79,7 @@ class NotificationsManager { if ($limit!="") $limit = " LIMIT ".$limit; - $r = q("SELECT * from notify where uid = %d $filter_sql order by $order_sql $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); @@ -71,7 +93,7 @@ class NotificationsManager { * @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", + $r = q("SELECT * FROM notify WHERE id = %d AND uid = %d LIMIT 1", intval($id), intval(local_user()) ); @@ -89,7 +111,7 @@ class NotificationsManager { * @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", + 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']), @@ -105,7 +127,7 @@ class NotificationsManager { * @return bool true on success, false on error */ public function setAllSeen($seen = true) { - return q("update notify set seen = %d where uid = %d", + return q("UPDATE notify SET seen = %d WHERE uid = %d", intval($seen), intval(local_user()) ); diff --git a/include/api.php b/include/api.php index 5acc816575..16481201e3 100644 --- a/include/api.php +++ b/include/api.php @@ -690,6 +690,11 @@ function api_array_to_xml($data, $ename="") { $attrs=""; $childs=""; + if (count($data)==1 && !is_array($data[0])) { + $ename = array_keys($data)[0]; + $v = $data[$ename]; + return "<$ename>$v"; + } foreach($data as $k=>$v) { $k=trim($k,'$'); if (!is_array($v)) { @@ -3415,41 +3420,62 @@ 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) - */ + * @brief Returns notifications + * + * @param App $a + * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' + * @return string + */ function api_friendica_notification(&$a, $type) { if (api_user()===false) throw new ForbiddenException(); - + if ($a->argc!==3) throw new BadRequestException("Invalid argument count"); $nm = new NotificationsManager(); - if ($a->argc==3) { - $notes = $nm->getAll(array(), "+seen -date", 50); - return api_apply_template("", $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(); + $notes = $nm->getAll(array(), "+seen -date", 50); + return api_apply_template("", $type, array('$notes' => $notes)); + } + + /** + * @brief Set notification as seen and returns associated item (if possible) + * + * POST request with 'id' param as notification id + * + * @param App $a + * @param string $type Known types are 'atom', 'rss', 'xml' and 'json' + * @return string + */ + function api_friendica_notification_seen(&$a, $type){ + if (api_user()===false) throw new ForbiddenException(); + if ($a->argc!==4) throw new BadRequestException("Invalid argument count"); + + $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0); + + $nm = new NotificationsManager(); + $note = $nm->getByID($id); + if (is_null($note)) throw new BadRequestException("Invalid argument"); + + $nm->setSeen($note); + if ($note['otype']=='item') { + // would be really better with an 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) { + // we found the item, return it to the user $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"); + // the item can't be found, but we set the note as seen, so we count this as a success + } + return api_apply_template('', $type, array('status' => "success")); } + + api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST); api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET); + /* To.Do: From 870d2f844d83741c7fc1878dda72807dab92d992 Mon Sep 17 00:00:00 2001 From: Fabrixxm Date: Mon, 8 Feb 2016 10:22:12 +0100 Subject: [PATCH 4/7] Update API docs Add `friendica/notification` and `friendica/notification/seen` endpoints Fix some list rendering issues Move all `friendica/*` endpoints under "Implemented API calls (not compatible with other APIs)" section Add info about permitted HTTP methods and required auth --- doc/api.md | 450 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 263 insertions(+), 187 deletions(-) diff --git a/doc/api.md b/doc/api.md index ced078f556..f050ae4304 100644 --- a/doc/api.md +++ b/doc/api.md @@ -7,6 +7,21 @@ Please refer to the linked documentation for further information. ## Implemented API calls ### General +#### HTTP Method + +API endpoints can restrict the method used to request them. +Using an invalid method results in HTTP error 405 "Method Not Allowed". + +In this document, the required method is listed after the endpoint name. "*" means every method can be used. + +#### Auth + +Friendica supports basic http auth and OAuth 1 to authenticate the user to the api. + +OAuth settings can be added by the user in web UI under /settings/oauth/ + +In this document, endpoints which requires auth are marked with "AUTH" after endpoint name + #### Unsupported parameters * cursor: Not implemented in GNU Social * trim_user: Not implemented in GNU Social @@ -37,36 +52,37 @@ Error body is json: ``` - { - "error": "Specific error message", - "request": "API path requested", - "code": "HTTP error code" - } +{ +"error": "Specific error message", +"request": "API path requested", +"code": "HTTP error code" +} ``` xml: ``` - - Specific error message - API path requested - HTTP error code - + +Specific error message +API path requested +HTTP error code + ``` --- -### account/rate_limit_status +### account/rate_limit_status (*; AUTH) --- -### account/verify_credentials +### account/verify_credentials (*; AUTH) #### Parameters + * skip_status: Don't show the "status" field. (Default: false) * include_entities: "true" shows entities for pictures and links (Default: false) --- -### conversation/show +### conversation/show (*; AUTH) Unofficial Twitter command. It shows all direct answers (excluding the original post) to a given id. -#### Parameters +#### Parameter * id: id of the post * count: Items per page (default: 20) * page: page number @@ -80,7 +96,7 @@ Unofficial Twitter command. It shows all direct answers (excluding the original * contributor_details --- -### direct_messages +### direct_messages (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -93,7 +109,7 @@ Unofficial Twitter command. It shows all direct answers (excluding the original * skip_status --- -### direct_messages/all +### direct_messages/all (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -102,7 +118,7 @@ Unofficial Twitter command. It shows all direct answers (excluding the original * getText: Defines the format of the status field. Can be "html" or "plain" --- -### direct_messages/conversation +### direct_messages/conversation (*; AUTH) Shows all direct messages of a conversation #### Parameters * count: Items per page (default: 20) @@ -113,7 +129,7 @@ Shows all direct messages of a conversation * uri: URI of the conversation --- -### direct_messages/new +### direct_messages/new (POST,PUT; AUTH) #### Parameters * user_id: id of the user * screen_name: screen name (for technical reasons, this value is not unique!) @@ -122,7 +138,7 @@ Shows all direct messages of a conversation * title: Title of the direct message --- -### direct_messages/sent +### direct_messages/sent (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -132,7 +148,7 @@ Shows all direct messages of a conversation * include_entities: "true" shows entities for pictures and links (Default: false) --- -### favorites +### favorites (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -144,22 +160,23 @@ Shows all direct messages of a conversation * user_id * screen_name -Favorites aren't displayed to other users, so "user_id" and "screen_name". So setting this value will result in an empty array. +Favorites aren't displayed to other users, so "user_id" and "screen_name" are unsupported. +Set this values will result in an empty array. --- -### favorites/create +### favorites/create (POST,PUT; AUTH) #### Parameters * id * include_entities: "true" shows entities for pictures and links (Default: false) --- -### favorites/destroy +### favorites/destroy (POST,DELETE; AUTH) #### Parameters * id * include_entities: "true" shows entities for pictures and links (Default: false) --- -### followers/ids +### followers/ids (*; AUTH) #### Parameters * stringify_ids: Should the id numbers be sent as text (true) or number (false)? (default: false) @@ -171,139 +188,7 @@ Favorites aren't displayed to other users, so "user_id" and "screen_name". So se Friendica doesn't allow showing followers of other users. --- -### friendica/activity/ -#### parameters -* id: item id - -Add or remove an activity from an item. -'verb' can be one of: -- like -- dislike -- attendyes -- attendno -- attendmaybe - -To remove an activity, prepend the verb with "un", eg. "unlike" or "undislike" -Attend verbs disable eachother: that means that if "attendyes" was added to an item, adding "attendno" remove previous "attendyes". -Attend verbs should be used only with event-related items (there is no check at the moment) - -#### Return values - -On success: -json -```"ok"``` - -xml -```true``` - -On error: -HTTP 400 BadRequest - ---- -### friendica/photo -#### Parameters -* photo_id: Resource id of a photo. -* scale: (optional) scale value of the photo - -Returns data of a picture with the given resource. -If 'scale' isn't provided, returned data include full url to each scale of the photo. -If 'scale' is set, returned data include image data base64 encoded. - -possibile scale value are: -0: original or max size by server settings -1: image with or height at <= 640 -2: image with or height at <= 320 -3: thumbnail 160x160 - -4: Profile image at 175x175 -5: Profile image at 80x80 -6: Profile image at 48x48 - -An image used as profile image has only scale 4-6, other images only 0-3 - -#### Return values - -json -``` - { - "id": "photo id" - "created": "date(YYYY-MM-GG HH:MM:SS)", - "edited": "date(YYYY-MM-GG HH:MM:SS)", - "title": "photo title", - "desc": "photo description", - "album": "album name", - "filename": "original file name", - "type": "mime type", - "height": "number", - "width": "number", - "profile": "1 if is profile photo", - "link": { - "": "url to image" - ... - }, - // if 'scale' is set - "datasize": "size in byte", - "data": "base64 encoded image data" - } -``` - -xml -``` - - photo id - date(YYYY-MM-GG HH:MM:SS) - date(YYYY-MM-GG HH:MM:SS) - photo title - photo description - album name - original file name - mime type - number - number - 1 if is profile photo - - - ... - - -``` - ---- -### friendica/photos/list - -Returns a list of all photo resources of the logged in user. - -#### Return values - -json -``` - [ - { - id: "resource_id", - album: "album name", - filename: "original file name", - type: "image mime type", - thumb: "url to thumb sized image" - }, - ... - ] -``` - -xml -``` - - - "url to thumb sized image" - - ... - -``` - ---- -### friends/ids +### friends/ids (*; AUTH) #### Parameters * stringify_ids: Should the id numbers be sent as text (true) or number (false)? (default: false) @@ -315,15 +200,15 @@ xml Friendica doesn't allow showing friends of other users. --- -### help/test +### help/test (*) --- -### media/upload +### media/upload (POST,PUT; AUTH) #### Parameters * media: image data --- -### oauth/request_token +### oauth/request_token (*) #### Parameters * oauth_callback @@ -331,7 +216,7 @@ Friendica doesn't allow showing friends of other users. * x_auth_access_type --- -### oauth/access_token +### oauth/access_token (*) #### Parameters * oauth_verifier @@ -341,7 +226,7 @@ Friendica doesn't allow showing friends of other users. * x_auth_mode --- -### statuses/destroy +### statuses/destroy (POST,DELETE; AUTH) #### Parameters * id: message number * include_entities: "true" shows entities for pictures and links (Default: false) @@ -350,15 +235,21 @@ Friendica doesn't allow showing friends of other users. * trim_user --- -### statuses/followers +### statuses/followers (*; AUTH) + +#### Parameters + * include_entities: "true" shows entities for pictures and links (Default: false) --- -### statuses/friends +### statuses/friends (*; AUTH) + +#### Parameters + * include_entities: "true" shows entities for pictures and links (Default: false) --- -### statuses/friends_timeline +### statuses/friends_timeline (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -374,7 +265,7 @@ Friendica doesn't allow showing friends of other users. * contributor_details --- -### statuses/home_timeline +### statuses/home_timeline (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -390,7 +281,7 @@ Friendica doesn't allow showing friends of other users. * contributor_details --- -### statuses/mentions +### statuses/mentions (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -404,7 +295,7 @@ Friendica doesn't allow showing friends of other users. * contributor_details --- -### statuses/public_timeline +### statuses/public_timeline (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -418,7 +309,7 @@ Friendica doesn't allow showing friends of other users. * trim_user --- -### statuses/replies +### statuses/replies (*; AUTH) #### Parameters * count: Items per page (default: 20) * page: page number @@ -432,7 +323,7 @@ Friendica doesn't allow showing friends of other users. * contributor_details --- -### statuses/retweet +### statuses/retweet (POST,PUT; AUTH) #### Parameters * id: message number * include_entities: "true" shows entities for pictures and links (Default: false) @@ -441,7 +332,7 @@ Friendica doesn't allow showing friends of other users. * trim_user --- -### statuses/show +### statuses/show (*; AUTH) #### Parameters * id: message number * conversation: if set to "1" show all messages of the conversation with the given id @@ -476,7 +367,7 @@ Friendica doesn't allow showing friends of other users. * display_coordinates --- -### statuses/user_timeline +### statuses/user_timeline (*; AUTH) #### Parameters * user_id: id of the user * screen_name: screen name (for technical reasons, this value is not unique!) @@ -489,15 +380,16 @@ Friendica doesn't allow showing friends of other users. * include_entities: "true" shows entities for pictures and links (Default: false) #### Unsupported parameters + * include_rts * trim_user * contributor_details --- -### statusnet/config +### statusnet/config (*) --- -### statusnet/version +### statusnet/version (*) #### Unsupported parameters * user_id @@ -507,7 +399,7 @@ Friendica doesn't allow showing friends of other users. Friendica doesn't allow showing followers of other users. --- -### users/search +### users/search (*) #### Parameters * q: name of the user @@ -517,7 +409,7 @@ Friendica doesn't allow showing followers of other users. * include_entities --- -### users/show +### users/show (*) #### Parameters * user_id: id of the user * screen_name: screen name (for technical reasons, this value is not unique!) @@ -533,8 +425,39 @@ Friendica doesn't allow showing friends of other users. ## Implemented API calls (not compatible with other APIs) + --- -### friendica/group_show +### friendica/activity/ +#### parameters +* id: item id + +Add or remove an activity from an item. +'verb' can be one of: + +- like +- dislike +- attendyes +- attendno +- attendmaybe + +To remove an activity, prepend the verb with "un", eg. "unlike" or "undislike" +Attend verbs disable eachother: that means that if "attendyes" was added to an item, adding "attendno" remove previous "attendyes". +Attend verbs should be used only with event-related items (there is no check at the moment) + +#### Return values + +On success: +json +```"ok"``` + +xml +```true``` + +On error: +HTTP 400 BadRequest + +--- +### friendica/group_show (*; AUTH) Return all or a specified group of the user with the containing contacts as array. #### Parameters @@ -542,22 +465,23 @@ Return all or a specified group of the user with the containing contacts as arra #### Return values Array of: + * name: name of the group * gid: id of the group * user: array of group members (return from api_get_user() function for each member) --- -### friendica/group_delete +### friendica/group_delete (POST,DELETE; AUTH) delete the specified group of contacts; API call need to include the correct gid AND name of the group to be deleted. ---- -### Parameters +#### Parameters * gid: id of the group to be deleted * name: name of the group to be deleted #### Return values Array of: + * success: true if successfully deleted * gid: gid of the deleted group * name: name of the deleted group @@ -566,19 +490,22 @@ Array of: --- -### friendica/group_create +### friendica/group_create (POST,PUT; AUTH) Create the group with the posted array of contacts as members. + #### Parameters * name: name of the group to be created #### POST data -JSON data as Array like the result of „users/group_show“: +JSON data as Array like the result of "users/group_show": + * gid * name * array of users #### Return values Array of: + * success: true if successfully created or reactivated * gid: gid of the created group * name: name of the created group @@ -587,26 +514,175 @@ Array of: --- -### friendica/group_update +### friendica/group_update (POST) Update the group with the posted array of contacts as members (post all members of the group to the call; function will remove members not posted). + #### Parameters * gid: id of the group to be changed * name: name of the group to be changed #### POST data JSON data as array like the result of „users/group_show“: + * gid * name * array of users #### Return values Array of: + * success: true if successfully updated * gid: gid of the changed group * name: name of the changed group * status: „missing user“ | „ok“ * wrong users: array of users, which were not available in the contact table + + +--- +### friendica/notifications (GET) +Return last 50 notification for current user, ordered by date with unseen item on top + +#### Parameters +none + +#### Return values +Array of: + +* id: id of the note +* type: type of notification as int (see NOTIFY_* constants in boot.php) +* name: full name of the contact subject of the note +* url: contact's profile url +* photo: contact's profile photo +* date: datetime string of the note +* timestamp: timestamp of the node +* date_rel: relative date of the note (eg. "1 hour ago") +* msg: note message in bbcode +* msg_html: note message in html +* msg_plain: note message in plain text +* link: link to note +* seen: seen state: 0 or 1 + + +--- +### friendica/notifications/seen (POST) +Set note as seen, returns item object if possible + +#### Parameters +id: id of the note to set seen + +#### Return values +If the note is linked to an item, the item is returned, just like one of the "statuses/*_timeline" api. + +If the note is not linked to an item, a success status is returned: + +* "success" (json) | "<status>success</status>" (xml) + + +--- +### friendica/photo (*; AUTH) +#### Parameters +* photo_id: Resource id of a photo. +* scale: (optional) scale value of the photo + +Returns data of a picture with the given resource. +If 'scale' isn't provided, returned data include full url to each scale of the photo. +If 'scale' is set, returned data include image data base64 encoded. + +possibile scale value are: + +* 0: original or max size by server settings +* 1: image with or height at <= 640 +* 2: image with or height at <= 320 +* 3: thumbnail 160x160 +* 4: Profile image at 175x175 +* 5: Profile image at 80x80 +* 6: Profile image at 48x48 + +An image used as profile image has only scale 4-6, other images only 0-3 + +#### Return values + +json +``` +{ +"id": "photo id" +"created": "date(YYYY-MM-GG HH:MM:SS)", +"edited": "date(YYYY-MM-GG HH:MM:SS)", +"title": "photo title", +"desc": "photo description", +"album": "album name", +"filename": "original file name", +"type": "mime type", +"height": "number", +"width": "number", +"profile": "1 if is profile photo", +"link": { +"": "url to image" +... +}, +// if 'scale' is set +"datasize": "size in byte", +"data": "base64 encoded image data" +} +``` + +xml +``` + +photo id +date(YYYY-MM-GG HH:MM:SS) +date(YYYY-MM-GG HH:MM:SS) +photo title +photo description +album name +original file name +mime type +number +number +1 if is profile photo + + +... + + +``` + +--- +### friendica/photos/list (*; AUTH) + +Returns a list of all photo resources of the logged in user. + +#### Return values + +json +``` +[ +{ +id: "resource_id", +album: "album name", +filename: "original file name", +type: "image mime type", +thumb: "url to thumb sized image" +}, +... +] +``` + +xml +``` + + +"url to thumb sized image" + +... + +``` + + --- ## Not Implemented API calls The following API calls are implemented in GNU Social but not in Friendica: (incomplete) @@ -702,13 +778,13 @@ The following API calls from the Twitter API aren't implemented neither in Frien ### BASH / cURL Betamax has documentated some example API usage from a [bash script](https://en.wikipedia.org/wiki/Bash_(Unix_shell) employing [curl](https://en.wikipedia.org/wiki/CURL) (see [his posting](https://betamax65.de/display/betamax65/43539)). - /usr/bin/curl -u USER:PASS https://YOUR.FRIENDICA.TLD/api/statuses/update.xml -d source="some source id" -d status="the status you want to post" +/usr/bin/curl -u USER:PASS https://YOUR.FRIENDICA.TLD/api/statuses/update.xml -d source="some source id" -d status="the status you want to post" ### Python The [RSStoFriedika](https://github.com/pafcu/RSStoFriendika) code can be used as an example of how to use the API with python. The lines for posting are located at [line 21](https://github.com/pafcu/RSStoFriendika/blob/master/RSStoFriendika.py#L21) and following. - def tweet(server, message, group_allow=None): - url = server + '/api/statuses/update' - urllib2.urlopen(url, urllib.urlencode({'status': message,'group_allow[]':group_allow}, doseq=True)) +def tweet(server, message, group_allow=None): +url = server + '/api/statuses/update' +urllib2.urlopen(url, urllib.urlencode({'status': message,'group_allow[]':group_allow}, doseq=True)) There is also a [module for python 3](https://bitbucket.org/tobiasd/python-friendica) for using the API. From a283691149fa9224be8b7ba8edc4dcdef88c3612 Mon Sep 17 00:00:00 2001 From: Fabrixxm Date: Mon, 8 Feb 2016 10:34:27 +0100 Subject: [PATCH 5/7] api docs: fix indentation --- doc/api.md | 132 ++++++++++++++++++++++++++--------------------------- 1 file changed, 66 insertions(+), 66 deletions(-) diff --git a/doc/api.md b/doc/api.md index f050ae4304..c020f403ff 100644 --- a/doc/api.md +++ b/doc/api.md @@ -52,20 +52,20 @@ Error body is json: ``` -{ -"error": "Specific error message", -"request": "API path requested", -"code": "HTTP error code" -} + { + "error": "Specific error message", + "request": "API path requested", + "code": "HTTP error code" + } ``` xml: ``` - -Specific error message -API path requested -HTTP error code - + + Specific error message + API path requested + HTTP error code + ``` --- @@ -605,47 +605,47 @@ An image used as profile image has only scale 4-6, other images only 0-3 json ``` -{ -"id": "photo id" -"created": "date(YYYY-MM-GG HH:MM:SS)", -"edited": "date(YYYY-MM-GG HH:MM:SS)", -"title": "photo title", -"desc": "photo description", -"album": "album name", -"filename": "original file name", -"type": "mime type", -"height": "number", -"width": "number", -"profile": "1 if is profile photo", -"link": { -"": "url to image" -... -}, -// if 'scale' is set -"datasize": "size in byte", -"data": "base64 encoded image data" -} + { + "id": "photo id" + "created": "date(YYYY-MM-GG HH:MM:SS)", + "edited": "date(YYYY-MM-GG HH:MM:SS)", + "title": "photo title", + "desc": "photo description", + "album": "album name", + "filename": "original file name", + "type": "mime type", + "height": "number", + "width": "number", + "profile": "1 if is profile photo", + "link": { + "": "url to image" + ... + }, + // if 'scale' is set + "datasize": "size in byte", + "data": "base64 encoded image data" + } ``` xml ``` - -photo id -date(YYYY-MM-GG HH:MM:SS) -date(YYYY-MM-GG HH:MM:SS) -photo title -photo description -album name -original file name -mime type -number -number -1 if is profile photo - - -... - - + + photo id + date(YYYY-MM-GG HH:MM:SS) + date(YYYY-MM-GG HH:MM:SS) + photo title + photo description + album name + original file name + mime type + number + number + 1 if is profile photo + + + ... + + ``` --- @@ -657,29 +657,29 @@ Returns a list of all photo resources of the logged in user. json ``` -[ -{ -id: "resource_id", -album: "album name", -filename: "original file name", -type: "image mime type", -thumb: "url to thumb sized image" -}, -... -] + [ + { + id: "resource_id", + album: "album name", + filename: "original file name", + type: "image mime type", + thumb: "url to thumb sized image" + }, + ... + ] ``` xml ``` - - -"url to thumb sized image" - -... - + + + "url to thumb sized image" + + ... + ``` From 9ff0fc92dd1525450ea99347895fbbe5e367d56b Mon Sep 17 00:00:00 2001 From: Fabrixxm Date: Mon, 8 Feb 2016 13:42:06 +0100 Subject: [PATCH 6/7] NotificationsManager: add backtick to queries --- include/NotificationsManager.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/NotificationsManager.php b/include/NotificationsManager.php index b7e31d4f65..c99d00742c 100644 --- a/include/NotificationsManager.php +++ b/include/NotificationsManager.php @@ -79,7 +79,7 @@ class NotificationsManager { if ($limit!="") $limit = " LIMIT ".$limit; - $r = q("SELECT * FROM notify WHERE uid = %d $filter_sql ORDER BY $order_sql $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); @@ -93,7 +93,7 @@ class NotificationsManager { * @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", + $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($id), intval(local_user()) ); @@ -111,7 +111,7 @@ class NotificationsManager { * @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", + 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']), @@ -127,7 +127,7 @@ class NotificationsManager { * @return bool true on success, false on error */ public function setAllSeen($seen = true) { - return q("UPDATE notify SET seen = %d WHERE uid = %d", + return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d", intval($seen), intval(local_user()) ); From 2a016e7685e76b29641dce09172058f716f4ee4b Mon Sep 17 00:00:00 2001 From: Fabrixxm Date: Mon, 8 Feb 2016 14:35:41 +0100 Subject: [PATCH 7/7] add missing query backticks --- include/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/api.php b/include/api.php index 16481201e3..d205451e5e 100644 --- a/include/api.php +++ b/include/api.php @@ -3457,7 +3457,7 @@ $nm->setSeen($note); if ($note['otype']=='item') { // would be really better with an ItemsManager and $im->getByID() :-P - $r = q("SELECT * FROM item WHERE id=%d AND uid=%d", + $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d", intval($note['iid']), intval(local_user()) );