Compare commits

...

8 Commits

13 changed files with 896 additions and 106 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
/.idea/
/cmake-build-debug/
/doc/

View File

@@ -1,6 +1,8 @@
cmake_minimum_required(VERSION 3.5)
project(YaDisk)
set(CMAKE_C_STANDARD 99)
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules)
find_package(CURL REQUIRED)
find_package(JsonC REQUIRED)
@@ -31,11 +33,10 @@ target_link_libraries(yadisk
target_include_directories(
test-app PRIVATE
"${CMAKE_SOURCE_DIR}/src"
${NEON_INCLUDE_DIR}
${CURL_INCLUDE_DIR}
${JSON_C_INCLUDE_DIR}
)
target_link_libraries(
test-app
yadisk
)
)

165
LICENSE Normal file
View File

@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@@ -1,7 +1,21 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#ifndef YADISK_YADISK_H
#define YADISK_YADISK_H

View File

@@ -1,6 +1,23 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#include <string.h>
#include <stdlib.h>
@@ -10,50 +27,97 @@
#include "yadisk_api_internal.h"
struct memory {
char *response;
char* response;
size_t size;
};
// Callback function for writing response data
static size_t write_callback(void *contents, size_t size, size_t nmemb, struct memory *mem) {
struct data {
char trace_ascii; /* 1 or 0 */
};
static size_t cb(void* data, size_t size, size_t nmemb, void* clientp)
{
size_t realsize = size * nmemb;
char *ptr = realloc(mem->response, mem->size + realsize + 1);
if(!ptr) {
// out of memory
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
struct memory* mem = (struct memory*)clientp;
char* ptr = realloc(mem->response, mem->size + realsize + 1);
if (ptr == NULL)
return 0; /* out of memory! */
mem->response = ptr;
memcpy(&(mem->response[mem->size]), contents, realsize);
memcpy(&(mem->response[mem->size]), data, realsize);
mem->size += realsize;
mem->response[mem->size] = 0;
return realsize;
}
char* build_query_string(query_param* params, size_t num_params)
{
CURL* curl = curl_easy_init();
if (!curl) {
return NULL;
}
char* query = NULL;
size_t query_len = 0;
for (size_t i = 0; i < num_params; ++i) {
char* encoded_key = curl_easy_escape(curl, params[i].key, 0);
char* encoded_value = curl_easy_escape(curl, params[i].value, 0);
// Calculate additional space needed: key=value& (including null terminator)
size_t additional_len = strlen(encoded_key) + strlen(encoded_value) + 2;
if (i < num_params - 1) {
additional_len++; // For '&'
}
query = realloc(query, query_len + additional_len);
sprintf(query + query_len, "%s=%s", encoded_key, encoded_value);
query_len += additional_len - 1; // Minus null terminator
if (i < num_params - 1) {
strcat(query, "&");
}
curl_free(encoded_key);
curl_free(encoded_value);
}
curl_easy_cleanup(curl);
return query;
}
// Function to make an HTTP request using libcurl
int api_http_request(
yadisk_api_client *client,
const char* method,
const char* path,
query_param *params,
size_t num_params,
char** output
) {
CURL *curl;
yadisk_api_client* client,
const char* method,
const char* path,
query_param* params,
size_t num_params,
char** output
)
{
CURL* curl;
CURLcode res;
struct memory chunk = {0};
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl) {
char url[256];
snprintf(url, sizeof(url), "%s%s", YANDEX_DISK_API_HOST, path);
if (curl) {
char url[512];
if (num_params) {
char* query_string = build_query_string(params, num_params);
snprintf(url, sizeof(url), "%s%s?%s", YANDEX_DISK_API_HOST, path, query_string);
free(query_string);
} else {
snprintf(url, sizeof(url), "%s%s", YANDEX_DISK_API_HOST, path);
}
printf("%s\n", url);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);
// Set the HTTP method
if (strcmp(method, "GET") == 0) {
@@ -69,17 +133,16 @@ int api_http_request(
// Set the authorization header
char auth_header[256];
snprintf(auth_header, sizeof(auth_header), "Authorization: OAuth %s", client->token);
struct curl_slist *headers = NULL;
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, auth_header);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// Perform the request
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
free(chunk.response);
curl_easy_cleanup(curl);
curl_global_cleanup();
return -1;
} else {
*output = strdup(chunk.response);
@@ -91,6 +154,5 @@ int api_http_request(
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}

View File

@@ -1,6 +1,23 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#ifndef YADISK_YADISK_API_INTERNAL_H
#define YADISK_YADISK_API_INTERNAL_H
@@ -8,15 +25,42 @@
#define YANDEX_DISK_API_HOST "https://cloud-api.yandex.net"
typedef struct {
const char *key;
const char *value;
const char* key;
const char* value;
} query_param;
int api_http_request(yadisk_api_client *client,
const char *method,
const char *path,
query_param *params,
int api_http_request(yadisk_api_client* client,
const char* method,
const char* path,
query_param* params,
size_t num_params,
char **output);
char** output);
#define THROW_PARSE_JSON_ERROR { \
return YADISK_FAILED_PARSE_JSON; \
}
#define __DANGER_GET_JSON_OBJECT(root, key) \
json_object* obj = NULL; \
if (!json_object_object_get_ex(root, key, &obj)){ \
}
// json_object_put(root);
// THROW_PARSE_JSON_ERROR
#define GET_JSON_STRING(root, key, v) { \
__DANGER_GET_JSON_OBJECT(root, key) \
*v = json_object_get_string(obj); \
}
#define GET_JSON_UINT64(root, key, v) { \
__DANGER_GET_JSON_OBJECT(root, key) \
*v = json_object_get_uint64(obj); \
}
#define GET_JSON_BOOL(root, key, v) { \
__DANGER_GET_JSON_OBJECT(root, key) \
*v = json_object_get_boolean(obj); \
}
#endif //YADISK_YADISK_API_INTERNAL_H

