Skip to content
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

Add JsonFileSessionStore #18

Closed
wants to merge 2 commits into from
Closed
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
10 changes: 5 additions & 5 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,18 @@ jobs:

- name: Prepare test suite assets
run: |
echo "$APP_CONFIG_IN_TESTS" > app.config
echo "$SESSION_DAT_IN_TESTS" > encodedSession.dat
echo "$APP_CFG_IN_TESTS" > app.config
echo "$SESSION_JSON_IN_TESTS" > session.json
shell: bash
env:
APP_CONFIG_IN_TESTS: ${{secrets.APP_CONFIG_IN_TESTS}}
SESSION_DAT_IN_TESTS: ${{secrets.SESSION_DAT_IN_TESTS}}
APP_CFG_IN_TESTS: ${{secrets.APP_CFG_IN_TESTS}}
SESSION_JSON_IN_TESTS: ${{secrets.SESSION_JSON_IN_TESTS}}

- name: Run Tests
run: |
MSBuild -p:Configuration=Debug -p:CI=true src/TgSharp.sln

certutil -decode encodedSession.dat src/TgSharp.Tests.NUnit/bin/Debug/session.dat
cp session.json src/TgSharp.Tests.NUnit/bin/Debug/
cp app.config src/TgSharp.Tests.NUnit/bin/Debug/TgSharp.Tests.NUnit.dll.config

./Nuget.exe install NUnit.Runners -Version 3.11.1 -OutputDirectory packages
Expand Down
19 changes: 11 additions & 8 deletions src/TgSharp.Core/DataCenter.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
using System;

namespace TgSharp.Core
{
internal class DataCenter
public class DataCenter
{
private const string defaultConnectionAddress = "149.154.175.100";//"149.154.167.50";
private const int defaultConnectionPort = 443;

[Obsolete ("Do not use, this ctor is public only for serialization")]
public DataCenter ()
{
}

internal DataCenter (int? dcId, string address = defaultConnectionAddress, int port = defaultConnectionPort)
{
DataCenterId = dcId;
Address = address;
Port = port;
}

internal DataCenter (string address = defaultConnectionAddress, int port = defaultConnectionPort) : this (null, address, port)
{
}

internal int? DataCenterId { get; }
internal string Address { get; }
internal int Port { get; }
public int? DataCenterId { get; set; }
public string Address { get; set; }
public int Port { get; set; }
}
}
21 changes: 13 additions & 8 deletions src/TgSharp.Core/FileSessionStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@

