예제 #1
0
        public GroupsHistoryResponseModel GetChannelHistory(string slackApiToken, string channel, DateTime startTime, DateTime endTime, int count)
        {
            var responseString = "https://slack.com/api/channels.history"
                .PostUrlEncodedAsync(
                    new
                    {
                        token = slackApiToken,
                        channel,
                        latest = endTime.ToUnixTime(),
                        oldest = startTime.ToUnixTime(),
                        count
                    })
                .ReceiveString()
                .Result;

            var serializer = new JsonSerializer<GroupsHistoryResponseModel>();
            var response = serializer.DeserializeFromString(responseString);

            if (!response.ok)
            {
                throw new SlackApiException(response.error);
            }

            return response;
        }
        /// <summary>
        /// Gets a secure signed url for downloading through Amazon CloudFront
        /// </summary>
        /// <param name="resourceUrl">URL to the resource</param>
        /// <param name="expires">Expiry date for the download link</param>
        /// <param name="keyXml">Private key XML (Use OpenSSLKey to convert from pem format)</param>
        /// <param name="keypairId">Key Pair Id of the key from AWS Security Credentials page</param>
        /// <returns></returns>
        public static string GetSecureUrl(string resourceUrl, DateTime expires, string keyXml, string keypairId)
        {
            if (string.IsNullOrEmpty(resourceUrl))
            {
                throw new ArgumentNullException("resourceUrl");
            }

            if (string.IsNullOrEmpty(keyXml))
            {
                throw new ArgumentNullException("keyXml");
            }

            if (string.IsNullOrEmpty(keypairId))
            {
                throw new ArgumentNullException("keypairId");
            }

            if (expires < DateTime.Now)
            {
                throw new ArgumentException("Expiry date cannot be before current time.");
            }

            var unixExpiry = expires.ToUnixTime();
            var policy = BuildCannedPolicy(resourceUrl, unixExpiry);
            var rsa = GetRsaProvider(keyXml);
            var rsaSignature = rsa.SignData(Encoding.UTF8.GetBytes(policy), new SHA1CryptoServiceProvider());
            var signature = EncodeSignature(rsaSignature);

            return string.Format(
                            "{0}?Expires={1}&Signature={2}&Key-Pair-Id={3}",
                            resourceUrl,
                            unixExpiry,
                            signature,
                            keypairId);
        }
        /// <summary>
        /// Gets all authorization codes that matches the specified redirect uri and expires after the
        /// specified date. Called when authenticating an authorization code.
        /// </summary>
        /// <param name="redirectUri">The redirect uri.</param>
        /// <param name="expires">The expire date.</param>
        /// <returns>The authorization codes.</returns>
        public async Task<IEnumerable<IAuthorizationCode>> GetAuthorizationCodes(string redirectUri, DateTime expires)
        {
            var db = this.GetDatabase();

            var min = expires.ToUnixTime();
            var codes = new List<IAuthorizationCode>();

            var keys = db.SortedSetRangeByScore(this.Configuration.AuthorizationCodePrefix, min, DateTimeMax);

            foreach (var key in keys)
            {
                var hashedId = key.ToString().Substring(this.Configuration.AuthorizationCodePrefix.Length + 1);
                var id = Encoding.UTF8.GetString(Convert.FromBase64String(hashedId));

                if (id.Contains(redirectUri))
                {
                    var hashEntries = await db.HashGetAllAsync(key.ToString());

                    if (hashEntries.Any())
                    {
                        var code = new RedisAuthorizationCode(hashEntries) { Id = hashedId };

                        codes.Add(code);
                    }
                }
            }

            return codes;
        }
예제 #4
0
        public UserExtended GetCurrentChanged(DateTime since)
        {
            var url = string.Format(ApiRoutes.User.CurrentSinceUrl, since.ToUnixTime());

            var obj = ToggleSrv.Get(url).GetData<UserExtended>();

            return obj;
        }
		public void ToUnixTimeTest()
		{

			DateTime dt = new DateTime(1970, 1, 1);
			var unixTime = dt.ToUnixTime();
			Assert.AreEqual(unixTime, (long)0);


		}
