System.DateTimeOffset.ToUnixTimeSeconds()

Here are the examples of the csharp api System.DateTimeOffset.ToUnixTimeSeconds() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

588 Examples 7

19 Source : LoginController.cs
with Apache License 2.0
from devonfw

[HttpPost]
        [HttpOptions]
        [Route("/mythaistar/login")]
        [AllowAnonymous]
        [EnableCors("CorsPolicy")]
        public async Task<IActionResult> Login([FromBody]LoginView loginView)
        {
            try
            {
                if (loginView == null) return Ok();
                var idenreplacedy = GetClaimsIdenreplacedy(loginView);
                if (idenreplacedy == null)
                {
                    return BadRequest("Invalid credentials");
                }
                var loged = _loginService.Login(loginView.UserName, loginView.Preplacedword);
                if (loged)
                {
                    var userScope = _loginService.GetUserScope(loginView.UserName);
                    if (!string.IsNullOrEmpty(userScope))
                    {
                        var now = new DateTimeOffset(DateTime.UtcNow);
                        var claims = new[]
                        {
                            new Claim(JwtConst.ClaimIssuer, JwtConst.Issuer),
                            new Claim(JwtRegisteredClaimNames.Sub, loginView.UserName),
                            new Claim(JwtConst.ClaimScope, userScope),
                            new Claim(JwtConst.ClaimCreated,now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
                            new Claim(JwtConst.ClaimExpiration,now.AddMinutes(60).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim(JwtRegisteredClaimNames.Iat, now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
                        };

                        // Create the JWT security token and encode it.
                        var jwt = new JwtSecurityToken(
                            issuer: _jwtOptions.Issuer,
                            audience: _jwtOptions.Audience,
                            claims: claims,
                            notBefore: _jwtOptions.NotBefore,
                            expires: _jwtOptions.Expiration.AddHours(5),
                            signingCredentials: _jwtOptions.SigningCredentials);

                        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                        var result = await _signInManager.PreplacedwordSignInAsync(loginView.UserName, "*Dev0nMts2017", true, lockoutOnFailure: false);
                        if (!result.Succeeded) return StatusCode((int)HttpStatusCode.Unauthorized, "Login Error");
                        Response.Headers.Add("Access-Control-Expose-Headers", "Authorization");
                        Response.Headers.Add("X-Content-Type-Options", "nosniff");
                        Response.Headers.Add("X-Frame-Options", "DENY");
                        Response.Headers.Add("X-XSS-Protection", "1;mode=block");
                        Response.Headers.Add("X-Application-Context", "restaurant:h2mem:8081");
                        Response.Headers.Add("Authorization", $"{JwtConst.TokenPrefix} {encodedJwt}");

                        return Ok(encodedJwt);
                    }
                }
                Response.Headers.Clear();
                return StatusCode((int)HttpStatusCode.Unauthorized, "Login Error");
            }
            catch (Exception ex)
            {
                return StatusCode((int)HttpStatusCode.InternalServerError, $"{ex.Message} : {ex.InnerException}");
            }
        }

19 Source : JwtTokenService.cs
with Apache License 2.0
from devonfw

public string GenerateToken(string userName, string userScope)
        {
            //userScope should be ROLE_Customer | ROL_Waiter
            var now = new DateTimeOffset(DateTime.UtcNow);
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConst.Secret));
            var claims = new[]
            {
                new Claim(JwtConst.ClaimIssuer, JwtConst.Issuer),
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtConst.ClaimScope, userScope),
                new Claim(JwtConst.ClaimCreated, now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtConst.ClaimExpiration, now.AddMinutes(60).ToUnixTimeSeconds().ToString(),
                    ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            };

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(claims: claims,
                signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha512));
            return new JwtSecurityTokenHandler().WriteToken(jwt);
        }

19 Source : CertificateManager.cs
with MIT License
from DIGGSweden

private long GetSecondsFromEpoc()
        {
            return DateTimeOffset.Now.ToUnixTimeSeconds();
        }

19 Source : TokenController.cs
with Apache License 2.0
from digimarc-corp

