基于 Seafile API 的二次开发
使用 Seafile 也很久了,在上面保存了很多的数据。某天需要对 Seafile 进行一些简单的二次开发。在 Seafile 官网查了下,确实有接口开放。而且也有示例代码和封装好的 Python 和 PHP 的 API 。由于项目的特殊性,我决定直接调用 Seafile 的 Web API 做一些简单的二次开发的工作。
如,我们想要列出某个 Seafile 用户下共享出来的文件和文件夹。步骤如下:
首先是获取 Seafile 的 token 。在官方的示例中,获取方式是:
curl -d "username=username@example.com&password=123456" https://cloud.seafile.com/api2/auth-token/
那么在 PHP 中,我们只需要模拟这个操作就可以了:
$stringSeafileUserName = 'username@example.com';
$stringSeafilePassword = 'yourpassword';
// getHttpContent 是一个自定义函数
$jsonSeafileToken = getHttpContent('http://seafile.mydomain.com/api2/auth-token/', 'POST', array('username' => $stringSeafileUserName,'password' => $stringSeafilePassword));
$arraySeafileToken = json_decode($jsonSeafileToken, true);
// 得到 token
$stringSeafileToken = $arraySeafileToken['token'];
// 利用获取到的 token 通过 web api 获取列表
$uri = 'http://seafile.mydomain.com/api2/shared-links/';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array('Authorization: Token ' . $stringSeafileToken),
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_VERBOSE => 1
));
$out = curl_exec($ch);
curl_close($ch);
$arraySeafileSharedInfo = json_decode($out, true);
echo '<pre>';
// 列出所有的共享文件和文件夹
print_r($arraySeafileSharedInfo);
/*****************************
* @param $url
* @param string $method
* @param json $postData
* @return mixed|null|string
*****************************/
function getHttpContent($url, $method = 'GET', $postData = array())
{
$data = '';
if (!empty($url)) {
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //30秒超时
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
if (strtoupper($method) == 'POST') {
if (is_array($postData)){
$curlPost = http_build_query($postData);
}else{
$curlPost = $postData;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
}
$curlPost = is_array($postData) ? http_build_query($postData) : $postData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$data = curl_exec($ch);
curl_close($ch);
} catch (Exception $e) {
$data = null;
}
}
return $data;
}
这个只是简单的一个应用,想要从 Seafile 中获取更多数据和更多功能,可以查阅在线手册: https://manual.seafile.com/develop/web_api_v2.1.html