예제 #6
0
        public async System.Threading.Tasks.Task<UserExtended> GetCurrentChanged(DateTime since)
        {
            var url = string.Format(ApiRoutes.User.CurrentSinceUrl, since.ToUnixTime());

            var response = await ToggleSrv.Get(url);
            var obj = response.GetData<UserExtended>();

            return obj;
        }
예제 #7
0
파일: DateTimeTests.cs 프로젝트: nikeee/nth
        public void ToUnixTime()
        {
            /*
             "The Unix epoch is the time 00:00:00 UTC on 1 January 1970 (or 1970-01-01T00:00:00Z ISO 8601)."
             * See:
             * https://en.wikipedia.org/wiki/Unix_time#Encoding_time_as_a_number
             */
            var unixStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            long expected = 0;
            var actual = unixStart.ToUnixTime();
            Assert.AreEqual(expected, actual);

            // First second
            var test1 = new DateTime(1970, 1, 1, 0, 0, 1, DateTimeKind.Utc);
            expected = 1;
            actual = test1.ToUnixTime();
            Assert.AreEqual(expected, actual);

            // -1
            var test11 = new DateTime(1969, 12, 31, 23, 59, 59, DateTimeKind.Utc);
            expected = -1;
            actual = test11.ToUnixTime();
            Assert.AreEqual(expected, actual);

            /*
             * "At 01:46:40 UTC on 9 September 2001, the Unix billennium (Unix time number 1,000,000,000) was celebrated."
             */
            var test2 = new DateTime(2001, 9, 9, 1, 46, 40, DateTimeKind.Utc);
            expected = 1000000000;
            actual = test2.ToUnixTime();
            Assert.AreEqual(expected, actual);

            /*
             * "At 23:31:30 UTC on 13 February 2009, the decimal representation of Unix time reached 1,234,567,890 seconds (like the number row on a keyboard)."
             */
            var test3 = new DateTime(2009, 2, 13, 23, 31, 30, DateTimeKind.Utc);
            expected = 1234567890;
            actual = test3.ToUnixTime();
            Assert.AreEqual(expected, actual);

            /*
             * "At 06:28:15 UTC on Sun, 7 February 2106, the Unix time will reach 0xFFFFFFFF or 4,294,967,295 seconds which, for systems that hold the time on 32 bit unsigned numbers, is the maximum attainable"
             */
            var test4 = new DateTime(2106, 2, 7, 06, 28, 15, DateTimeKind.Utc);
            expected = 0xFFFFFFFF;
            actual = test4.ToUnixTime();
            Assert.AreEqual(expected, actual);

            /*
             * "At 16:53:20 UTC on 13 May 2014, the Unix time value 1,400,000,000 seconds was celebrated over the Web"
             */
            var test5 = new DateTime(2014, 5, 13, 16, 53, 20, DateTimeKind.Utc);
            expected = 1400000000;
            actual = test5.ToUnixTime();
            Assert.AreEqual(expected, actual);
        }
예제 #8
0
        public string CreateSignature(long userId, long appId, string appSecret, DateTime now)
        {
            var bytes = BitConverter.GetBytes(userId)
                .Concat(BitConverter.GetBytes(appId))
                .Concat(BitConverter.GetBytes(now.ToUnixTime()))
                .Concat(Encoding.UTF8.GetBytes(appSecret))
                .ToArray();

            return _hashAlgorithm.ComputeHash(bytes).ToHexString().ToLower();
        }
예제 #9
0
        public void Serialize_UTC_Date()
        {
            var d = new DateTime(2001, 01, 01);

            d.ToJson().Print();
            "\"\\/Date(978325200000-0000)\\/\"".Print();
            d.ToUnixTime().ToString().Print();
            d.ToUnixTimeMs().ToString().Print();

            Assert.That(d.ToJson(), Is.EqualTo("\"\\/Date(978325200000-0000)\\/\""));
        }