[HttpPost]
        public async Task<IActionResult> Post([FromBody] RegistryCredentials credentials)
        {
            // must specify a registry
            if (string.IsNullOrEmpty(credentials.Registry)) { return Unauthorized(); }

            // deny requests for foreign instances, if configured
            if (!string.IsNullOrEmpty(Config.Registry) && credentials.Registry.ToLowerInvariant() != Config.Registry.ToLowerInvariant())
            {
                return Unauthorized();
            }
            try
            {
                credentials.Registry = RegistryCredentials.DeAliasDockerHub(credentials.Registry);
                var handler = new AuthHandler(cache, Config, loggerFactory.CreateLogger<AuthHandler>());
                await handler.LoginAsync(credentials.Registry, credentials.Username, credentials.Preplacedword);
                var json = JsonConvert.SerializeObject(credentials);

                // publicly visible parameters for session validation
                var headers = new Dictionary<string, object>
                {
                    { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
                    { "exp", DateTimeOffset.UtcNow.ToUnixTimeSeconds() + Config.AuthTokenLifetime },
                    { "reg", credentials.Registry }
                };

                var token = new Token
                {
                    Usr = credentials.Username,
                    Pwd = credentials.Preplacedword,
                    Reg = credentials.Registry,
                    Iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                    Exp = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + Config.AuthTokenLifetime
                };

                var jwe = Jose.JWT.Encode(token, crypto, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM, extraHeaders: headers);

                return Ok(new
                {
                    token = jwe
                });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error authenticating token request.");
                return Unauthorized();
            }
        }

19 Source : RegistryAuthenticationDecoder.cs
with Apache License 2.0
from digimarc-corp

public Task<AuthenticateResult> AuthenticateAsync(string authorization)
        {
            try
            {
                var header = AuthenticationHeaderValue.Parse(authorization);
                logger.LogTrace($"Got authorization header: {header}");

                var jweHeader = Jose.JWT.Headers(header.Parameter);
                logger.LogDebug($"JWE Header: {string.Join(", ", jweHeader.Select(p => string.Join(": ", p.Key, p.Value)))}");

                if (!jweHeader.ContainsKey("exp") || (long)jweHeader["exp"] <= DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                {
                    return Task.FromResult(AuthenticateResult.Fail("{ \"error\": \"The token has expired\" }"));
                }

                var token = Jose.JWT.Decode<Token>(header.Parameter, crypto);
                var credentials = new RegistryCredentials
                {
                    Preplacedword = token.Pwd,
                    Username = token.Usr,
                    Registry = token.Reg
                };
                logger.LogDebug($"Decoded token for {credentials.Registry}");

                if (!string.IsNullOrEmpty(config.Registry) && RegistryCredentials.DeAliasDockerHub(config.Registry.ToLowerInvariant()) != credentials.Registry.ToLowerInvariant())
                {
                    return Task.FromResult(AuthenticateResult.Fail("{ error: \"The supplied token is for an unsupported registry.\" }"));
                }

                var principal = new ClaimsPrincipal(credentials.ToClaimsIdenreplacedy());
                var ticket = new AuthenticationTicket(principal, "token");

                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Token authentication failed.");
                return Task.FromResult(AuthenticateResult.Fail("{ \"error\": \"The supplied token is invalid.\" }"));
            }
        }

19 Source : CleanupServiceData.cs
with GNU General Public License v2.0
from DirtyRacer1337

public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
        {
            await Task.Yield();
            progress?.Report(0);

            var db = new JObject();
            if (!string.IsNullOrEmpty(Plugin.Instance.Configuration.TokenStorage))
            {
                db = JObject.Parse(Plugin.Instance.Configuration.TokenStorage);
            }

            var new_db = new JObject();
            foreach (var site in db)
            {
                var token = (string)site.Value;
                var timestamp = 0;

                if (token.Contains("."))
                {
                    token = Encoding.UTF8.GetString(Helper.ConvertFromBase64String(token.Split('.')[1]));
                    timestamp = (int)JObject.Parse(token)["exp"];
                }
                else
                {
                    token = Encoding.UTF8.GetString(Helper.ConvertFromBase64String(token));
                    if (token.Contains("validUntil") && int.TryParse(token.Split("validUntil=")[1].Split("&")[0], out timestamp))
                    {
                    }
                }

                if (timestamp > DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                {
                    new_db.Add(site.Key, site.Value);
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }
            }

            Plugin.Instance.Configuration.TokenStorage = JsonConvert.SerializeObject(new_db);
            Plugin.Instance.SaveConfiguration();

            if (Directory.Exists(replacedytics.LogsPath))
            {
                foreach (var file in Directory.GetFiles(replacedytics.LogsPath, "*.json.gz"))
                {
                    if (Math.Abs((DateTime.Now - File.GetCreationTime(file)).TotalDays) > 3)
                    {
                        File.Delete(file);
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                }
            }

            progress?.Report(100);
        }

19 Source : Network1service.cs
with GNU General Public License v2.0
from DirtyRacer1337

public static async Task<string> GetToken(int[] siteNum, CancellationToken cancellationToken)
        {
            var result = string.Empty;

            if (siteNum == null)
            {
                return result;
            }

            var db = new JObject();
            if (!string.IsNullOrEmpty(Plugin.Instance.Configuration.TokenStorage))
            {
                db = JObject.Parse(Plugin.Instance.Configuration.TokenStorage);
            }

            var keyName = new Uri(Helper.GetSearchBaseURL(siteNum)).Host;
            if (db.ContainsKey(keyName))
            {
                string token = (string)db[keyName],
                    res = Encoding.UTF8.GetString(Helper.ConvertFromBase64String(token.Split('.')[1]));

                if ((int)JObject.Parse(res)["exp"] > DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                {
                    result = token;
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                var http = await HTTP.Request(Helper.GetSearchBaseURL(siteNum), HttpMethod.Head, cancellationToken).ConfigureAwait(false);
                var instanceToken = http.Cookies.Where(o => o.Name == "instance_token");
                if (!instanceToken.Any())
                {
                    return result;
                }

                result = instanceToken.First().Value;

                if (db.ContainsKey(keyName))
                {
                    db[keyName] = result;
                }
                else
                {
                    db.Add(keyName, result);
                }

                Plugin.Instance.Configuration.TokenStorage = JsonConvert.SerializeObject(db);
                Plugin.Instance.SaveConfiguration();
            }

            return result;
        }

19 Source : NetworkGammaEnt.cs
with GNU General Public License v2.0
from DirtyRacer1337

public static async Task<string> GetAPIKey(int[] siteNum, CancellationToken cancellationToken)
        {
            var result = string.Empty;

            if (siteNum == null)
            {
                return result;
            }

            var db = new JObject();
            if (!string.IsNullOrEmpty(Plugin.Instance.Configuration.TokenStorage))
            {
                db = JObject.Parse(Plugin.Instance.Configuration.TokenStorage);
            }

            var keyName = new Uri(Helper.GetSearchBaseURL(siteNum)).Host;
            if (db.ContainsKey(keyName))
            {
                string token = (string)db[keyName],
                    res = Encoding.UTF8.GetString(Helper.ConvertFromBase64String(token));

                if (res.Contains("validUntil") && int.TryParse(res.Split("validUntil=")[1].Split("&")[0], out var timestamp))
                {
                    if (timestamp > DateTimeOffset.UtcNow.ToUnixTimeSeconds())
                    {
                        result = token;
                    }
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                var http = await HTTP.Request(Helper.GetSearchBaseURL(siteNum) + "/en/login", cancellationToken).ConfigureAwait(false);
                if (http.IsOK)
                {
                    var regEx = Regex.Match(http.Content, "\"apiKey\":\"(.*?)\"");
                    if (regEx.Groups.Count > 0)
                    {
                        result = regEx.Groups[1].Value;
                    }
                }

                if (db.ContainsKey(keyName))
                {
                    db[keyName] = result;
                }
                else
                {
                    db.Add(keyName, result);
                }

                Plugin.Instance.Configuration.TokenStorage = JsonConvert.SerializeObject(db);
                Plugin.Instance.SaveConfiguration();
            }

            return result;
        }

19 Source : TimestampTag.cs
with MIT License
from Discord-Net-Labs

public override string ToString()
        {
            return $"<t:{((DateTimeOffset)Time).ToUnixTimeSeconds()}:{(char)Style}>";
        }

19 Source : RequestBucket.cs
with MIT License
from discord-net

public void UpdateRateLimit(RateLimitInfo info)
        {
            if (WindowCount == 0)
                return;

            lock (_lock)
            {
                bool hasQueuedReset = _resetsAt != null;
                if (info.Limit.HasValue && WindowCount != info.Limit.Value)
                {
                    WindowCount = info.Limit.Value;
                    _semapreplaced = info.Remaining.Value;
                }

                long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                DateTimeOffset? resetsAt = null;

                //Using X-RateLimit-Remaining causes a race condition
                /*if (info.Remaining.HasValue)
                    _semapreplaced = info.Remaining.Value;*/
                if (info.RetryAfter.HasValue) //Millis
                    resetsAt = DateTimeOffset.UtcNow.AddMilliseconds(info.RetryAfter.Value);
                else if (info.Reset.HasValue) //Secs
                    resetsAt = info.Reset.Value.AddSeconds(info.Lag?.TotalSeconds ?? 1.0);

                if (resetsAt == null)
                {
                    WindowCount = 0; //No rate limit info, disable limits on this bucket (should only ever happen with a user token)
                    return;
                }

                if (!hasQueuedReset || resetsAt > _resetsAt)
                {
                    _resetsAt = resetsAt;
                    LastAttemptAt = resetsAt.Value; //Make sure we dont destroy this until after its been reset

                    if (!hasQueuedReset)
                    {
                        int millis = (int)Math.Ceiling((_resetsAt.Value - DateTimeOffset.UtcNow).TotalMilliseconds);
                        var _ = QueueReset(millis);
                    }
                }
            }
        }

19 Source : HackerNewsResult.cs
with GNU General Public License v3.0
from dkgv

private long GetHoursAgo(HackerNewsSubmission submission)
        {
            var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            var then = submission.Time;
            var sSince = now - then;
            var mSince = sSince / 60;
            var hSince = mSince / 60;
            return hSince;
        }

19 Source : JwtFactory.cs
with MIT License
from dnikolovv

public string GenerateEncodedToken(string userId, string email, IEnumerable<Claim> additionalClaims)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userId),
                new Claim(JwtRegisteredClaimNames.Email, email),
                new Claim(JwtRegisteredClaimNames.Jti, _jwtConfiguration.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
            }
            .Concat(additionalClaims);

            var jwt = new JwtSecurityToken(
                issuer: _jwtConfiguration.Issuer,
                audience: _jwtConfiguration.Audience,
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.Add(_jwtConfiguration.ValidFor),
                signingCredentials: _jwtConfiguration.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return encodedJwt;
        }

19 Source : TokenMaker.cs
with MIT License
from doddgu

public static string GetJWT(int userID, string userName, List<string> lstPermisionCode)
        {
            var claims = new List<Claim>
            {
                new Claim("sub", userID.ToString()),
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMonths(1)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss, "API"),
                new Claim(JwtRegisteredClaimNames.Aud, "User"),
            };

            lstPermisionCode.ForEach(pc => claims.Add(new Claim("AlpacaPermission", pc)));

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
            var jwt = new JwtSecurityToken(new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.HmacSha256)), new JwtPayload(claims));
            var handler = new JwtSecurityTokenHandler();

            return handler.WriteToken(jwt);
        }

19 Source : HttpTransport.cs
with MIT License
from doghappy

string AppendRandom(string uri)
        {
            return uri + "&t=" + DateTimeOffset.Now.ToUnixTimeSeconds();
        }

19 Source : Backoff.cs
with Apache License 2.0
from eaba

public virtual long Next()
		{
			var current = _next;
			if (current < _max)
			{
				_next = Math.Min(_next * 2, _max);
			}

			// Check for mandatory stop
			if (!_mandatoryStopMade)
			{
				var now = _clock.ToUnixTimeSeconds();
				long timeElapsedSinceFirstBackoff = 0;
				if (_initial == current)
				{
					_firstBackoffTimeInMillis = now;
				}
				else
				{
					timeElapsedSinceFirstBackoff = now - _firstBackoffTimeInMillis;
				}

				if (timeElapsedSinceFirstBackoff + current > _mandatoryStop)
				{
					current = Math.Max(_initial, _mandatoryStop - timeElapsedSinceFirstBackoff);
					_mandatoryStopMade = true;
				}
			}

			// Randomly decrease the timeout up to 10% to avoid simultaneous retries
			// If current < 10 then current/10 < 1 and we get an exception from Random saying "Bound must be positive"
			if (current > 10)
			{
				current -= _random.Next((int)current / 10);
			}
			return Math.Max(_initial, current);
		}

19 Source : DateTimeExtensions.cs
with MIT License
from EasyAbp

public static long GetUtcUnixTimestamp() => DateTimeOffset.UtcNow.ToUnixTimeSeconds();

19 Source : NotificationSource.cs
with MIT License
from egramtel

public IObservable<Notification> MessagesNotifications()
        {
            return _agent.Updates
                .OfType<TdApi.Update.UpdateNewMessage>()
                .Where(u => !u.DisableNotification)
                .Where(u => u.Message.Date > DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 60)
                .Select(update => update.Message)
                .SelectSeq(message =>
                {
                    return GetChat(message.ChatId)
                        .Select(chat => new Notification
                        {
                            Chat = chat,
                            Message = message
                        });
                });
        }

19 Source : WebAuthentication.cs
with Apache License 2.0
from elucidsoft

private static bool ValidateTimeBounds(TimeBounds timeBounds, DateTimeOffset now)
        {
            if (timeBounds is null) return false;
            if (timeBounds.MinTime == 0 || timeBounds.MaxTime == 0) return false;
            var unixNow = now.ToUnixTimeSeconds();
            return timeBounds.MinTime <= unixNow && unixNow <= timeBounds.MaxTime;
        }

19 Source : TimeTests.cs
with BSD 2-Clause "Simplified" License
from emilianavt

[Test]
        public void TimeTest()
        {
            var f = new MsgPackFormatter();

            {
                f.GetStore().Clear();
                var time = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
                f.Value(time);

                var bytes = f.GetStoreBytes().ArrayOrCopy();
                unchecked
                {
                    replacedert.AreEqual(new byte[]
                    {
                (byte)MsgPackType.FIX_EXT_4, (byte)-1, 0, 0, 0, 0
                    }, bytes);
                }
                var parsed = MsgPackParser.Parse(bytes).GetValue();
                replacedert.AreEqual(time, parsed);
            }

            {
                var time = new DateTimeOffset(2018, 12, 8, 2, 12, 15, TimeSpan.Zero);
                replacedert.AreEqual(1544235135, time.ToUnixTimeSeconds());
                f.GetStore().Clear();
                f.Value(time);
                var bytes = f.GetStoreBytes().ArrayOrCopy();
                var parsed = MsgPackParser.Parse(bytes).GetValue();
                replacedert.AreEqual(time, parsed);
            }

            {
                f.GetStore().Clear();
                replacedert.Catch(() =>
                {
                    f.Value(new DateTimeOffset());
                });
            }
        }

19 Source : MsgPackFormatter.cs
with BSD 2-Clause "Simplified" License
from emilianavt

public void TimeStamp32(DateTimeOffset time)
        {
            // https://github.com/ousttrue/UniJSON/blob/1.2/Scripts/Extensions/DateTimeOffsetExtensions.cs#L13-L16
            if (time < DateTimeOffsetExtensions.EpochTime)
            {
                throw new ArgumentOutOfRangeException();
            }
            m_store.Write((Byte)MsgPackType.FIX_EXT_4);
            m_store.Write((SByte)(-1));
            m_store.WriteBigEndian((uint)time.ToUnixTimeSeconds());
        }

19 Source : Platform.cs
with MIT License
from emily33901

public static uint ToUnixTime(DateTime t)
        {
            return (uint)(new DateTimeOffset(t)).ToUnixTimeSeconds();
        }

19 Source : Utility.cs
with GNU General Public License v3.0
from Erisa

public static long ToUnixTimestamp(DateTime? dateTime)
        {
            return ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
        }

19 Source : WeChatPayUtility.cs
with MIT License
from essensoft

public static string GetTimeStamp()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        }

19 Source : Utils.cs
with GNU Affero General Public License v3.0
from Executor-Cheng

public static int DateTime2UnixTimeSeconds(DateTime time)
            => (int)new DateTimeOffset(time).ToUnixTimeSeconds();

19 Source : JwtTokenGenerator.cs
with GNU General Public License v3.0
from explorer14

private static IEnumerable<Claim> MergeUserClaimsWithDefaultClaims(string userName,
            IEnumerable<Claim> userClaims)
        {
            var claims = new List<Claim>(userClaims)
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat,
                    DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
                    ClaimValueTypes.Integer64)
            };

            return claims;
        }

