Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

implement uploading of files #470

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
kkuepper wants to merge 5 commits into notion-dotnet:main
base: main
Choose a base branch
Loading
from kkuepper:feature/support-files
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Src/Notion.Client/Models/File/FileObject.cs
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace Notion.Client
{
[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubTypeAttribute(typeof(UploadedFile), "file")]
[JsonSubtypes.KnownSubTypeAttribute(typeof(UploadingFile), "file_upload")]
[JsonSubtypes.KnownSubTypeAttribute(typeof(ExternalFile), "external")]
public abstract class FileObject : IPageIcon
{
Expand Down
1 change: 1 addition & 0 deletions Src/Notion.Client/Models/File/FileObjectWithName.cs
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace Notion.Client
[JsonConverter(typeof(JsonSubtypes), "type")]
[JsonSubtypes.KnownSubTypeAttribute(typeof(UploadedFileWithName), "file")]
[JsonSubtypes.KnownSubTypeAttribute(typeof(ExternalFileWithName), "external")]
[JsonSubtypes.KnownSubTypeAttribute(typeof(FileUploadWithName), "file_upload")]
public abstract class FileObjectWithName
{
[JsonProperty("type")]
Expand Down
19 changes: 19 additions & 0 deletions Src/Notion.Client/Models/File/FileUploadWithName.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;
using Newtonsoft.Json;

namespace Notion.Client
{
public class FileUploadWithName : FileObjectWithName
{
public override string Type => "file_upload";

[JsonProperty("file_upload")]
public Info FileUpload { get; set; }

public class Info
{
[JsonProperty("id")]
public Guid Id { get; set; }
}
}
}
19 changes: 19 additions & 0 deletions Src/Notion.Client/Models/File/UploadingFile.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;
using Newtonsoft.Json;

namespace Notion.Client
{
public class UploadingFile : FileObject
{
public override string Type => "file_upload";

[JsonProperty("file_upload")]
public Info FileUpload { get; set; }

public class Info
{
[JsonProperty("id")]
public Guid Id { get; set; }
}
}
}
4 changes: 4 additions & 0 deletions Src/Notion.Client/RestClient/IRestClient.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand Down Expand Up @@ -35,5 +36,8 @@ Task DeleteAsync(
IDictionary<string, string> queryParams = null,
IDictionary<string, string> headers = null,
CancellationToken cancellationToken = default);

Task<RestClient.UploadResponse> Upload(string filePath, JsonSerializerSettings serializerSettings = null);
Task<RestClient.UploadResponse> Upload(Stream stream, string filename, JsonSerializerSettings serializerSettings = null);
}
}
69 changes: 69 additions & 0 deletions Src/Notion.Client/RestClient/RestClient.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
Expand Down Expand Up @@ -91,6 +92,74 @@ public async Task DeleteAsync(
await SendAsync(uri, HttpMethod.Delete, queryParams, headers, null, cancellationToken);
}

public async Task<UploadResponse> Upload(string filePath, JsonSerializerSettings serializerSettings = null)
{
var fileStream = File.OpenRead(filePath);
return await Upload(fileStream, Path.GetFileName(filePath), serializerSettings);
}

public async Task<UploadResponse> Upload(Stream stream, string filename, JsonSerializerSettings serializerSettings = null)
{
var response = await this.PostAsync<UploadResponse>("https://api.notion.com/v1/file_uploads",
new UploadRequest {Mode = "single_part"});

using (var formData = new MultipartFormDataContent())
{
var fileContent = new StreamContent(stream);

var mimeMapping = new Dictionary<string, string>
{
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".png", "image/png"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".gif", "image/gif"},
{".svg", "image/svg+xml"}
};

if (mimeMapping.TryGetValue(Path.GetExtension(filename).ToLower(), out var mapping))
{
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mapping);
}
formData.Add(fileContent, "file", filename);

var uploadResponse = await this.SendAsync(response.UploadUrl, HttpMethod.Post,
attachContent: message =>
{
message.Content = formData;
});
return await uploadResponse.ParseStreamAsync<UploadResponse>(serializerSettings);
}
}

public class UploadRequest
{
public string Mode { get; set; }
}

public class UploadResponse
{
public Guid Id { get; set; }
public string Object { get; set; }
[JsonProperty("created_time")]
public DateTime CreatedTime { get; set; }
[JsonProperty("last_edited_time")]
public DateTime LastEditedTime { get; set; }
[JsonProperty("expiry_time")]
public DateTime ExpiryTime { get; set; }
[JsonProperty("upload_url")]
public string UploadUrl { get; set; }
public bool Archived { get; set; }
public string Status { get; set; }
public string Filename { get; set; }
[JsonProperty("content_type")]
public string ContentType { get; set; }
[JsonProperty("request_id")]
public Guid RequestId { get; set; }
}


private static ClientOptions MergeOptions(ClientOptions options)
{
return new ClientOptions
Expand Down
61 changes: 60 additions & 1 deletion Test/Notion.IntegrationTests/PageClientTests.cs
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ public async Task InitializeAsync()
}
}
},
{ "Number", new NumberPropertySchema { Number = new Number { Format = "number" } } }
{ "Number", new NumberPropertySchema { Number = new Number { Format = "number" } } },
{"Profile picture", new FilePropertySchema() { Files = new Dictionary<string, object>()}}
},
Parent = new ParentPageInput { PageId = _page.Id }
};
Expand Down Expand Up @@ -179,6 +180,64 @@ public async Task Test_RetrievePagePropertyItemAsync()
titleProperty.Title.PlainText.Should().Be("Test Page Title");
});
}

[Fact]
public async Task Test_CanUploadAndSetProfilePicture()
{
// Arrange
var upload = await Client.RestClient.Upload("/Users/kkuepper/Pictures/Scan.jpeg");

// Act
var pagesCreateParameters = PagesCreateParametersBuilder
.Create(new DatabaseParentInput {DatabaseId = _database.Id})
.AddProperty("Name",
new TitlePropertyValue
{
Title = new List<RichTextBase>
{
new RichTextText {Text = new Text {Content = "Test Page Title"}}
}
})
.AddProperty("Number", new NumberPropertyValue {Number = 123})
.AddProperty("Profile picture",
new FilesPropertyValue
{
Files = new List<FileObjectWithName>
{
new FileUploadWithName {FileUpload = new FileUploadWithName.Info {Id = upload.Id}}
}
}
)
.AddPageContent(new ImageBlock
{
Image = new UploadingFile {FileUpload = new UploadingFile.Info {Id = upload.Id}}
})
.Build();

var page = await Client.Pages.CreateAsync(pagesCreateParameters);

var property = await Client.Pages.RetrievePagePropertyItemAsync(new RetrievePropertyItemParameters
{
PageId = page.Id,
PropertyId = "Profile picture"
});

// Assert
property.Should().NotBeNull();
property.Should().BeOfType<FilesPropertyItem>();

var listProperty = (FilesPropertyItem)property;

listProperty.Type.Should().NotBeNull();

listProperty.Files.Should().SatisfyRespectively(p =>
{
p.Should().BeOfType<UploadedFileWithName>();
var fileWithName = (UploadedFileWithName)p;

fileWithName.Name.Should().Be("Scan.jpeg");
});
}

[Fact]
public async Task Test_UpdatePageProperty_with_date_as_null()
Expand Down
Loading

AltStyle によって変換されたページ (->オリジナル) /