예제 #10
0
		public PlaintextMessage(string path, int value, DateTime timestamp)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}

			Path = path;
			Value = value;
			Timestamp = timestamp.ToUnixTime();
		}
        public void ToUnixTime_ThenCorrectUnixTimeReturned()
        {
            // arrange
            const Int64 Expected = 1396137600;
            DateTime dateTime = new DateTime(2014, 03, 30, 0, 0, 0, 0);

            // act
            Int64 unixTime = dateTime.ToUnixTime();

            // assert
            unixTime.ShouldBeEquivalentTo(Expected);
        }
예제 #12
0
        public IEnumerable<ScheduledGame> GetScheduledLeagueGames(DateTime dateMin = default(DateTime), DateTime dateMax = default(DateTime))
        {
            var request = new RestRequest(RequestPaths.Dota2.League.ScheduledLeagueGames);

            var defaultDateTime = default(DateTime);
            if (dateMin != defaultDateTime)
                request.AddQueryParameter("date_min", dateMin.ToUnixTime());
            if (dateMax != defaultDateTime)
                request.AddQueryParameter("date_max", dateMax.ToUnixTime());

            var response = Execute<ScheduledLeagueGamesResponseWrapper>(request);
            return Mapper.Map<List<ScheduledGame>>(response.Games);
        }
예제 #13
0
        public void DateTimeToUnixTime_Works()
        {
            // UTC time
            var utcDateTime = new DateTime(2013, 9, 26, 22, 21, 11, DateTimeKind.Utc);
            Assert.That(utcDateTime.ToUnixTime(), Is.EqualTo(1380234071L));

            // Local time
            var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, TimeZoneInfo.Local);
            Assert.That(localDateTime.ToUnixTime(), Is.EqualTo(1380234071L));

            // Min value
            Assert.That(DateTime.MinValue.ToUnixTime(), Is.EqualTo(-62135596800L));
        }
예제 #14
0
 public static DynamicProfileBadge CreateFromCommentCount(string userName, int commentCount, DateTime newestCommentTime)
 {
     if (string.IsNullOrWhiteSpace(userName))
         throw new ArgumentNullException(nameof(userName));
     foreach (var ccn in CommentCountNames.OrderByDescending(kvp => kvp.Key))
     {
         if (commentCount > ccn.Key)
         {
             var template = BadgeTemplates[DynamicBadgeType.Comments];
             var description = string.Format(template.Description ?? string.Empty, ccn.Key);
             var link = $"{ClientConstants.UserUrlPrefix}/{userName}/comments/before/{newestCommentTime.ToUnixTime()}";
             return new DynamicProfileBadge(template.Image, description, link, newestCommentTime, template.Name, ccn.Value);
         }
     }
     return null;
 }
예제 #15
0
        public Event[] GetInRange(DateTime from, DateTime to, int[] hostids, TypeOfEvent typeOfEvent = TypeOfEvent.Trigger, TypeOfObjectRelatedEvent relatedEvent = TypeOfObjectRelatedEvent.Trigger)
        {
            if (from == null || to == null)
                throw new ArgumentNullException();

            var response = _event.Get(new Get
            {
                time_from = from.ToUnixTime(),
                time_till = to.ToUnixTime(),
                @object = relatedEvent,
                source = typeOfEvent,
                sortfield = new []{"eventid"},
                output = "extend",
                sortorder = new[] { "desc" }
            });
            return response;
        }
예제 #16
0
        public HistoryBase[] GetHistoryInRange(DateTime from, DateTime to)
        {
            if (from == null || to == null)
                throw new ArgumentNullException();

            if (from.Kind != DateTimeKind.Utc)
                from = from.ToUniversalTime();

            if (to.Kind != DateTimeKind.Utc)
                to = to.ToUniversalTime();

            var response = _provider.Get(new Get
            {
                time_from = from.ToUnixTime(),
                time_till = to.ToUnixTime(),
            });
            return response;
        }