View File

@@ -1,29 +1,99 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#include "yadisk_get_disk.h"
#include "yadisk_api_internal.h"
yadisk_code yadisk_get_disk(yadisk_api_client* client, yadisk_disk_info* info)
yadisk_code yadisk_get_disk(yadisk_api_client* client, yadisk_get_disk_params* params, yadisk_disk_info* info)
{
char* output = NULL;
int error = api_http_request(client, "GET", "/v1/disk", NULL, 0, &output);
json_object* root = json_tokener_parse(output);
if (error) {
json_object_put(root);
return YADISK_FAILED_PARSE_JSON;
query_param* qparams = NULL;
int num_params = 0;
const int max_params = 1;
if (params != NULL) {
qparams = malloc(max_params * sizeof(query_param));
if (params->fields != NULL) {
qparams[num_params].key = "fields";
qparams[num_params].value = strdup(params->fields);
num_params++;
}
}
json_object* total_space = NULL;
if (!json_object_object_get_ex(root, "total_space", &total_space)) {
// printf("Key total_space doesn't exists!");
return YADISK_FAILED_PARSE_JSON;
char* output = NULL;
int error = api_http_request(client, "GET", "/v1/disk", qparams, num_params, &output);
if (error) {
return YADISK_FAILED_HTTP_REQUEST;
}
info->total_space = json_object_get_uint64(total_space);
json_object_put(total_space);
json_object* root = json_tokener_parse(output);
free(output);
GET_JSON_UINT64(root, "total_space", &(info->total_space));
GET_JSON_UINT64(root, "trash_size", &(info->trash_size));
GET_JSON_UINT64(root, "used_space", &(info->used_space));
GET_JSON_STRING(root, "reg_time", &(info->reg_time));
GET_JSON_BOOL(root, "is_paid", &(info->is_paid));
json_object *user_object;
if (!json_object_object_get_ex(root, "user", &user_object)) {
// THROW_PARSE_JSON_ERROR
}
if (user_object) {
GET_JSON_STRING(user_object, "reg_time", &(info->user.reg_time));
GET_JSON_STRING(user_object, "display_name", &(info->user.display_name));
GET_JSON_STRING(user_object, "uid", &(info->user.uid));
GET_JSON_STRING(user_object, "country", &(info->user.country));
GET_JSON_BOOL(user_object, "is_child", &(info->user.is_child));
GET_JSON_STRING(user_object, "login", &(info->user.login));
}
json_object *system_folders;
if (!json_object_object_get_ex(root, "system_folders", &system_folders)) {
// THROW_PARSE_JSON_ERROR
}
if (system_folders) {
GET_JSON_STRING(system_folders, "odnoklassniki", &(info->system_folders.odnoklassniki));
GET_JSON_STRING(system_folders, "google", &(info->system_folders.google));
GET_JSON_STRING(system_folders, "instagram", &(info->system_folders.instagram));
GET_JSON_STRING(system_folders, "vkontakte", &(info->system_folders.vkontakte));
GET_JSON_STRING(system_folders, "attach", &(info->system_folders.attach));
GET_JSON_STRING(system_folders, "mailru", &(info->system_folders.mailru));
GET_JSON_STRING(system_folders, "downloads", &(info->system_folders.downloads));
GET_JSON_STRING(system_folders, "applications", &(info->system_folders.applications));
GET_JSON_STRING(system_folders, "facebook", &(info->system_folders.facebook));
GET_JSON_STRING(system_folders, "social", &(info->system_folders.social));
GET_JSON_STRING(system_folders, "messenger", &(info->system_folders.messenger));
GET_JSON_STRING(system_folders, "calendar", &(info->system_folders.calendar));
GET_JSON_STRING(system_folders, "photostream", &(info->system_folders.photostream));
GET_JSON_STRING(system_folders, "screenshots", &(info->system_folders.screenshots));
GET_JSON_STRING(system_folders, "scans", &(info->system_folders.scans));
}
GET_JSON_BOOL(root, "unlimited_autoupload_enabled", &(info->unlimited_autoupload_enabled));
GET_JSON_UINT64(root, "revision", &(info->revision));
json_object_put(root);
free(output);
return YADISK_OK;
}

View File

@@ -1,16 +1,152 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
/**
* @file
*/
#ifndef YADISK_YADISK_GET_DISK_H
#define YADISK_YADISK_GET_DISK_H
#include "yadisk_shared.h"
/**
* @brief
* @en User info
* @ru Информация о пользователе
*/
typedef struct {
const char* reg_time;
const char* display_name;
const char* uid;
const char* country;
int is_child;
const char* login;
} yadisk_user_info;
/**
* @brief
* @en System folders paths
* @ru Пути системных папок
*/
typedef struct {
const char* odnoklassniki;
const char* google;
const char* instagram;
const char* vkontakte;
const char* attach;
const char* mailru;
const char* downloads;
const char* applications;
const char* facebook;
const char* social;
const char* messenger;
const char* calendar;
const char* photostream;
const char* screenshots;
const char* scans;
} yadisk_system_folders;
/**
* @brief
* @en Information about the disk
* @ru Информация о диске
*/
typedef struct yadisk_disk_info {
/**
* @brief
* @en Total space
* @ru Общий объем
*/
unsigned long total_space;
/**
* @brief
* @en Trash size
* @ru Объем корзины
*/
unsigned long trash_size;
/**
* @brief
* @en Used space
* @ru Использованный объем
*/
unsigned long used_space;
/**
* @brief
* @en Is paid tariff
* @ru Платный ли тариф
*/
int is_paid;
/**
* @brief
* @en Registration date
* @ru Дата регистрации
*/
const char* reg_time;
/**
* @brief
* @en System folders paths
* @ru Пути системных папок
*/
yadisk_system_folders system_folders;
/**
* @brief
* @en Info about user
* @ru Информация о пользователе
*/
yadisk_user_info user;
/**
* @brief
* @en Unlimited autoupload
* @ru Безлимитная автозагрузка
*/
int unlimited_autoupload_enabled;
/**
* @brief
* @en Revision
* @ru Ревизия
*/
unsigned long revision;
} yadisk_disk_info;
yadisk_code yadisk_get_disk(yadisk_api_client* client, yadisk_disk_info* info);
typedef struct {
/**
* @brief
* @ru Список возвращаемых атрибутов.
*/
const char* fields;
} yadisk_get_disk_params;
/**
* @brief
* @ru Функция для получения метаинформации о диске пользователя.
*
* Реализует метод `GET /v1/disk`
* @param client
* @ru Клиент Яндекс.Диска
* @param params
* @ru Параметры запроса
* @param info
* @ru Информация о диске. Результат выполнения операции
* @return
* @ru Код возврата (YADISK_OK в случае успеха).
*/
yadisk_code yadisk_get_disk(yadisk_api_client* client, yadisk_get_disk_params* params, yadisk_disk_info* info);
#endif //YADISK_YADISK_GET_DISK_H

View File

@@ -1,12 +1,50 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#include "yadisk_get_disk_resources.h"
#include "yadisk_api_internal.h"
yadisk_code
yadisk_get_disk_resources(yadisk_api_client* client, const char* path)
yadisk_get_disk_resources(
yadisk_api_client* client, yadisk_get_disk_resources_params* path, yadisk_resource_info* info
)
{
char* output;
int error = api_http_request(client, "GET", "/v1/disk", NULL, 0, &output);
char* output = NULL;
query_param params[] = {
{"path", path},
};
int error = api_http_request(client, "GET", "/v1/disk/resources", params, 1, &output);
if (error) {
return YADISK_FAILED_HTTP_REQUEST;
}
json_object* root = json_tokener_parse(output);
free(output);
GET_JSON_STRING(root, "path", &(info->path));
GET_JSON_STRING(root, "name", &(info->name));
GET_JSON_STRING(root, "resource_id", &(info->resource_id));
GET_JSON_STRING(root, "type", &(info->type));
GET_JSON_STRING(root, "created", &(info->created));
GET_JSON_STRING(root, "modified", &(info->modified));
GET_JSON_STRING(root, "media_type", &(info->media_type));
GET_JSON_STRING(root, "mime_type", &(info->mime_type));
GET_JSON_UINT64(root, "size", &(info->size));
json_object_put(root);
return YADISK_OK;
};

View File

@@ -1,18 +1,95 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#ifndef YADISK_GET_DISK_RESOURCES_H_INCLUDED
#define YADISK_GET_DISK_RESOURCES_H_INCLUDED
#include "yadisk_shared.h"
#define YADISK_RESOURCE_ITEM_PROPERTIES \
const char* path; \
const char* name; \
const char* resource_id; \
const char* type; \
const char* created; \
const char* modified; \
const char* mime_type; \
const char* media_type; \
unsigned long size; \
const char* md5; \
const char* sha256; \
const char* antivirus_status; \
unsigned long long revision; \
yadisk_comment_ids* comment_ids; \
yadisk_sizes* sizes; \
unsigned long sizes_count;
// Структура для комментариев
typedef struct {
const char* private_resource;
const char* public_resource;
} yadisk_comment_ids;
// Структура для размеров
typedef struct {
const char* url;
const char* name;
} yadisk_size;
// Массив размеров
typedef struct {
yadisk_size* sizes;
unsigned long count;
} yadisk_sizes;
struct yadisk_resource_item {
YADISK_RESOURCE_ITEM_PROPERTIES
};
typedef struct {
/** Массив элементов */
struct yadisk_resource_item* items; // Массив элементов
unsigned long items_count; // Количество элементов
unsigned long limit;
unsigned long offset;
unsigned long total;
const char* sort;
const char* path;
} yadisk_resource_embedded;
typedef struct
{
const char* path;
const char* name;
const char* resource_id;
const char* type;
typedef struct {
YADISK_RESOURCE_ITEM_PROPERTIES
const yadisk_resource_embedded* _embedded;
} yadisk_resource_info;
yadisk_code yadisk_get_disk_resources(yadisk_api_client *client, const char *path);
typedef struct {
const char* path;
const char* fields;
unsigned long limit;
unsigned long offset;
int preview_crop;
const char* preview_size;
const char* sort;
} yadisk_get_disk_resources_params;
yadisk_code yadisk_get_disk_resources(yadisk_api_client* client, yadisk_get_disk_resources_params* params, yadisk_resource_info* resource);
#endif // YADISK_GET_DISK_RESOURCES_H_INCLUDED

View File

@@ -1,5 +1,32 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#include "yadisk_shared.h"
int yadisk_init()
{
return curl_global_init(CURL_GLOBAL_ALL);
}
void yadisk_cleanup()
{
curl_global_cleanup();
}

View File

@@ -1,7 +1,26 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
/**
* @file
*/
#ifndef YADISK_YADISK_SHARED_H
#define YADISK_YADISK_SHARED_H
@@ -9,13 +28,74 @@
#include <curl/curl.h>
#include <json.h>
/**
* @brief
* @ru Определение кодов ошибок для взаимодействия с сервисом Яндекс.Диск.
*
* Это перечисление используется для представления различных состояний, которые могут возникнуть
* при взаимодействии с API Яндекс.Диска. Оно включает в себя как успешные, так и ошибочные
* результаты операций.
*/
typedef enum {
/**
* @brief
* @ru Операция выполнена успешно, без ошибок.
*/
YADISK_OK = 0,
YADISK_FAILED_PARSE_JSON = 1
/**
* @brief
* @ru Ошибка при разборе JSON.
*
* Возникает, если полученный от Яндекс.Диска ответ не может быть
* корректно интерпретирован как валидный JSON.
*/
YADISK_FAILED_PARSE_JSON = 1,
/**
* @brief
* @ru Ошибка HTTP запроса.
*
* Этот код возвращается, когда происходит сбой в процессе
* отправки запроса или получения ответа от Яндекс.Диска,
* например, из-за проблем с сетевым соединением.
*/
YADISK_FAILED_HTTP_REQUEST = 2
} yadisk_code;
/**
* @brief
* @ru Структура для клиента API Яндекс.Диска.
*
* Эта структура используется для хранения данных, необходимых для взаимодействия с API Яндекс.Диска.
*/
typedef struct {
/**
* @brief
* @ru OAuth токен для аутентификации в API Яндекс.Диска.
*/
char* token;
} yadisk_api_client;
/**
* @brief
* @ru Инициализирует клиента Яндекс.Диска.
*
* Вызывает необходимые процедуры для подготовки клиента к работе с API Яндекс.Диска.
* Эта функция должна быть вызвана перед началом работы с API.
*
* @return
* @ru Код ошибки (0 в случае успеха).
*/
int yadisk_init();
/**
* @brief
* @ru Освобождает ресурсы, связанные с клиентом Яндекс.Диска.
*
* Эта функция освобождает все ресурсы и выполняет необходимые действия по очистке
* после завершения работы с API Яндекс.Диска. Она должна быть вызвана после
* завершения всех операций с API.
*/
void yadisk_cleanup();
#endif //YADISK_YADISK_SHARED_H

View File

@@ -1,25 +1,100 @@
//
// Created by maxim on 27.11.23.
//
/*
* libyadisk - A C library for interacting with Yandex.Disk API
*
* This file is part of libyadisk.
*
* Copyright (C) 2023 Maxim Slipenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
*/
#include <yadisk.h>
#include <stdio.h>
int main() {
int main()
{
char token[1024];
printf("Enter OAuth token: ");
fgets(token, sizeof(token), stdin);
yadisk_api_client* client = &(yadisk_api_client){
.token = token
yadisk_init();
yadisk_api_client* client = malloc(sizeof(yadisk_api_client));
if (client != NULL) {
client->token = token;
}
yadisk_disk_info info;
// yadisk_get_disk_params params1 = {.fields = "total_space"};
yadisk_code result = yadisk_get_disk(client, NULL, &info);
if (result != YADISK_OK) {
printf("Erorr yadisk_get_disk\n");
return -1;
}
printf("Total disk size: %lu\n", info.total_space);
printf("Trash size: %lu\n", info.trash_size);
printf("Used space: %lu\n", info.used_space);
printf("Registration time: %s\n", info.reg_time);
printf("Is paid: %s\n", info.is_paid ? "Yes" : "No");
printf("User Info:\n");
printf(" Registration time: %s\n", info.user.reg_time);
printf(" Display Name: %s\n", info.user.display_name);
printf(" UID: %s\n", info.user.uid);
printf(" Country: %s\n", info.user.country);
printf(" Is Child: %s\n", info.user.is_child ? "Yes" : "No");
printf(" Login: %s\n", info.user.login);
printf("System Folders:\n");
printf(" Odnoklassniki: %s\n", info.system_folders.odnoklassniki);
printf(" Google: %s\n", info.system_folders.google);
printf(" Instagram: %s\n", info.system_folders.instagram);
printf(" Vkontakte: %s\n", info.system_folders.vkontakte);
printf(" Attach: %s\n", info.system_folders.attach);
printf(" Mailru: %s\n", info.system_folders.mailru);
printf(" Downloads: %s\n", info.system_folders.downloads);
printf(" Applications: %s\n", info.system_folders.applications);
printf(" Facebook: %s\n", info.system_folders.facebook);
printf(" Social: %s\n", info.system_folders.social);
printf(" Messenger: %s\n", info.system_folders.messenger);
printf(" Calendar: %s\n", info.system_folders.calendar);
printf(" Photostream: %s\n", info.system_folders.photostream);
printf(" Screenshots: %s\n", info.system_folders.screenshots);
printf(" Scans: %s\n", info.system_folders.scans);
printf("Unlimited Autoupload Enabled: %s\n", info.unlimited_autoupload_enabled ? "Yes" : "No");
printf("Revision: %lu\n", info.revision);
printf("=================\n");
yadisk_resource_info resource;
yadisk_get_disk_resources_params params = {
.path = "/"
};
yadisk_get_disk_resources(client, &params, &resource);
printf("Path: %s\n", resource.path);
printf("Name: %s\n", resource.name);
printf("Type: %s\n", resource.type);
printf("Created: %s\n", resource.created);
printf("Modified: %s\n", resource.modified);
printf("ResourceID: %s\n", resource.resource_id);
printf("Media TYPE: %s\n", resource.media_type);
printf("Mime TYPE: %s\n", resource.mime_type);
printf("Size: %lu\n", resource.size);
yadisk_disk_info yadisk_disk_info;
yadisk_get_disk(client, &yadisk_disk_info);
printf("Total disk size: %lu", yadisk_disk_info.total_space);
yadisk_cleanup();
return 0;
}
}