19 Source : TokenController.cs
with MIT License
from eyazici90

[NonAction]
        private GetTokenResponse Generate(string username, List<Claim> claimList)
        {
            var dtExpired = new DateTimeOffset(DateTime.Now.AddMinutes(180));

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, dtExpired.ToUnixTimeSeconds().ToString()),
                new Claim(JwtRegisteredClaimNames.Iss, $"IdenreplacedyIssuer"),
                new Claim(JwtRegisteredClaimNames.Aud, $"IdenreplacedyAudience")
            };

            if (claimList != null || claimList.Any())
                claims.AddRange(claimList);


            var token = new JwtSecurityToken(
                new JwtHeader(new SigningCredentials(SecurityKeyExtension.GetSigningKey("IdenreplacedyAPIseckey2017!.#")
                                            , SecurityAlgorithms.HmacSha256)),
                new JwtPayload(claims));
             
            return new GetTokenResponse
            {
                ExpiredDate = dtExpired,
                Token = new JwtSecurityTokenHandler().WriteToken(token)
            };
        }

19 Source : SqliteExtensions.cs
with GNU General Public License v3.0
from faush01

public static void TryBind(this IStatement statement, int index, DateTimeOffset value, bool enableMsPrecision)
        {
            IBindParameter bindParam = statement.BindParameters[index];

            if (enableMsPrecision)
            {
                bindParam.Bind(value.ToUnixTimeMilliseconds());
            }
            else
            {
                bindParam.Bind(value.ToUnixTimeSeconds());
            }
        }

19 Source : SqliteExtensions.cs
with GNU General Public License v3.0
from faush01

public static void TryBind(this IStatement statement, string name, DateTimeOffset value, bool enableMsPrecision)
        {
            IBindParameter bindParam;
            if (statement.BindParameters.TryGetValue(name, out bindParam))
            {
                if (enableMsPrecision)
                {
                    bindParam.Bind(value.ToUnixTimeMilliseconds());
                }
                else
                {
                    bindParam.Bind(value.ToUnixTimeSeconds());
                }
            }
            else
            {
                CheckName(name);
            }
        }

19 Source : JwtHelper.cs
with MIT License
from feiyit

public static string IssueJWT(TokenModel tokenModel)
        {
            var jwtConfig = new JwtAuthConfigModel();
            //过期时间(分钟)
            double exp = 0;
            switch (tokenModel.TokenType)
            {
                case "Web":
                    exp = jwtConfig.WebExp;
                    break;
                case "App":
                    exp = jwtConfig.AppExp;
                    break;
                case "Wx":
                    exp = jwtConfig.WxExp;
                    break;
                case "Other":
                    exp = jwtConfig.OtherExp;
                    break;
            }
            var dateTime = DateTime.UtcNow;
            var claims = new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid),
                    new Claim("UserName", tokenModel.UserName),//用户名
                    new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") , 
                    //这个就是过期时间,目前是过期100秒,可自定义,注意JWT有自己的缓冲过期时间
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(exp)).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Iss,jwtConfig.Issuer),
                    new Claim(JwtRegisteredClaimNames.Aud,jwtConfig.Audience),
                    new Claim(ClaimTypes.Role,tokenModel.Role),
               };
            //秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.JWTSecretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(
                issuer: jwtConfig.Issuer,
                audience: jwtConfig.Audience,
                claims: claims,
                expires: dateTime.AddMinutes(exp),
                signingCredentials: creds);
            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);
            return encodedJwt;
        }

19 Source : Utils.cs
with MIT License
from FelisDiligens

public static long GetUnixTimeStamp()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        }

19 Source : FMDataIni.Generated.cs
with MIT License
from FenPhoenix