예제 #17
0
        public Trend[] GetInRange(DateTime from, DateTime to, TrendType trendType = TrendType.Float)
        {
            if (from == null || to == null)
                throw new ArgumentNullException();

            if (from.Kind != DateTimeKind.Utc)
                from = from.ToUniversalTime();

            if (to.Kind != DateTimeKind.Utc)
                to = to.ToUniversalTime();

            var response = _provider.Get(new Get
                {
                    time_from = from.ToUnixTime(),
                    time_till = to.ToUnixTime(),
                    history = trendType
                });
            return response;
        }
예제 #18
0
        /// <summary>
        /// Gets a secure signed url for downloading from an S3 bucket
        /// </summary>
        /// <param name="bucketName">Name of the S3 bucket</param>
        /// <param name="fileKey">Filename / key</param>
        /// <param name="expires">Expiry date for the link</param>
        /// <param name="accessKeyId">AWS Access Key Id</param>
        /// <param name="secretAccessKey">AWS Secret Access key</param>
        /// <returns></returns>
        public static string GetSecureUrl(string bucketName, string fileKey, DateTime expires, string accessKeyId,
            string secretAccessKey)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentNullException("bucketName");
            }

            if (string.IsNullOrEmpty(fileKey))
            {
                throw new ArgumentNullException("fileKey");
            }

            if (string.IsNullOrEmpty(accessKeyId))
            {
                throw new ArgumentNullException("accessKeyId");
            }

            if (string.IsNullOrEmpty(secretAccessKey))
            {
                throw new ArgumentNullException("secretAccessKey");
            }

            if (expires < DateTime.Now)
            {
                throw new ArgumentException("Expiry date cannot be before current time.");
            }

            double unixExpiry = expires.ToUnixTime();
            string stringToSign = BuildStringToSign(bucketName, fileKey, unixExpiry);
            var hmacGenerator = new HMACSHA1(Encoding.UTF8.GetBytes(secretAccessKey));
            byte[] hash = hmacGenerator.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            string signature = EncodeSignature(hash);

            return string.Format(
                "http://{0}.s3.amazonaws.com/{1}?AWSAccessKeyId={2}&Expires={3}&Signature={4}",
                bucketName,
                fileKey,
                accessKeyId,
                unixExpiry,
                signature);
        }
예제 #19
0
 /// <summary>
 /// Encodes a timestamp.
 /// </summary>
 /// <returns></returns>
 public static int EncodeTimestamp(DateTime timestamp, long dateGranularity)
 {
     return (int)(timestamp.ToUnixTime() / dateGranularity);
 }
예제 #20
0
 public HistoryBase[] GetHistoryByItemIdsInRange(string[] itemids, DateTime from, DateTime to)
 {
     return GetHistoryByItemIdsInRange(itemids, from.ToUnixTime(), to.ToUnixTime());
 }
예제 #21
0
        /// <summary>
        /// Generates a timestamp based on the elapsed seconds of a given time since '01/01/1970 0000 GMT"
        /// </summary>
        /// <seealso cref="http://oauth.net/core/1.0#nonce"/>
        /// <param name="dateTime">A specified point in time.</param>
        /// <returns></returns>
        public static string GetTimestamp(DateTime dateTime)
        {
            long timestamp = dateTime.ToUnixTime();

            return timestamp.ToString();
        }