namespace TgSharp.Core
{
public class FileSessionStore : ISessionStore
[Obsolete ("Use JsonFileSessionStore")]
public class FileSessionStore : BinaryFileSessionStore
{
}

public class BinaryFileSessionStore : ISessionStore
{
private readonly DirectoryInfo basePath;

public FileSessionStore (DirectoryInfo basePath = null)
public BinaryFileSessionStore (DirectoryInfo basePath = null)
{
if (basePath != null && !basePath.Exists) {
throw new ArgumentException ("basePath doesn't exist", nameof (basePath));
Expand Down Expand Up @@ -69,14 +74,14 @@ public static Session FromBytes (byte [] buffer, ISessionStore store, string ses

var doesAuthExist = reader.ReadInt32 () == 1;
int sessionExpires = 0;
TLUser TLUser = null;
int userId = default;
if (doesAuthExist) {
sessionExpires = reader.ReadInt32 ();
TLUser = (TLUser)ObjectUtils.DeserializeObject (reader);
userId = reader.ReadInt32 ();
}

var authData = Serializers.Bytes.Read (reader);
var defaultDataCenter = new DataCenter (serverAddress, port);
var defaultDataCenter = new DataCenter (null, serverAddress, port);

return new Session () {
AuthKey = new AuthKey (authData),
Expand All @@ -86,7 +91,7 @@ public static Session FromBytes (byte [] buffer, ISessionStore store, string ses
LastMessageId = lastMessageId,
TimeOffset = timeOffset,
SessionExpires = sessionExpires,
TLUser = TLUser,
UserId = userId,
SessionUserId = sessionUserId,
DataCenter = defaultDataCenter,
};
Expand All @@ -105,10 +110,10 @@ internal byte [] ToBytes (Session session)
Serializers.String.Write (writer, session.DataCenter.Address);
writer.Write (session.DataCenter.Port);

if (session.TLUser != null) {
if (session.UserId != default) {
writer.Write (1);
writer.Write (session.SessionExpires);
ObjectUtils.SerializeObject (session.TLUser, writer);
writer.Write (session.UserId);
} else {
writer.Write (0);
}
Expand Down
55 changes: 55 additions & 0 deletions src/TgSharp.Core/JsonFileSessionStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace TgSharp.Core
{
public class JsonFileSessionStore : ISessionStore
{
private readonly DirectoryInfo basePath;
private readonly JsonSerializerOptions jsonSerializerSettings;

internal static JsonFileSessionStore DefaultSessionStore()
{
return new JsonFileSessionStore(null, new JsonSerializerOptions()
{
WriteIndented = true
});
}

public JsonFileSessionStore(DirectoryInfo basePath = null, JsonSerializerOptions jsonSerializerSettings = null)
{
if (basePath != null && !basePath.Exists)
{
throw new ArgumentException("basePath doesn't exist", nameof(basePath));
}

this.basePath = basePath;
this.jsonSerializerSettings = jsonSerializerSettings;
}

public void Save(Session session)
{
var json = JsonSerializer.Serialize(session);
File.WriteAllText(GetSessionPath(session.SessionUserId), json);
}

public Session Load(string sessionUserId)
{
string sessionPath = GetSessionPath(sessionUserId);

if (File.Exists(sessionPath))
{
return JsonSerializer.Deserialize<Session>(File.ReadAllText(sessionPath), jsonSerializerSettings);
}

return null;
}

private string GetSessionPath(string sessionUserId)
{
return Path.Combine(basePath?.FullName ?? string.Empty, sessionUserId + ".json");
}
}
}
14 changes: 14 additions & 0 deletions src/TgSharp.Core/MTProto/Crypto/AuthKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ public class AuthKey
private byte[] key;
private ulong keyId;
private ulong auxHash;

[Obsolete ("Do not use, this ctor is public only for serialization")]
public AuthKey ()
{
}

public AuthKey(BigInteger gab)
{
key = gab.ToByteArrayUnsigned();
Expand Down Expand Up @@ -69,6 +75,10 @@ public byte[] Data
{
return key;
}
set
{
key = value;
}
}

public ulong Id
Expand All @@ -77,6 +87,10 @@ public ulong Id
{
return keyId;
}
set
{
keyId = value;
}
}

public override string ToString()
Expand Down
9 changes: 4 additions & 5 deletions src/TgSharp.Core/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal static Session TryLoadOrCreateNew (ISessionStore store, string sessionU
{
var session = store.Load (sessionUserId);
if (null == session) {
var defaultDataCenter = new DataCenter ();
var defaultDataCenter = new DataCenter (null);
session = new Session {
Id = GenerateRandomUlong (),
SessionUserId = sessionUserId,
Expand Down Expand Up @@ -68,19 +68,18 @@ internal static int CurrentTime ()
#endif

public string SessionUserId { get; set; }
internal DataCenter DataCenter { get; set; }
public DataCenter DataCenter { get; set; }
public AuthKey AuthKey { get; set; }
public ulong Id { get; set; }
public ulong Salt { get; set; }
public int TimeOffset { get; set; }
public long LastMessageId { get; set; }
public int SessionExpires { get; set; }
public TLUser TLUser { get; set; }
private Random random;
public int UserId { get; set; }
private Random random = new Random ();

public Session()
{
random = new Random();
}

public long GetNewMessageId()
Expand Down
14 changes: 8 additions & 6 deletions src/TgSharp.Core/TelegramClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ public TelegramClient(int apiId, string apiHash,
throw new MissingApiConfigurationException("API_HASH");

if (store == null)
store = new FileSessionStore();
{
store = JsonFileSessionStore.DefaultSessionStore ();
}
this.store = store;

this.apiHash = apiHash;
Expand Down Expand Up @@ -119,7 +121,7 @@ public TelegramClient(int apiId, string apiHash,
throw new InvalidOperationException($"Can't reconnect. Establish initial connection first.");

TLExportedAuthorization exported = null;
if (Session.TLUser != null)
if (Session.UserId != default)
{
TLRequestExportAuthorization exportAuthorization = new TLRequestExportAuthorization() { DcId = dcId };
exported = await SendRequestAsync<TLExportedAuthorization>(exportAuthorization, token).ConfigureAwait(false);
Expand Down Expand Up @@ -152,7 +154,7 @@ public TelegramClient(int apiId, string apiHash,

await ConnectInternalAsync(true, token).ConfigureAwait(false);

if (Session.TLUser != null)
if (Session.UserId != default)
{
TLRequestImportAuthorization importAuthorization = new TLRequestImportAuthorization() { Id = exported.Id, Bytes = exported.Bytes };
var imported = await SendRequestAsync<TLAuthorization>(importAuthorization, token).ConfigureAwait(false);
Expand Down Expand Up @@ -191,7 +193,7 @@ public TelegramClient(int apiId, string apiHash,

public bool IsUserAuthorized()
{
return Session.TLUser != null;
return Session.UserId != default;
}

public async Task<string> SendCodeRequestAsync(string phoneNumber, CancellationToken token = default(CancellationToken))
Expand Down Expand Up @@ -421,9 +423,9 @@ await sender.SendPingAsync(token)
.ConfigureAwait(false);
}

private void OnUserAuthenticated(TLUser TLUser)
private void OnUserAuthenticated(TLUser user)
{
Session.TLUser = TLUser;
Session.UserId = user.Id;
Session.SessionExpires = int.MaxValue;

this.store.Save (Session);
Expand Down
32 changes: 31 additions & 1 deletion src/TgSharp.Core/TgSharp.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TgSharp.Core</RootNamespace>
<AssemblyName>TgSharp.Core</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
Expand Down Expand Up @@ -42,6 +42,35 @@
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="System.Buffers">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="System.Numerics.Vectors">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.CompilerServices.Unsafe">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.7.1\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Memory">
<HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web">
<HintPath>..\packages\System.Text.Encodings.Web.4.7.1\lib\net461\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.1.1.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json">
<HintPath>..\packages\System.Text.Json.4.7.2\lib\net461\System.Text.Json.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Auth\Authenticator.cs" />
Expand Down Expand Up @@ -80,6 +109,7 @@
<Compile Include="Utils\Helpers.cs" />
<Compile Include="DataCenter.cs" />
<Compile Include="FileSessionStore.cs" />
<Compile Include="JsonFileSessionStore.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
Expand Down
9 changes: 9 additions & 0 deletions src/TgSharp.Core/packages.config
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.AsyncInterfaces" version="1.1.0" targetFramework="net462" />
<package id="System.Buffers" version="4.5.1" targetFramework="net462" />
<package id="System.Memory" version="4.5.4" targetFramework="net462" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net462" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.7.1" targetFramework="net462" />
<package id="System.Text.Encodings.Web" version="4.7.1" targetFramework="net462" />
<package id="System.Text.Json" version="4.7.2" targetFramework="net462" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net462" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net462" />
</packages>
Loading