private static void WriteFMDataIni(List<FanMission> fmDataList, string fileName)
        {
            // Averaged over the 1573 FMs in my FMData.ini file (in new HasResources format)
            const int averageFMEntryCharCount = 378;
            var sb = new StringBuilder(averageFMEntryCharCount * fmDataList.Count);

            foreach (FanMission fm in fmDataList)
            {
                sb.AppendLine("[FM]");

                if (fm.NoArchive)
                {
                    sb.Append("NoArchive=");
                    sb.AppendLine(fm.NoArchive.ToString());
                }
                if (fm.MarkedScanned)
                {
                    sb.Append("MarkedScanned=");
                    sb.AppendLine(fm.MarkedScanned.ToString());
                }
                if (fm.Pinned)
                {
                    sb.Append("Pinned=");
                    sb.AppendLine(fm.Pinned.ToString());
                }
                if (!string.IsNullOrEmpty(fm.Archive))
                {
                    sb.Append("Archive=");
                    sb.AppendLine(fm.Archive);
                }
                if (!string.IsNullOrEmpty(fm.InstalledDir))
                {
                    sb.Append("InstalledDir=");
                    sb.AppendLine(fm.InstalledDir);
                }
                if (!string.IsNullOrEmpty(fm.replacedle))
                {
                    sb.Append("replacedle=");
                    sb.AppendLine(fm.replacedle);
                }
                foreach (string s in fm.Altreplacedles)
                {
                    sb.Append("Altreplacedles=");
                    sb.AppendLine(s);
                }
                if (!string.IsNullOrEmpty(fm.Author))
                {
                    sb.Append("Author=");
                    sb.AppendLine(fm.Author);
                }
                switch (fm.Game)
                {
                    // Much faster to do this than Enum.ToString()
                    case Game.Thief1:
                        sb.AppendLine("Game=Thief1");
                        break;
                    case Game.Thief2:
                        sb.AppendLine("Game=Thief2");
                        break;
                    case Game.Thief3:
                        sb.AppendLine("Game=Thief3");
                        break;
                    case Game.SS2:
                        sb.AppendLine("Game=SS2");
                        break;
                    case Game.Unsupported:
                        sb.AppendLine("Game=Unsupported");
                        break;
                        // Don't handle Game.Null because we don't want to write out defaults
                }
                if (fm.Installed)
                {
                    sb.Append("Installed=");
                    sb.AppendLine(fm.Installed.ToString());
                }
                if (fm.NoReadmes)
                {
                    sb.Append("NoReadmes=");
                    sb.AppendLine(fm.NoReadmes.ToString());
                }
                if (!string.IsNullOrEmpty(fm.SelectedReadme))
                {
                    sb.Append("SelectedReadme=");
                    sb.AppendLine(fm.SelectedReadme);
                }
                foreach (string s in fm.ReadmeAndCodePageEntries)
                {
                    sb.Append("ReadmeEncoding=");
                    sb.AppendLine(s);
                }
                if (fm.SizeBytes != 0)
                {
                    sb.Append("SizeBytes=");
                    sb.AppendLine(fm.SizeBytes.ToString());
                }
                if (fm.Rating != -1)
                {
                    sb.Append("Rating=");
                    sb.AppendLine(fm.Rating.ToString());
                }
                if (!string.IsNullOrEmpty(fm.ReleaseDate.UnixDateString))
                {
                    sb.Append("ReleaseDate=");
                    sb.AppendLine(fm.ReleaseDate.UnixDateString);
                }
                if (!string.IsNullOrEmpty(fm.LastPlayed.UnixDateString))
                {
                    sb.Append("LastPlayed=");
                    sb.AppendLine(fm.LastPlayed.UnixDateString);
                }
                if (fm.DateAdded != null)
                {
                    sb.Append("DateAdded=");
                    // Again, important to convert to local time here because we don't do it on startup.
                    sb.AppendLine(new DateTimeOffset(((DateTime)fm.DateAdded).ToLocalTime()).ToUnixTimeSeconds().ToString("X"));
                }
                if (fm.FinishedOn != 0)
                {
                    sb.Append("FinishedOn=");
                    sb.AppendLine(fm.FinishedOn.ToString());
                }
                if (fm.FinishedOnUnknown)
                {
                    sb.Append("FinishedOnUnknown=");
                    sb.AppendLine(fm.FinishedOnUnknown.ToString());
                }
                if (!string.IsNullOrEmpty(fm.Comment))
                {
                    sb.Append("Comment=");
                    sb.AppendLine(fm.Comment);
                }
                if (!string.IsNullOrEmpty(fm.DisabledMods))
                {
                    sb.Append("DisabledMods=");
                    sb.AppendLine(fm.DisabledMods);
                }
#if write_old_resources_style
                if (fm.ResourcesScanned)
                {
                    sb.AppendLine("HasMap=" + FMHasResource(fm, CustomResources.Map).ToString());
                    sb.AppendLine("HasAutomap=" + FMHasResource(fm, CustomResources.Automap).ToString());
                    sb.AppendLine("Hreplacedcripts=" + FMHasResource(fm, CustomResources.Scripts).ToString());
                    sb.AppendLine("HasTextures=" + FMHasResource(fm, CustomResources.Textures).ToString());
                    sb.AppendLine("Hreplacedounds=" + FMHasResource(fm, CustomResources.Sounds).ToString());
                    sb.AppendLine("HasObjects=" + FMHasResource(fm, CustomResources.Objects).ToString());
                    sb.AppendLine("HasCreatures=" + FMHasResource(fm, CustomResources.Creatures).ToString());
                    sb.AppendLine("HasMotions=" + FMHasResource(fm, CustomResources.Motions).ToString());
                    sb.AppendLine("HasMovies=" + FMHasResource(fm, CustomResources.Movies).ToString());
                    sb.AppendLine("Hreplacedubreplacedles=" + FMHasResource(fm, CustomResources.Subreplacedles).ToString());
                }
#else
                sb.Append("HasResources=");
                if (fm.ResourcesScanned)
                {
                    CommaCombineHasXFields(fm, sb);
                }
                else
                {
                    sb.AppendLine("NotScanned");
                }
#endif
                if (fm.LangsScanned)
                {
                    sb.Append("LangsScanned=");
                    sb.AppendLine(fm.LangsScanned.ToString());
                }
                if (!string.IsNullOrEmpty(fm.Langs))
                {
                    sb.Append("Langs=");
                    sb.AppendLine(fm.Langs);
                }
                if (!string.IsNullOrEmpty(fm.SelectedLang))
                {
                    sb.Append("SelectedLang=");
                    sb.AppendLine(fm.SelectedLang);
                }
                if (!string.IsNullOrEmpty(fm.TagsString))
                {
                    sb.Append("TagsString=");
                    sb.AppendLine(fm.TagsString);
                }
            }

            using var sw = new StreamWriter(fileName, false, Encoding.UTF8);
            sw.Write(sb.ToString());
        }

19 Source : IniCommon.cs
with MIT License
from FenPhoenix

private static string FilterDate(DateTime? dt) => dt == null
            ? ""
            : new DateTimeOffset((DateTime)dt).ToUnixTimeSeconds().ToString("X");

19 Source : SqliteExtensions.cs
with GNU General Public License v3.0
from firecore

public static void TryBind(this IStatement statement, string name, DateTimeOffset value, bool enableMsPrecision)
        {
            IBindParameter bindParam;
            if (statement.BindParameters.TryGetValue(name, out bindParam))
            {
                if (enableMsPrecision)
                {
                    bindParam.Bind(value.ToUnixTimeMilliseconds());
                }
                else
                {
                    bindParam.Bind(value.ToUnixTimeSeconds());
                }
            }
            else
            {
                ThrowInvalidParamName(statement, name);
            }
        }

19 Source : PlayCommands.cs
with GNU General Public License v3.0
from fmbot-discord

[Command("plays", RunMode = RunMode.Async)]
        [Summary("Shows your total scrobblecount for a specific time period.")]
        [Options(Constants.CompactTimePeriodList, Constants.UserMentionExample)]
        [Examples("p", "plays", "plays @frikandel", "plays monthly")]
        [Alias("p", "scrobbles")]
        [UsernameSetRequired]
        public async Task PlaysAsync([Remainder] string extraOptions = null)
        {
            var user = await this._userService.GetUserSettingsAsync(this.Context.User);

            _ = this.Context.Channel.TriggerTypingAsync();

            var timeType = SettingService.GetTimePeriod(extraOptions, TimePeriod.AllTime);
            var userSettings = await this._settingService.GetUser(timeType.NewSearchValue, user, this.Context, true);

            long? timeFrom = null;
            if (timeType.TimePeriod != TimePeriod.AllTime && timeType.PlayDays != null)
            {
                var dateAgo = DateTime.UtcNow.AddDays(-timeType.PlayDays.Value);
                timeFrom = ((DateTimeOffset)dateAgo).ToUnixTimeSeconds();
            }

            var count = await this._lastFmRepository.GetScrobbleCountFromDateAsync(userSettings.UserNameLastFm, timeFrom);

            var userreplacedle = $"{userSettings.DiscordUserName.FilterOutMentions()}{userSettings.UserType.UserTypeToIcon()}";

            var reply =
                $"**{userreplacedle}** has `{count}` total scrobbles";

            if (timeType.TimePeriod == TimePeriod.AllTime)
            {
                await this.Context.Channel.SendMessageAsync($"**{userreplacedle}** has `{count}` total scrobbles");
            }
            else
            {
                await this.Context.Channel.SendMessageAsync($"**{userreplacedle}** has `{count}` scrobbles in the {timeType.AltDescription}");
            }
            this.Context.LogCommandUsed();
        }

