abraunegg-onedrive/src/onedrive.d

346 lines
9.4 KiB
D
Raw Normal View History

2015-12-29 19:38:15 +01:00
import std.net.curl: CurlException, HTTP;
import std.datetime, std.exception, std.json, std.path;
import std.stdio, std.string, std.uni, std.uri;
2015-09-14 19:21:06 +02:00
import config;
2015-09-01 20:45:34 +02:00
2015-12-29 19:38:15 +01:00
2015-09-01 20:45:34 +02:00
private immutable {
string authUrl = "https://login.live.com/oauth20_authorize.srf";
string redirectUrl = "https://login.live.com/oauth20_desktop.srf"; // "urn:ietf:wg:oauth:2.0:oob";
2015-09-01 20:45:34 +02:00
string tokenUrl = "https://login.live.com/oauth20_token.srf";
string itemByIdUrl = "https://api.onedrive.com/v1.0/drive/items/";
string itemByPathUrl = "https://api.onedrive.com/v1.0/drive/root:/";
}
class OneDriveException: Exception
{
// HTTP status code
int code;
2015-12-29 19:38:15 +01:00
@nogc @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line, next);
}
@safe pure this(int code, string reason, string file = __FILE__, size_t line = __LINE__)
{
this.code = code;
string msg = format("HTTP request returned status code %d (%s)", code, reason);
super(msg, file, line, next);
}
2015-09-01 20:45:34 +02:00
}
final class OneDriveApi
{
private string clientId;
2015-09-01 20:45:34 +02:00
private string refreshToken, accessToken;
2015-09-01 22:23:42 +02:00
private SysTime accessTokenExpiration;
/* private */ HTTP http;
2015-09-01 20:45:34 +02:00
2015-09-14 19:21:06 +02:00
void delegate(string) onRefreshToken; // called when a new refresh_token is received
2015-09-01 20:45:34 +02:00
2015-09-14 19:21:06 +02:00
this(Config cfg, bool verbose)
2015-09-01 20:45:34 +02:00
{
2015-09-14 19:21:06 +02:00
this.clientId = cfg.get("client_id");
2015-09-01 20:45:34 +02:00
http = HTTP();
2015-09-14 23:56:14 +02:00
//http.verbose = verbose;
2015-09-01 20:45:34 +02:00
}
2016-06-30 12:51:44 +02:00
bool authorize()
2015-09-01 20:45:34 +02:00
{
import std.stdio, std.regex;
2016-06-30 12:51:44 +02:00
char[] response;
string url = authUrl ~ "?client_id=" ~ clientId ~ "&scope=onedrive.readwrite%20offline_access&response_type=code&redirect_uri=" ~ redirectUrl;
2015-09-14 19:21:06 +02:00
writeln("Authorize this app visiting:\n");
2016-06-30 12:51:44 +02:00
write(url, "\n\n", "Enter the response uri: ");
readln(response);
// match the authorization code
auto c = matchFirst(response, r"(?:code=)(([\w\d]+-){4}[\w\d]+)");
if (c.empty) {
writeln("Invalid uri");
return false;
2015-09-01 20:45:34 +02:00
}
2016-06-30 12:51:44 +02:00
c.popFront(); // skip the whole match
redeemToken(c.front);
return true;
2015-09-01 20:45:34 +02:00
}
void setRefreshToken(string refreshToken)
{
this.refreshToken = refreshToken;
}
// https://dev.onedrive.com/items/view_delta.htm
2015-09-01 20:45:34 +02:00
JSONValue viewChangesById(const(char)[] id, const(char)[] statusToken)
{
2015-09-01 22:23:42 +02:00
checkAccessTokenExpired();
const(char)[] url = itemByIdUrl ~ id ~ "/view.delta";
url ~= "?select=id,name,eTag,cTag,deleted,file,folder,fileSystemInfo,remoteItem,parentReference";
2015-09-01 20:45:34 +02:00
if (statusToken) url ~= "?token=" ~ statusToken;
return get(url);
}
// https://dev.onedrive.com/items/view_delta.htm
2015-09-01 20:45:34 +02:00
JSONValue viewChangesByPath(const(char)[] path, const(char)[] statusToken)
{
2015-09-01 22:23:42 +02:00
checkAccessTokenExpired();
string url = itemByPathUrl ~ encodeComponent(path) ~ ":/view.delta";
url ~= "?select=id,name,eTag,cTag,deleted,file,folder,fileSystemInfo,remoteItem,parentReference";
2015-09-01 20:45:34 +02:00
if (statusToken) url ~= "&token=" ~ statusToken;
return get(url);
}
// https://dev.onedrive.com/items/download.htm
void downloadById(const(char)[] id, string saveToPath)
{
2015-09-01 22:23:42 +02:00
checkAccessTokenExpired();
scope(failure) {
2015-09-01 20:45:34 +02:00
import std.file;
if (exists(saveToPath)) remove(saveToPath);
}
2016-06-29 21:41:44 +02:00
const(char)[] url = itemByIdUrl ~ id ~ "/content?AVOverride=1";
download(url, saveToPath);
2015-09-01 20:45:34 +02:00
}
// https://dev.onedrive.com/items/upload_put.htm
2015-09-05 21:23:43 +02:00
JSONValue simpleUpload(string localPath, const(char)[] remotePath, const(char)[] eTag = null)
2015-09-01 20:45:34 +02:00
{
2015-09-01 22:23:42 +02:00
checkAccessTokenExpired();
2015-09-16 10:29:20 +02:00
string url = itemByPathUrl ~ encodeComponent(remotePath) ~ ":/content";
http.addRequestHeader("Content-Type", "application/octet-stream");
if (eTag) http.addRequestHeader("If-Match", eTag);
else url ~= "?@name.conflictBehavior=fail";
return upload(localPath, url);
2015-09-01 20:45:34 +02:00
}
2015-09-05 21:23:43 +02:00
// https://dev.onedrive.com/items/update.htm
JSONValue updateById(const(char)[] id, JSONValue data, const(char)[] eTag = null)
{
checkAccessTokenExpired();
char[] url = itemByIdUrl ~ id;
if (eTag) http.addRequestHeader("If-Match", eTag);
http.addRequestHeader("Content-Type", "application/json");
return patch(url, data.toString());
2015-09-05 21:23:43 +02:00
}
2015-12-29 19:38:15 +01:00
// https://dev.onedrive.com/items/delete.htm
2015-09-06 10:23:32 +02:00
void deleteById(const(char)[] id, const(char)[] eTag = null)
{
checkAccessTokenExpired();
char[] url = itemByIdUrl ~ id;
if (eTag) http.addRequestHeader("If-Match", eTag);
del(url);
2015-09-06 10:23:32 +02:00
}
2015-12-29 19:38:15 +01:00
// https://dev.onedrive.com/items/create.htm
2015-09-06 11:06:13 +02:00
JSONValue createByPath(const(char)[] parentPath, JSONValue item)
{
2015-09-16 10:29:20 +02:00
string url = itemByPathUrl ~ encodeComponent(parentPath) ~ ":/children";
2015-09-06 11:06:13 +02:00
http.addRequestHeader("Content-Type", "application/json");
return post(url, item.toString());
2015-09-06 11:06:13 +02:00
}
// https://dev.onedrive.com/items/upload_large_files.htm
JSONValue createUploadSession(const(char)[] path, const(char)[] eTag = null)
{
checkAccessTokenExpired();
string url = itemByPathUrl ~ encodeComponent(path) ~ ":/upload.createSession";
if (eTag) http.addRequestHeader("If-Match", eTag);
return post(url, null);
}
// https://dev.onedrive.com/items/upload_large_files.htm
JSONValue uploadFragment(const(char)[] uploadUrl, string filepath, long offset, long offsetSize, long fileSize)
{
checkAccessTokenExpired();
scope(exit) {
http.clearRequestHeaders();
http.onSend = null;
}
http.method = HTTP.Method.put;
http.url = uploadUrl;
addAccessTokenHeader();
import std.conv;
string contentRange = "bytes " ~ to!string(offset) ~ "-" ~ to!string(offset + offsetSize - 1) ~ "/" ~ to!string(fileSize);
http.addRequestHeader("Content-Range", contentRange);
auto file = File(filepath, "rb");
file.seek(offset);
http.onSend = data => file.rawRead(data).length;
http.contentLength = offsetSize;
auto response = perform();
// TODO: retry on 5xx errors
checkHttpCode();
return response;
}
// https://dev.onedrive.com/items/upload_large_files.htm
JSONValue requestUploadStatus(const(char)[] uploadUrl)
{
checkAccessTokenExpired();
return get(uploadUrl);
}
2015-09-01 20:45:34 +02:00
private void redeemToken(const(char)[] authCode)
{
const(char)[] postData =
"client_id=" ~ clientId ~
"&redirect_uri=" ~ redirectUrl ~
"&code=" ~ authCode ~
"&grant_type=authorization_code";
2015-09-01 20:45:34 +02:00
acquireToken(postData);
}
private void newToken()
{
string postData =
"client_id=" ~ clientId ~
"&redirect_uri=" ~ redirectUrl ~
"&refresh_token=" ~ refreshToken ~
"&grant_type=refresh_token";
2015-09-01 20:45:34 +02:00
acquireToken(postData);
}
private void acquireToken(const(char)[] postData)
{
JSONValue response = post(tokenUrl, postData);
accessToken = "bearer " ~ response["access_token"].str();
2015-09-02 11:20:42 +02:00
refreshToken = response["refresh_token"].str();
2015-09-01 22:23:42 +02:00
accessTokenExpiration = Clock.currTime() + dur!"seconds"(response["expires_in"].integer());
2015-09-01 20:45:34 +02:00
if (onRefreshToken) onRefreshToken(refreshToken);
}
2015-09-01 22:23:42 +02:00
private void checkAccessTokenExpired()
{
if (Clock.currTime() >= accessTokenExpiration) {
newToken();
}
}
2015-09-05 21:23:43 +02:00
private void addAccessTokenHeader()
2015-09-01 20:45:34 +02:00
{
http.addRequestHeader("Authorization", accessToken);
}
private JSONValue get(const(char)[] url)
{
scope(exit) http.clearRequestHeaders();
http.method = HTTP.Method.get;
http.url = url;
addAccessTokenHeader();
auto response = perform();
checkHttpCode();
return response;
}
private void del(const(char)[] url)
{
scope(exit) http.clearRequestHeaders();
http.method = HTTP.Method.del;
http.url = url;
addAccessTokenHeader();
perform();
checkHttpCode();
}
private void download(const(char)[] url, string filename)
{
scope(exit) http.clearRequestHeaders();
http.method = HTTP.Method.get;
http.url = url;
addAccessTokenHeader();
auto f = File(filename, "wb");
http.onReceive = (ubyte[] data) {
f.rawWrite(data);
return data.length;
};
http.perform();
checkHttpCode();
2015-09-01 20:45:34 +02:00
}
2015-09-05 21:23:43 +02:00
private auto patch(T)(const(char)[] url, const(T)[] patchData)
{
scope(exit) http.clearRequestHeaders();
http.method = HTTP.Method.patch;
http.url = url;
addAccessTokenHeader();
auto response = perform(patchData);
checkHttpCode();
return response;
2015-09-05 21:23:43 +02:00
}
2015-09-01 20:45:34 +02:00
private auto post(T)(const(char)[] url, const(T)[] postData)
{
scope(exit) http.clearRequestHeaders();
http.method = HTTP.Method.post;
http.url = url;
addAccessTokenHeader();
auto response = perform(postData);
checkHttpCode();
return response;
}
private JSONValue upload(string filepath, string url)
{
scope(exit) {
http.clearRequestHeaders();
http.onSend = null;
http.contentLength = 0;
}
http.method = HTTP.Method.put;
http.url = url;
addAccessTokenHeader();
http.addRequestHeader("Content-Type", "application/octet-stream");
auto file = File(filepath, "rb");
http.onSend = data => file.rawRead(data).length;
http.contentLength = file.size;
auto response = perform();
checkHttpCode();
return response;
}
private JSONValue perform(const(void)[] sendData)
{
scope(exit) {
http.onSend = null;
http.contentLength = 0;
}
if (sendData) {
http.contentLength = sendData.length;
http.onSend = (void[] buf) {
import std.algorithm: min;
size_t minLen = min(buf.length, sendData.length);
if (minLen == 0) return 0;
buf[0 .. minLen] = sendData[0 .. minLen];
sendData = sendData[minLen .. $];
return minLen;
};
} else {
http.onSend = buf => 0;
}
return perform();
}
private JSONValue perform()
{
scope(exit) http.onReceive = null;
2015-10-04 17:33:48 +02:00
char[] content;
http.onReceive = (ubyte[] data) {
content ~= data;
return data.length;
};
2015-12-29 19:38:15 +01:00
try {
http.perform();
} catch (CurlException e) {
throw new OneDriveException(e.msg, e);
}
return content.parseJSON();
2015-09-01 20:45:34 +02:00
}
2015-09-06 10:07:18 +02:00
private void checkHttpCode()
2015-09-01 20:45:34 +02:00
{
if (http.statusLine.code / 100 != 2) {
throw new OneDriveException(http.statusLine.code, http.statusLine.reason);
2015-09-01 20:45:34 +02:00
}
}
}