TLSharp/src/TgSharp.Core/Session.cs

104 lines
3.1 KiB
C#
Raw Normal View History

2020-04-02 10:37:22 +02:00
using System;
2015-09-28 04:01:17 +02:00
using System.IO;
using TgSharp.TL;
2020-04-02 10:37:22 +02:00
using TgSharp.Core.MTProto;
using TgSharp.Core.MTProto.Crypto;
2015-09-28 04:01:17 +02:00
2020-04-02 10:37:22 +02:00
namespace TgSharp.Core
2015-09-28 04:01:17 +02:00
{
2016-04-18 12:50:57 +02:00
public interface ISessionStore
{
void Save(Session session);
Session Load(string sessionUserId);
}
public class FakeSessionStore : ISessionStore
{
public void Save(Session session)
{
}
public Session Load(string sessionUserId)
{
return null;
2016-04-18 12:50:57 +02:00
}
}
internal static class SessionFactory
2016-04-18 12:50:57 +02:00
{
internal static Session TryLoadOrCreateNew (ISessionStore store, string sessionUserId)
{
var session = store.Load (sessionUserId);
if (null == session) {
var defaultDataCenter = new DataCenter ();
session = new Session {
Id = GenerateRandomUlong (),
SessionUserId = sessionUserId,
DataCenter = defaultDataCenter,
};
}
return session;
}
2016-04-18 12:50:57 +02:00
private static ulong GenerateRandomUlong ()
{
var random = new Random ();
ulong rand = (((ulong)random.Next ()) << 32) | ((ulong)random.Next ());
return rand;
}
}
public class Session
{
internal object Lock = new object ();
public int Sequence { get; set; }
#if CI
// see the same CI-wrapped assignment in .FromBytes(), but this one will become useful
// when we generate a new session.dat for CI again
= CurrentTime ();
// this is similar to the unixTime but rooted on the worst year of humanity instead of 1970
internal static int CurrentTime ()
{
return (int)DateTime.UtcNow.Subtract (new DateTime (2020, 1, 1)).TotalSeconds;
}
#endif
2016-04-18 12:50:57 +02:00
public string SessionUserId { get; set; }
internal DataCenter DataCenter { get; set; }
2016-04-18 12:50:57 +02:00
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; }
2016-09-24 15:38:26 +02:00
public TLUser TLUser { get; set; }
2016-04-18 12:50:57 +02:00
private Random random;
public Session()
2016-04-18 12:50:57 +02:00
{
random = new Random();
}
public long GetNewMessageId()
{
long time = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
long newMessageId = ((time / 1000 + TimeOffset) << 32) |
((time % 1000) << 22) |
(random.Next(524288) << 2); // 2^19
// [ unix timestamp : 32 bit] [ milliseconds : 10 bit ] [ buffer space : 1 bit ] [ random : 19 bit ] [ msg_id type : 2 bit ] = [ msg_id : 64 bit ]
if (LastMessageId >= newMessageId)
{
newMessageId = LastMessageId + 4;
}
LastMessageId = newMessageId;
return newMessageId;
}
}
2015-09-28 04:01:17 +02:00
}