19 Source : AdminCommands.cs
with GNU General Public License v3.0
from fmbot-discord

[Command("getusers")]
        [Examples("getusers frikandel_")]
        [GuildOnly]
        public async Task GetUsersForLastfmUserNameAsync(string userString = null)
        {
            if (await this._adminService.HasCommandAccessAsync(this.Context.User, UserType.Admin))
            {
                var guild = await this._guildService.GetGuildAsync(this.Context.Guild.Id);

                if (guild.SpecialGuild != true)
                {
                    await ReplyAsync("This command can only be used in special guilds.");
                    this.Context.LogCommandUsed(CommandResponse.NoPermission);
                    return;
                }

                if (string.IsNullOrEmpty(userString))
                {
                    await ReplyAsync("Enter a Last.fm username to get the accounts for.");
                    this.Context.LogCommandUsed(CommandResponse.WrongInput);
                    return;
                }

                var users = await this._adminService.GetUsersWithLfmUsernameAsync(userString);

                this._embed.Withreplacedle($"All .fmbot users with Last.fm username {userString}");

                foreach (var user in users)
                {
                    var userDescription = new StringBuilder();

                    if (user.SessionKeyLastFm != null)
                    {
                        userDescription.AppendLine($"Authorized");
                    }

                    userDescription.AppendLine($"`{user.DiscordUserId}`");
                    userDescription.AppendLine($"<@{user.DiscordUserId}>");

                    if (user.LastUsed.HasValue)
                    {
                        var specifiedDateTime = DateTime.SpecifyKind(user.LastUsed.Value, DateTimeKind.Utc);
                        var dateValue = ((DateTimeOffset)specifiedDateTime).ToUnixTimeSeconds();

                        userDescription.AppendLine($"Last used: <t:{dateValue}:R>.");
                    }

                    this._embed.AddField($"{user.UserId}", userDescription.ToString());
                }

                this._embed.WithFooter("Command not intended for use in public channels");

                await ReplyAsync("", false, this._embed.Build()).ConfigureAwait(false);
                this.Context.LogCommandUsed();

            }
            else
            {
                await ReplyAsync("Error: Insufficient rights. Only .fmbot staff can use this command");
                this.Context.LogCommandUsed(CommandResponse.NoPermission);
            }
        }

19 Source : CrownCommands.cs
with GNU General Public License v3.0
from fmbot-discord