예제 #22
0
		/// <summary>
		/// This will find all modified videos
		/// </summary>
		/// <param name="from_date">The date, specified in minutes since January 1st, 1970 00:00:00 GMT, of the oldest Video which you would like returned.</param>
		/// <param name="howMany">Number of items returned per page. A page is a subset of all of the items that satisfy the request. The maximum page size is 25; if you do not set this argument, or if you set it to an integer > 25, your results will come back as if you had set page_size=25.</param>
		/// <param name="sortBy">The field by which to sort the results. A SortByType: One of PUBLISH_DATE, CREATION_DATE, MODIFIED_DATE, PLAYS_TOTAL, PLAYS_TRAILING_WEEK.</param>
		/// <param name="sortOrder">How to order the results: ascending (ASC) or descending (DESC).</param>
		/// <param name="video_fields">A comma-separated list of the fields you wish to have populated in the videos contained in the returned object. If you omit this parameter, the method returns the following fields of the video: id, name, shortDescription, longDescription, creationDate, publisheddate, lastModifiedDate, linkURL, linkText, tags, videoStillURL, thumbnailURL, referenceId, length, economics, playsTotal, playsTrailingWeek. If you use a token with URL access, this method also returns FLVURL, renditions, FLVFullLength, videoFullLength.</param>
		/// <param name="custom_fields">A comma-separated list of the custom fields you wish to have populated in the videos contained in the returned object. If you omit this parameter, no custom fields are returned, unless you include the value 'customFields' in the video_fields parameter.</param>
		/// <param name="filter">A comma-separated list of filters, specifying which categories of videos you would like returned. Valid filter values are PLAYABLE, UNSCHEDULED, INACTIVE, and DELETED.</param>
		/// <param name="media_delivery">If universal delivery service is enabled for your account, set this optional parameter to http to return video by HTTP, rather than streaming. Meaningful only if used together with the video_fields=FLVURL, videoFullLength, or renditions parameters. This is a MediaDeliveryTypeEnum with a value of http or default.</param>
		/// <returns>Returns a BCQueryResult Item</returns>
		public BCQueryResult FindModifiedVideos(DateTime from_date, int howMany, BCSortByType sortBy, BCSortOrderType sortOrder, List<VideoFields> video_fields, List<string> custom_fields, List<string> filter, MediaDeliveryTypeEnum media_delivery) {

			Dictionary<String, String> reqparams = new Dictionary<string, string>();

			//Build the REST parameter list
			reqparams.Add("command", "find_modified_videos");
			if (from_date != null) reqparams.Add("from_date", from_date.ToUnixTime());
			if (video_fields != null) reqparams.Add("video_fields", video_fields.ToFieldString());
			if (custom_fields != null) reqparams.Add("custom_fields", Implode(custom_fields));
			if (filter != null) reqparams.Add("filter", Implode(filter));
			reqparams.Add("sort_order", sortOrder.ToString());
			reqparams.Add("sort_by", sortBy.ToString());
			reqparams.Add("media_delivery", media_delivery.ToString());
			if (howMany >= 0) reqparams.Add("page_size", howMany.ToString());

			return MultipleQueryHandler(reqparams, BCObjectType.videos, Account);
		}
예제 #23
0
        public void TestUnixTime()
        {
            DateTime time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
                DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);

            long unixTime = time.ToUnixTime();
            DateTime timeAfter = unixTime.FromUnixTime();

            Assert.AreEqual(time, timeAfter);

            unixTime = 1374842318000;
            time = unixTime.FromUnixTime();
            long unixTimeAfter = time.ToUnixTime();

            Assert.AreEqual(unixTime, unixTimeAfter);
        }
 internal NormalizedTimestamp(DateTime utcNow, Credential credential, int localOffset = 0) :
     this(utcNow.ToUnixTime(), credential, localOffset) { }