[Command("crowns", RunMode = RunMode.Async)]
        [Summary("Shows you your crowns for this server.")]
        [Alias("cws")]
        [UsernameSetRequired]
        [GuildOnly]
        [SupportsPagination]
        [RequiresIndex]
        public async Task UserCrownsAsync([Remainder] string extraOptions = null)
        {
            var contextUser = await this._userService.GetUserSettingsAsync(this.Context.User);
            var prfx = this._prefixService.GetPrefix(this.Context.Guild?.Id);
            var guild = await this._guildService.GetFullGuildAsync(this.Context.Guild.Id);

            if (guild.CrownsDisabled == true)
            {
                await ReplyAsync("Crown functionality has been disabled in this server.");
                this.Context.LogCommandUsed(CommandResponse.Disabled);
                return;
            }

            var userreplacedle = await this._userService.GetUserreplacedleAsync(this.Context);

            var differentUser = false;
            if (!string.IsNullOrWhiteSpace(extraOptions))
            {
                var userSettings = await this._settingService.StringWithDiscordIdForUser(extraOptions);

                if (userSettings != null)
                {
                    contextUser = userSettings;
                    differentUser = true;
                }
            }

            var crownViewSettings = new CrownViewSettings
            {
                CrownOrderType = CrownOrderType.Playcount
            };

            crownViewSettings = SettingService.SetCrownViewSettings(crownViewSettings, extraOptions);
            var userCrowns = await this._crownService.GetCrownsForUser(guild, contextUser.UserId, crownViewSettings.CrownOrderType);

            var replacedle = differentUser
                ? $"Crowns for {contextUser.UserNameLastFM}, requested by {userreplacedle}"
                : $"Crowns for {userreplacedle}";

            if (!userCrowns.Any())
            {
                this._embed.WithDescription($"You or the user you're searching for don't have any crowns yet. \n" +
                                            $"Use `{prfx}whoknows` to start getting crowns!");
                await this.Context.Channel.SendMessageAsync("", false, this._embed.Build());
                this.Context.LogCommandUsed();
                return;
            }

            try
            {
                var pages = new List<PageBuilder>();

                var crownPages = userCrowns.ChunkBy(10);

                var counter = 1;
                var pageCounter = 1;
                foreach (var crownPage in crownPages)
                {
                    var crownPageString = new StringBuilder();
                    foreach (var userCrown in crownPage)
                    {
                        crownPageString.AppendLine($"{counter}. **{userCrown.ArtistName}** - **{userCrown.CurrentPlaycount}** plays (claimed <t:{((DateTimeOffset)userCrown.Created).ToUnixTimeSeconds()}:R>)");
                        counter++;
                    }

                    var footer = new StringBuilder();

                    footer.AppendLine($"Page {pageCounter}/{crownPages.Count} - {userCrowns.Count} total crowns");

                    if (crownViewSettings.CrownOrderType == CrownOrderType.Playcount)
                    {
                        footer.AppendLine("Ordered by playcount - Available options: playcount and recent");
                    }
                    else
                    {
                        footer.AppendLine("Ordered by recent crowns - Available options: playcount and recent");
                    }

                    pages.Add(new PageBuilder()
                        .WithDescription(crownPageString.ToString())
                        .Withreplacedle(replacedle)
                        .WithFooter(footer.ToString()));
                    pageCounter++;
                }

                var paginator = StringService.BuildStaticPaginator(pages);

                _ = this.Interactivity.SendPaginatorAsync(
                    paginator,
                    this.Context.Channel,
                    TimeSpan.FromMinutes(DiscordConstants.PaginationTimeoutInSeconds));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            this.Context.LogCommandUsed();
        }

19 Source : PlayCommands.cs
with GNU General Public License v3.0
from fmbot-discord

[Command("pace", RunMode = RunMode.Async)]
        [Summary("Displays the date you reach a scrobble goal based on average scrobbles per day.")]
        [Options(Constants.CompactTimePeriodList, "Optional goal amount: For example `10000` or `10k`", Constants.UserMentionExample)]
        [Examples("pc", "pc 100k q", "pc 40000 h @user", "pace", "pace yearly @user 250000")]
        [UsernameSetRequired]
        [Alias("pc")]
        public async Task PaceAsync([Remainder] string extraOptions = null)
        {
            var user = await this._userService.GetUserSettingsAsync(this.Context.User);

            _ = this.Context.Channel.TriggerTypingAsync();

            var userSettings = await this._settingService.GetUser(extraOptions, user, this.Context);
            var userInfo = await this._lastFmRepository.GetLfmUserInfoAsync(userSettings.UserNameLastFm, userSettings.SessionKeyLastFm);

            var goalAmount = SettingService.GetGoalAmount(extraOptions, userInfo.Playcount);

            var timeType = SettingService.GetTimePeriod(extraOptions, TimePeriod.AllTime);

            long timeFrom;
            if (timeType.TimePeriod != TimePeriod.AllTime && timeType.PlayDays != null)
            {
                var dateAgo = DateTime.UtcNow.AddDays(-timeType.PlayDays.Value);
                timeFrom = ((DateTimeOffset)dateAgo).ToUnixTimeSeconds();
            }
            else
            {
                timeFrom = userInfo.Registered.Unixtime;
            }

            var count = await this._lastFmRepository.GetScrobbleCountFromDateAsync(userSettings.UserNameLastFm, timeFrom, userSettings.SessionKeyLastFm);

            if (count == null || count == 0)
            {
                var errorReply = $"<@{this.Context.User.Id}> No plays found in the {timeType.Description} time period.";

                await this.Context.Channel.SendMessageAsync(errorReply);
            }

            var age = DateTimeOffset.FromUnixTimeSeconds(timeFrom);
            var totalDays = (DateTime.UtcNow - age).TotalDays;

            var playsLeft = goalAmount - userInfo.Playcount;

            var avgPerDay = count / totalDays;

            var goalDate = (DateTime.UtcNow.AddDays(playsLeft / avgPerDay.Value));

            var reply = new StringBuilder();

            var determiner = "your";
            if (userSettings.DifferentUser)
            {
                reply.Append($"<@{this.Context.User.Id}> My estimate is that the user '{userSettings.UserNameLastFm.FilterOutMentions()}'");
                determiner = "their";
            }
            else
            {
                reply.Append($"<@{this.Context.User.Id}> My estimate is that you");
            }

            reply.AppendLine($" will reach **{goalAmount}** scrobbles on **<t:{goalDate.ToUnixEpochDate()}:D>**.");

            if (timeType.TimePeriod == TimePeriod.AllTime)
            {
                reply.AppendLine(
                    $"This is based on {determiner} alltime avg of {Math.Round(avgPerDay.GetValueOrDefault(0), 1)} per day. ({count} in {Math.Round(totalDays, 0)} days)");
            }
            else
            {
                reply.AppendLine(
                    $"This is based on {determiner} avg of {Math.Round(avgPerDay.GetValueOrDefault(0), 1)} per day in the last {Math.Round(totalDays, 0)} days ({count} total)");
            }

            await this.Context.Channel.SendMessageAsync(reply.ToString());

            this.Context.LogCommandUsed();
        }

19 Source : AdminCommands.cs
with GNU General Public License v3.0
from fmbot-discord

[Command("checkbotted")]
        [Alias("checkbotteduser")]
        [Summary("Checks some stats for a user and if they're banned from global whoknows")]
        public async Task CheckBottedUserAsync(string user = null)
        {
            if (await this._adminService.HasCommandAccessAsync(this.Context.User, UserType.Admin))
            {
                if (string.IsNullOrEmpty(user))
                {
                    await ReplyAsync("Enter an username to check\n" +
                                     "Example: `.fmcheckbotted Kefkef123`");
                    return;
                }

                _ = this.Context.Channel.TriggerTypingAsync();

                var contextUser = await this._userService.GetUserSettingsAsync(this.Context.User);
                var targetedUser = await this._settingService.GetUser(user, contextUser, this.Context);

                if (targetedUser.DifferentUser)
                {
                    user = targetedUser.UserNameLastFm;
                }

                var bottedUser = await this._adminService.GetBottedUserAsync(user);

                var userInfo = await this._lastFmRepository.GetLfmUserInfoAsync(user);

                this._embed.Withreplacedle($"Botted check for Last.fm '{user}'");

                if (userInfo == null)
                {
                    this._embed.WithDescription($"Not found on Last.fm - [User]({Constants.LastFMUserUrl}{user})");
                }
                else
                {
                    this._embed.WithDescription($"[Profile]({Constants.LastFMUserUrl}{user}) - " +
                                                $"[Library]({Constants.LastFMUserUrl}{user}/library) - " +
                                                $"[Last.week]({Constants.LastFMUserUrl}{user}/listening-report) - " +
                                                $"[Last.year]({Constants.LastFMUserUrl}{user}/listening-report/year)");

                    var dateAgo = DateTime.UtcNow.AddDays(-365);
                    var timeFrom = ((DateTimeOffset)dateAgo).ToUnixTimeSeconds();

                    var count = await this._lastFmRepository.GetScrobbleCountFromDateAsync(user, timeFrom);

                    var age = DateTimeOffset.FromUnixTimeSeconds(timeFrom);
                    var totalDays = (DateTime.UtcNow - age).TotalDays;

                    var avgPerDay = count / totalDays;
                    this._embed.AddField("Avg scrobbles / day in last year", Math.Round(avgPerDay.GetValueOrDefault(0), 1));
                }

                this._embed.AddField("Banned from GlobalWhoKnows", bottedUser == null ? "No" : bottedUser.BanActive ? "Yes" : "No, but has been banned before");
                if (bottedUser != null)
                {
                    this._embed.AddField("Reason / additional notes", bottedUser.Notes ?? "*No reason/notes*");
                }

                this._embed.WithFooter("Command not intended for use in public channels");

                await ReplyAsync("", false, this._embed.Build()).ConfigureAwait(false);
                this.Context.LogCommandUsed();
            }
            else
            {
                await ReplyAsync("Error: Insufficient rights. Only .fmbot staff can check botted users");
                this.Context.LogCommandUsed(CommandResponse.NoPermission);
            }
        }

19 Source : PlayService.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<string> GetStreak(int userId, Response<RecentTrackList> recentTracks)
        {
            await using var db = this._contextFactory.CreateDbContext();
            var lastPlays = await db.UserPlays
                .AsQueryable()
                .Where(w => w.UserId == userId)
                .OrderByDescending(o => o.TimePlayed)
                .ToListAsync();

            if (!lastPlays.Any())
            {
                return null;
            }

            var firstPlay = recentTracks.Content.RecentTracks.First();

            var artistCount = 1;
            var albumCount = 1;
            var trackCount = 1;

            var streakStarted = new DateTime?();

            var artistContinue = true;
            var albumContinue = true;
            var trackContinue = true;
            for (var i = 1; i < lastPlays.Count; i++)
            {
                var play = lastPlays[i];

                if (firstPlay.ArtistName.ToLower() == play.ArtistName.ToLower() && artistContinue)
                {
                    artistCount++;
                    streakStarted = play.TimePlayed;
                }
                else
                {
                    artistContinue = false;
                }

                if (firstPlay.AlbumName != null && play.AlbumName != null && firstPlay.AlbumName.ToLower() == play.AlbumName.ToLower() && albumContinue)
                {
                    albumCount++;
                    streakStarted = play.TimePlayed;
                }
                else
                {
                    albumContinue = false;
                }

                if (firstPlay.TrackName.ToLower() == play.TrackName.ToLower() && trackContinue)
                {
                    trackCount++;
                    streakStarted = play.TimePlayed;
                }
                else
                {
                    trackContinue = false;
                }

                if (!artistContinue && !albumContinue && !trackContinue)
                {
                    break;
                }
            }

            var description = new StringBuilder();
            if (artistCount > 1)
            {
                description.AppendLine($"Artist: **[{firstPlay.ArtistName}](https://www.last.fm/music/{HttpUtility.UrlEncode(firstPlay.ArtistName)})** - " +
                                       $"{GetEmojiForStreakCount(artistCount)}*{artistCount} plays in a row*");
            }
            if (albumCount > 1)
            {
                description.AppendLine($"Album: **[{firstPlay.AlbumName}](https://www.last.fm/music/{HttpUtility.UrlEncode(firstPlay.ArtistName)}/{HttpUtility.UrlEncode(firstPlay.AlbumName)})** - " +
                                       $"{GetEmojiForStreakCount(albumCount)}*{albumCount} plays in a row*");
            }
            if (trackCount > 1)
            {
                description.AppendLine($"Track: **[{firstPlay.TrackName}](https://www.last.fm/music/{HttpUtility.UrlEncode(firstPlay.ArtistName)}/_/{HttpUtility.UrlEncode(firstPlay.TrackName)})** - " +
                                       $"{GetEmojiForStreakCount(trackCount)}*{trackCount} plays in a row*");
            }

            if (streakStarted.HasValue)
            {
                var specifiedDateTime = DateTime.SpecifyKind(streakStarted.Value, DateTimeKind.Utc);
                var dateValue = ((DateTimeOffset)specifiedDateTime).ToUnixTimeSeconds();

                description.AppendLine();
                description.AppendLine($"Streak started <t:{dateValue}:R>.");
            }

            if (description.Length > 0)
            {
                return description.ToString();
            }

            return "No active streak found.";
        }

19 Source : LastFmRepository.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<Response<TopAlbumList>> GetTopAlbumsForCustomTimePeriodAsyncAsync(string lastFmUserName,
            DateTime startDateTime, DateTime endDateTime, int count)
        {
            var start = ((DateTimeOffset)startDateTime).ToUnixTimeSeconds();
            var end = ((DateTimeOffset)endDateTime).ToUnixTimeSeconds();
            var queryParams = new Dictionary<string, string>
            {
                {"username", lastFmUserName },
                {"limit", count.ToString() },
                {"from", start.ToString() },
                {"to", end.ToString() },
            };

            var artistCall = await this._lastFmApi.CallApiAsync<WeeklyAlbumChartsResponse>(queryParams, Call.GetWeeklyAlbumChart);
            if (artistCall.Success)
            {
                return new Response<TopAlbumList>
                {
                    Success = true,
                    Content = new TopAlbumList
                    {
                        TopAlbums = artistCall.Content.WeeklyAlbumChart.Album.Select(s => new TopAlbum
                        {
                            ArtistName = s.Artist.Text,
                            AlbumName = s.Name,
                            Mbid = !string.IsNullOrWhiteSpace(s.Mbid)
                                ? Guid.Parse(s.Mbid)
                                : null,
                            AlbumUrl = s.Url,
                            UserPlaycount = s.Playcount
                        }).ToList()
                    }
                };
            }

            return new Response<TopAlbumList>
            {
                Success = false,
                Error = artistCall.Error,
                Message = artistCall.Message
            };
        }

19 Source : LastFmRepository.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<Response<TopArtistList>> GetTopArtistsForCustomTimePeriodAsync(string lastFmUserName,
            DateTime startDateTime, DateTime endDateTime, int count)
        {
            var start = ((DateTimeOffset)startDateTime).ToUnixTimeSeconds();
            var end = ((DateTimeOffset)endDateTime).ToUnixTimeSeconds();

            var queryParams = new Dictionary<string, string>
            {
                {"username", lastFmUserName },
                {"limit", count.ToString() },
                {"from", start.ToString() },
                {"to", end.ToString() },
            };

            var artistCall = await this._lastFmApi.CallApiAsync<WeeklyArtistChartsResponse>(queryParams, Call.GetWeeklyArtistChart);
            if (artistCall.Success)
            {
                return new Response<TopArtistList>
                {
                    Success = true,
                    Content = new TopArtistList
                    {
                        TopArtists = artistCall.Content.WeeklyArtistChart.Artist.Select(s => new TopArtist
                        {
                            ArtistUrl = s.Url,
                            ArtistName = s.Name,
                            Mbid = !string.IsNullOrWhiteSpace(s.Mbid)
                                ? Guid.Parse(s.Mbid)
                                : null,
                            ArtistImageUrl = Uri.IsWellFormedUriString(s.Url, UriKind.Absolute)
                                ? s.Url
                                : null,
                            UserPlaycount = s.Playcount
                        }).ToList()
                    }
                };
            }

            return new Response<TopArtistList>
            {
                Success = false,
                Error = artistCall.Error,
                Message = artistCall.Message
            };
        }

19 Source : LastFmRepository.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<Response<TopTrackList>> GetTopTracksForCustomTimePeriodAsyncAsync(string lastFmUserName,
            DateTime startDateTime, DateTime endDateTime, int count)
        {
            var start = ((DateTimeOffset)startDateTime).ToUnixTimeSeconds();
            var end = ((DateTimeOffset)endDateTime).ToUnixTimeSeconds();
            var queryParams = new Dictionary<string, string>
            {
                {"username", lastFmUserName },
                {"limit", count.ToString() },
                {"from", start.ToString() },
                {"to", end.ToString() },
            };

            var artistCall = await this._lastFmApi.CallApiAsync<WeeklyTrackChartsResponse>(queryParams, Call.GetWeeklyTrackChart);
            if (artistCall.Success)
            {
                return new Response<TopTrackList>
                {
                    Success = true,
                    Content = new TopTrackList
                    {
                        TopTracks = artistCall.Content.WeeklyTrackChart.Track.Select(s => new TopTrack
                        {
                            ArtistUrl = s.Url,
                            ArtistName = s.Artist.Text,
                            TrackName = s.Name,
                            Mbid = !string.IsNullOrWhiteSpace(s.Mbid)
                                ? Guid.Parse(s.Mbid)
                                : null,
                            TrackUrl = Uri.IsWellFormedUriString(s.Url, UriKind.Absolute)
                                ? s.Url
                                : null,
                            UserPlaycount = s.Playcount
                        }).ToList()
                    }
                };
            }

            return new Response<TopTrackList>
            {
                Success = false,
                Error = artistCall.Error,
                Message = artistCall.Message
            };
        }

19 Source : LastFmRepository.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<Response<ScrobbledTrack>> SetNowPlayingAsync(User user, string artistName, string trackName, string albumName = null)
        {
            var queryParams = new Dictionary<string, string>
            {
                {"artist", artistName},
                {"track", trackName},
                {"sk", user.SessionKeyLastFm},
                {"timestamp",  ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds().ToString() }
            };

            if (!string.IsNullOrWhiteSpace(albumName))
            {
                queryParams.Add("album", albumName);
            }

            var authSessionCall = await this._lastFmApi.CallApiAsync<ScrobbledTrack>(queryParams, Call.TrackUpdateNowPlaying, true);

            return authSessionCall;
        }

19 Source : LastFmRepository.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<Response<ScrobbledTrack>> ScrobbleAsync(User user, string artistName, string trackName, string albumName = null)
        {
            var queryParams = new Dictionary<string, string>
            {
                {"artist", artistName},
                {"track", trackName},
                {"sk", user.SessionKeyLastFm},
                {"timestamp",  ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds().ToString() }
            };

            if (!string.IsNullOrWhiteSpace(albumName))
            {
                queryParams.Add("album", albumName);
            }

            var authSessionCall = await this._lastFmApi.CallApiAsync<ScrobbledTrack>(queryParams, Call.TrackScrobble, true);

            return authSessionCall;
        }

19 Source : UpdateRepository.cs
with GNU General Public License v3.0
from fmbot-discord

public async Task<Response<RecentTrackList>> UpdateUser(UpdateUserQueueItem queueItem)
        {
            Thread.Sleep(queueItem.TimeoutMs);

            await using var db = this._contextFactory.CreateDbContext();
            var user = await db.Users.FindAsync(queueItem.UserId);

            Log.Information("Update: Started on {userId} | {userNameLastFm}", user.UserId, user.UserNameLastFM);

            string sessionKey = null;
            if (!string.IsNullOrEmpty(user.SessionKeyLastFm))
            {
                sessionKey = user.SessionKeyLastFm;
            }

            var lastStoredPlay = await GetLastStoredPlay(user);

            var dateAgo = lastStoredPlay?.TimePlayed.AddMinutes(-10) ?? DateTime.UtcNow.AddDays(-14);
            var timeFrom = (long?)((DateTimeOffset)dateAgo).ToUnixTimeSeconds();

            var count = 900;
            var totalPlaycountCorrect = false;
            var now = DateTime.UtcNow;
            if (dateAgo > now.AddHours(-1) && dateAgo < now.AddMinutes(-30))
            {
                count = 60;
                timeFrom = null;
                totalPlaycountCorrect = true;
            }
            else if (dateAgo > now.AddHours(-2) && dateAgo < now.AddMinutes(-30))
            {
                count = 120;
                timeFrom = null;
                totalPlaycountCorrect = true;
            }
            else if (dateAgo > now.AddHours(-12) && dateAgo < now.AddMinutes(-30))
            {
                count = 500;
                timeFrom = null;
                totalPlaycountCorrect = true;
            }

            var recentTracks = await this._lastFmRepository.GetRecentTracksAsync(
                user.UserNameLastFM,
                count,
                true,
                sessionKey,
                timeFrom);

            if (!recentTracks.Success)
            {
                Log.Information("Update: Something went wrong getting tracks for {userId} | {userNameLastFm} | {responseStatus}", user.UserId, user.UserNameLastFM, recentTracks.Error);

                if (recentTracks.Error == ResponseStatus.MissingParameters)
                {
                    await AddOrUpdateInactiveUserMissingParameterError(user);
                }
                if (recentTracks.Error == ResponseStatus.LoginRequired)
                {
                    await AddOrUpdatePrivateUserMissingParameterError(user);
                }

                recentTracks.Content = new RecentTrackList
                {
                    NewRecentTracksAmount = 0
                };
                return recentTracks;
            }

            await RemoveInactiveUserIfExists(user);

            await using var connection = new NpgsqlConnection(this._connectionString);
            await connection.OpenAsync();

            if (!recentTracks.Content.RecentTracks.Any())
            {
                Log.Information("Update: No new tracks for {userId} | {userNameLastFm}", user.UserId, user.UserNameLastFM);
                await SetUserUpdateTime(user, DateTime.UtcNow, connection);

                recentTracks.Content.NewRecentTracksAmount = 0;
                return recentTracks;
            }

            AddRecentPlayToMemoryCache(user.UserId, recentTracks.Content.RecentTracks.First());

            var newScrobbles = recentTracks.Content.RecentTracks
                .Where(w => !w.NowPlaying &&
                            w.TimePlayed != null &&
                            (lastStoredPlay?.TimePlayed == null || w.TimePlayed > lastStoredPlay.TimePlayed))
                .ToList();

            if (!newScrobbles.Any())
            {
                Log.Information("Update: After local filter no new tracks for {userId} | {userNameLastFm}", user.UserId, user.UserNameLastFM);
                await SetUserUpdateTime(user, DateTime.UtcNow, connection);

                if (!user.TotalPlaycount.HasValue)
                {
                    recentTracks.Content.TotalAmount = await SetOrUpdateUserPlaycount(user, newScrobbles.Count, connection, totalPlaycountCorrect ? recentTracks.Content.TotalAmount : null);
                }
                else if (totalPlaycountCorrect)
                {
                    await SetOrUpdateUserPlaycount(user, newScrobbles.Count, connection, recentTracks.Content.TotalAmount);
                }
                else
                {
                    recentTracks.Content.TotalAmount = user.TotalPlaycount.Value;
                }
                recentTracks.Content.NewRecentTracksAmount = 0;
                return recentTracks;
            }

            await CacheArtistAliases();

            try
            {
                var cacheKey = $"{user.UserId}-update-in-progress";
                if (this._cache.TryGetValue(cacheKey, out bool _))
                {
                    return recentTracks;
                }

                this._cache.Set(cacheKey, true, TimeSpan.FromSeconds(1));

                recentTracks.Content.TotalAmount = await SetOrUpdateUserPlaycount(user, newScrobbles.Count, connection, totalPlaycountCorrect ? recentTracks.Content.TotalAmount : null);

                await UpdatePlaysForUser(user, newScrobbles, connection);

                var userArtists = await GetUserArtists(user.UserId, connection);
                var userAlbums = await GetUserAlbums(user.UserId, connection);
                var userTracks = await GetUserTracks(user.UserId, connection);

                await UpdateArtistsForUser(user, newScrobbles, connection, userArtists);
                await UpdateAlbumsForUser(user, newScrobbles, connection, userAlbums);
                await UpdateTracksForUser(user, newScrobbles, connection, userTracks);

                var lastNewScrobble = newScrobbles.OrderByDescending(o => o.TimePlayed).FirstOrDefault();
                if (lastNewScrobble?.TimePlayed != null)
                {
                    await SetUserLastScrobbleTime(user, lastNewScrobble.TimePlayed.Value, connection);
                }

                await SetUserUpdateTime(user, DateTime.UtcNow, connection);

                this._cache.Remove($"user-{user.UserId}-topartists-alltime");
            }
            catch (Exception e)
            {
                Log.Error(e, "Update: Error in update process for user {userId} | {userNameLastFm}", user.UserId, user.UserNameLastFM);
            }

            Statistics.UpdatedUsers.Inc();

            await connection.CloseAsync();

            recentTracks.Content.NewRecentTracksAmount = newScrobbles.Count;
            return recentTracks;
        }

19 Source : ExposureKeyMapper.cs
with MIT License
from folkehelseinstituttet

public Domain.Proto.TemporaryExposureKeyExport FromEnreplacedyToProtoBatch(IList<TemporaryExposureKey> dtoKeys)
        {
            var keysByTime = dtoKeys.OrderBy(k => k.CreatedOn);
            var startTimes = new DateTimeOffset(keysByTime.First().CreatedOn);
            var endTimes = new DateTimeOffset(keysByTime.Last().CreatedOn);
            var batch = new Domain.Proto.TemporaryExposureKeyExport
            {
                BatchNum = 1,
                BatchSize = 1,
                StartTimestamp = (ulong)(startTimes.ToUnixTimeSeconds()),
                EndTimestamp = (ulong)(endTimes.ToUnixTimeSeconds()),
                Region = "NO"
            };
            batch.Keys.AddRange(dtoKeys.Select(x => FromEnreplacedyToProto(x)).ToList());

            return batch;
        }

19 Source : ExposureKeyMapperTests.cs
with MIT License
from folkehelseinstituttet

[Test]
        public void FromEnreplacedyToProtoBatch_GiveEnreplacedyList_ShouldReturnCorrectProtoBatchModel()
        {
            int listCount = 3;
            var keys = CreateMockedListExposureKeys(listCount);
            var keysByTime = keys.OrderBy(k => k.CreatedOn);
            var startTimes = new DateTimeOffset(keysByTime.First().CreatedOn);
            var endTimes = new DateTimeOffset(keysByTime.Last().CreatedOn);

            var mapper = new ExposureKeyMapper(_epochConverter);
            var protoBatch = mapper.FromEnreplacedyToProtoBatch(keys);

            replacedert.AreEqual(listCount, protoBatch.Keys.Count);
            replacedert.AreEqual(protoBatch.BatchNum, 1);
            replacedert.AreEqual(protoBatch.BatchSize, 1);
            replacedert.AreEqual(protoBatch.StartTimestamp, startTimes.ToUnixTimeSeconds());
            replacedert.AreEqual(protoBatch.EndTimestamp, endTimes.ToUnixTimeSeconds());
            replacedert.AreEqual(protoBatch.Region, "NO");
            replacedert.IsInstanceOf<Domain.Proto.TemporaryExposureKeyExport>(protoBatch);
        }

19 Source : AnonymousTokenKeyStore.cs
with MIT License
from folkehelseinstituttet

private long ToIntervalNumber(DateTimeOffset pointInTime)
        {
            return pointInTime.ToUnixTimeSeconds() / Convert.ToInt64(_config.KeyRotationInterval.TotalSeconds);
        }

19 Source : AnonymousTokensControllerTests.cs
with MIT License
from folkehelseinstituttet

[Test]
        public async Task IssueNewToken_RequiredClaimsPresentAndIssueOk_ReturnsAnonymousTokenResponse()
        {
            //Arrange
            var tokenId = Guid.NewGuid();
            var request = new AnonymousTokenRequest();
            var response = new AnonymousTokenResponse();
            var user = new ClaimsPrincipal(new ClaimsIdenreplacedy(new[]
            {
                new Claim(JwtClaimTypes.JwtId, tokenId.ToString()),
                new Claim(JwtClaimTypes.Expiration, DateTimeOffset.Now.ToUnixTimeSeconds().ToString())
            }));

            var automocker = new AutoMocker();
            automocker.Setup<IMediator, Task<Option<AnonymousTokenResponse, string>>>(x => x.Send(
                It.IsAny<IssueAnonymousToken.Command>(),
                It.IsAny<CancellationToken>()))
                .ReturnsAsync(response.Some<AnonymousTokenResponse, string>());

            var target = automocker.CreateInstance<AnonymousTokensController>().SetUserForContext(user);

            //Act
            var result = await target.IssueNewToken(request);

            result.Value.Should().Be(response);
        }

19 Source : AnonymousTokensControllerTests.cs
with MIT License
from folkehelseinstituttet

[Test]
        public async Task IssueNewToken_RequiredClaimsPresentAndIssueRejected_ReturnsConflictResponse()
        {
            //Arrange
            var tokenId = Guid.NewGuid();
            var request = new AnonymousTokenRequest();
            var user = new ClaimsPrincipal(new ClaimsIdenreplacedy(new[]
            {
                new Claim(JwtClaimTypes.JwtId, tokenId.ToString()),
                new Claim(JwtClaimTypes.Expiration, DateTimeOffset.Now.ToUnixTimeSeconds().ToString())
            }));

            var automocker = new AutoMocker();
            automocker.Setup<IMediator, Task<Option<AnonymousTokenResponse, string>>>(x => x.Send(
                    It.IsAny<IssueAnonymousToken.Command>(),
                    It.IsAny<CancellationToken>()))
                .ReturnsAsync(Option.None<AnonymousTokenResponse, string>("Rejected."));

            var target = automocker.CreateInstance<AnonymousTokensController>().SetUserForContext(user);

            //Act
            var result = await target.IssueNewToken(request);

            result.Result.Should().BeOfType<ConflictObjectResult>();
        }

See More Examples