예제 #25
0
 public Trend[] GetInRange(int[] itemids, DateTime from, DateTime to, TrendType trendType = TrendType.Float)
 {
     if (from == null || to == null)
         throw new ArgumentNullException();
     return GetInRange(itemids, from.ToUnixTime(), to.ToUnixTime(), trendType);
 }
 public static ISignatureBuilder Append(this ISignatureBuilder signatureBuilder, DateTime value)
 {
     return signatureBuilder.Append(BitConverter.GetBytes(value.ToUnixTime()));
 }
        /// <summary>
        /// Generates a new one time password from the supplied data.
        /// </summary>
        /// <param name="secretKey">The secret key to use in the HMAC</param>
        /// <param name="hmac">The hmac algorithm to use</param>
        /// <param name="dt">The date and time to generate a code for</param>
        /// <param name="offset">Any offsets that should be applied to the supplie date time</param>
        /// <param name="timeStep">The timestep value to use to calculate the current step</param>
        /// <param name="otpLength">The required legnth of the returned passcode</param>
        /// <returns>A one time password code</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if hmac or secret key is null</exception>
        /// <exception cref="System.ArgumentException">Thrown if secret key is empty, optLength is
        /// not defined value or timeStep is less than 1 second.</exception>
        public static string Generate(byte[] secretKey, HMAC hmac, DateTime dt, TimeSpan offset, TimeSpan timeStep, OneTimePasswordLength otpLength)
        {
            #region Input validation

            Insist.IsNotNull(hmac, "hmac");
            Insist.IsNotNull(secretKey, "secretKey");
            Insist.IsNotEmpty(secretKey, "secretKey");
            Insist.IsDefined<OneTimePasswordLength>(otpLength, "optLength");
            Insist.IsAtLeast(timeStep.TotalSeconds, 1, "timeStep");

            #endregion

            dt = dt + offset;

            ulong stepNumber = (ulong)Math.Floor((double)dt.ToUnixTime() / (double)timeStep.TotalSeconds);

            return HmacOneTimePassword.Generate(secretKey, stepNumber, hmac, otpLength);
        }
예제 #28
0
        /// <summary>Sends a log entry to the intel reporting server.</summary>
        /// <param name="channel">The channel were the intel was
        /// reported.</param>
        /// <param name="timestamp">The time and date the intel was
        /// reported.</param>
        /// <param name="message">The entire message entered into the
        /// log file (including the <var>username &gt; </var>).</param>
        /// <returns>
        /// <see langword="true" /> if our session is still valid;
        /// otherwise, <see langword="false" />.
        /// </returns>
        /// <exception cref="WebException">Failed to contact the web
        /// server.</exception>
        public virtual bool Report(string channel, DateTime timestamp, string message)
        {
            Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(channel));
            Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(message));
            Contract.Ensures(Contract.Result<bool>() == this.IsConnected);
            if (!this.IsConnected)
                return false;

            try {
                var request = WebRequest.Create(this.serviceUri);
                Contract.Assert(request != null);
                var response = request.Post(new Dictionary<string, string>() {
                    { "session", session },
                    { "inteltime", timestamp.ToUnixTime()
                        .ToString("F0", CultureInfo.InvariantCulture) },
                    { "action", "INTEL" },
                    { "region", channel },
                    // XXX: The \r is to make our report match the perl version EXACTLY
                    { "intel", message + '\r' }
                });
                var responseBody = response.ReadContent();

                Match match;
                if ((match = IntelResponse.Match(responseBody)).Success) {
                    // Successfully reported intel
                    ++this.ReportsSent;
                    this.serverErrors = 0;
                    return true;
                } else if ((match = ErrorResponse.Match(responseBody)).Success) {
                    if (match.Groups[1].Value == "502") {
                        // Our session has expired
                        this.OnClosed();
                        return false;
                    } else {
                        // The server responded with something unexpected
                        throw new WebException(Resources.IntelException,
                            WebExceptionStatus.ProtocolError);
                    }
                } else {
                    // The server responded with something unexpected
                    throw new WebException(Resources.IntelException,
                        WebExceptionStatus.ProtocolError);
                }
            } catch {
                this.OnError();
                throw;
            }
        }
예제 #29
0
 /// <summary>
 /// Create a new filter to select commits before a given date/time.
 /// </summary>
 /// <param name="ts">the point in time to cut on.</param>
 /// <returns>
 /// a new filter to select commits on or before <paramref name="ts"/>.
 /// </returns>
 public static RevFilter Before(DateTime ts)
 {
     return new BeforeCommitTimeRevFilter(ts.ToUnixTime() * 1000);
 }
예제 #30
0
 /// <summary>
 /// Create a new filter to select commits After a given date/time.
 /// </summary>
 /// <param name="ts">the point in time to cut on.</param>
 /// <returns>
 /// a new filter to select commits on or After <paramref name="ts"/>.
 /// </returns>
 public static RevFilter After(DateTime ts)
 {
     return new AfterCommitTimeRevFilter(ts.ToUnixTime() * 1000);
 }