ToInt64() public static method

public static ToInt64 ( DateTime value ) : long
value DateTime
return long
 private static void RegisterSingleConversions(
     ITypeConverterRegistry registry)
 {
     registry.Register <float, byte>(from => SysConv.ToByte(from));
     registry.Register <float, short>(from => SysConv.ToInt16(from));
     registry.Register <float, int>(from => SysConv.ToInt32(from));
     registry.Register <float, long>(from => SysConv.ToInt64(from));
     registry.Register <float, ushort>(from => SysConv.ToUInt16(from));
     registry.Register <float, uint>(from => SysConv.ToUInt32(from));
     registry.Register <float, ulong>(from => SysConv.ToUInt64(from));
     registry.Register <float, decimal>(from => SysConv.ToDecimal(from));
     registry.Register <float, double>(from => SysConv.ToDouble(from));
     registry.Register <float, string>(from =>
                                       from.ToString(CultureInfo.InvariantCulture));
 }
Beispiel #2
0
 private static void RegisterDoubleConversions(
     DefaultTypeConverter registry)
 {
     registry.Register <double, byte>(from => SysConv.ToByte(from));
     registry.Register <double, short>(from => SysConv.ToInt16(from));
     registry.Register <double, int>(from => SysConv.ToInt32(from));
     registry.Register <double, long>(from => SysConv.ToInt64(from));
     registry.Register <double, ushort>(from => SysConv.ToUInt16(from));
     registry.Register <double, uint>(from => SysConv.ToUInt32(from));
     registry.Register <double, ulong>(from => SysConv.ToUInt64(from));
     registry.Register <double, decimal>(from => SysConv.ToDecimal(from));
     registry.Register <double, float>(from => SysConv.ToSingle(from));
     registry.Register <double, string>(from =>
                                        from.ToString(CultureInfo.InvariantCulture));
 }
        /// <summary>
        /// OAuthで使用する共通情報を取得する
        /// </summary>
        /// <param name="token">アクセストークン、もしくはリクエストトークン。未取得なら空文字列</param>
        /// <returns>OAuth情報のディクショナリ</returns>
        protected Dictionary <string, string> GetOAuthParameter(string token)
        {
            Dictionary <string, string> parameter = new Dictionary <string, string>();

            parameter.Add("oauth_consumer_key", this.consumerKey);
            parameter.Add("oauth_signature_method", "HMAC-SHA1");
            parameter.Add("oauth_timestamp", Convert.ToInt64((DateTime.UtcNow - HttpConnectionOAuth.UnixEpoch).TotalSeconds).ToString());                   // epoch秒
            parameter.Add("oauth_nonce", HttpConnectionOAuth.NonceRandom.Next(123400, 9999999).ToString());
            parameter.Add("oauth_version", "1.0");
            if (!string.IsNullOrEmpty(token))
            {
                parameter.Add("oauth_token", token);                   // トークンがあれば追加
            }
            return(parameter);
        }
Beispiel #4
0
 private static object ConvertValue(string keyValue, string locale)
 {
     if (keyValue.StartsWith("I'"))
     {
         return(Convert.ToInt64(keyValue.Substring(2)));
     }
     if (keyValue.StartsWith("F'"))
     {
         return(Convert.ToDouble(keyValue.Substring(2)));
     }
     if (keyValue.StartsWith("D'"))
     {
         return(Convert.ToDateTime(keyValue.Substring(2), (locale == null ? CultureInfo.CurrentCulture : new CultureInfo(locale))));
     }
     return(keyValue.Replace("\\n", "\n").Replace("\\t", "\t"));
 }
Beispiel #5
0
        private async Task Client_MessageReactionAdded(DSharpPlus.EventArgs.MessageReactionAddEventArgs e)
        {
            var context = new DiscordContext();

            var message = await context.SankakuPost.FirstOrDefaultAsync(post => post.MessageId == Convert.ToInt64(e.Message.Id));

            if (message != null)
            {
                SankakuImageVote vote = null;

                vote = new SankakuImageVote()
                {
                    ImageId   = message.ImageId,
                    UserId    = Convert.ToInt64(e.User.Id),
                    VoteValue = 0
                };

                string discordName = e.Emoji.GetDiscordName();

                if (Config.Emojis.Confirms.Contains(discordName))
                {
                    vote.VoteValue = 1;
                }
                else if (Config.Emojis.Love.Contains(discordName))
                {
                    vote.VoteValue = 3;
                }
                else if (Config.Emojis.Declines.Contains(discordName))
                {
                    vote.VoteValue = -1;
                }
                else if (Config.Emojis.Hate.Contains(discordName))
                {
                    vote.VoteValue = -3;
                }

                if (vote.VoteValue != 0)
                {
                    await context.SankakuImageVote.AddAsync(vote);
                }

                await context.SaveChangesAsync();
            }
        }
Beispiel #6
0
        /// <summary>
        ///     将枚举转成字典
        /// </summary>
        /// <param name="enumType"></param>
        public static IList <KeyValue> EnumToKeyValues(Type enumType)
        {
            var objectCache = Ioc.Resolve <IObjectCache>();

            return(objectCache.GetOrSet(() => {
                IList <KeyValue> list = new List <KeyValue>();
                foreach (var item in Enum.GetValues(enumType))
                {
                    var value = item.GetDisplayName();
                    var icon = ((Enum)item).GetIcon();
                    var key = Convert.ToInt64(item);
                    var keyValueItem = new KeyValue(key, value, enumType.Name)
                    {
                        Icon = icon
                    };
                    list.Add(keyValueItem);
                }

                return list;
            }
                                        , "EnumToKeyValues_" + enumType.FullName).Value);
        }
Beispiel #7
0
        public async Task <(Entities.Sankaku.Image Information, byte[] Data)> GetImage(DiscordChannel channel, int skip = 0)
        {
            using var sankakuContext = new SankakuContext();

            var channelIDLong = Convert.ToInt64(channel.Id);

            var startDate = DateTime.Now - TimeSpan.FromDays(90);

            if (!_cachedImages.ContainsKey(channelIDLong))
            {
                Console.WriteLine($"Couldn't find cached Images for Channel {channelIDLong}");
                throw new Exception("Couldn't find cached Images for Channel.");
            }

            var images = _cachedImages[Convert.ToInt64(channelIDLong)];

            async Task RemoveImage(long image)
            {
                images.Remove(image);
                var sankakuImage = await sankakuContext.Image.FirstOrDefaultAsync();

                if (sankakuImage != null)
                {
                    sankakuImage.IsAvailableBool = false;
                    await sankakuContext.SaveChangesAsync();
                }
            }

            var hasImage = images.Where(cImg => !_postedImages.Contains(cImg)).Skip(skip).Any();

            if (hasImage == false)
            {
                await Console.Error.WriteLineAsync("Could not find a suitable Sankaku Image");

                throw new Exception("Could not find a suitable Sankaku Image.");
            }

            Uri imageUri = null;
            int attempt  = 0;

            Entities.Sankaku.Image imgToPost = null;

            while (imageUri == null && attempt < 10)
            {
                var imgToPostID = images.Where(cImg => !_postedImages.Contains(cImg)).Skip(skip).FirstOrDefault();

                if (imgToPostID == default)
                {
                    await Console.Error.WriteLineAsync("Could not find a suitable Sankaku Image in loop.");

                    throw new Exception("Could not find a suitable Sankaku Image in loop.");
                }

                imgToPost = await GetOriginalImage(imgToPostID);

                if (imgToPost == null || imgToPost.Status != Entities.Sankaku.Status.Active || imgToPost.FileUrl == null || imgToPost.FileSize > 8_000_000)
                {
                    if (imgToPost == null)
                    {
                        await Console.Error.WriteLineAsync($"Could not retrieve image with nr. {imgToPost.Id}");
                    }
                    else if (imgToPost.Status != Entities.Sankaku.Status.Active)
                    {
                        await Console.Error.WriteLineAsync($"Cannot send image with nr. {imgToPost.Id} because its Status is not \"Active\"");
                    }
                    else if (imgToPost.FileUrl == null)
                    {
                        await Console.Error.WriteLineAsync($"Cannot send image with nr. {imgToPost.Id} because its FileUrl is null");
                    }
                    else if (imgToPost.FileSize > 8_000_000)
                    {
                        await Console.Error.WriteLineAsync($"Cannot send image with nr. {imgToPost.Id} because it's too big");
                    }

                    await RemoveImage(imgToPost.Id);

                    await Task.Delay(100);
                }
                else
                {
                    imageUri = imgToPost.FileUrl;
                    break;
                }

                attempt++;
            }

            if (imageUri == null)
            {
                await Console.Error.WriteLineAsync($"Attempt {attempt} of retrieving sankaku Image has not succeeded.");

                throw new Exception($"Attempt {attempt} of retrieving sankaku Image has not succeeded.");
            }

            var link = HttpUtility.HtmlDecode(imageUri.AbsoluteUri);

            HttpResponseMessage response = null;

            try
            {
                response = await _httpClient.GetAsync(link);
            }
            catch (Exception)
            { }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                await Console.Error.WriteLineAsync($"Could not get Image Link for {imgToPost}").ConfigureAwait(false);
                await RemoveImage(imgToPost.Id);

                throw new Exception($"Could not get Image Link.");
            }

            return(imgToPost, await response.Content.ReadAsByteArrayAsync());
        }
Beispiel #8
0
        private async Task Client_MessageReactionRemoved(DSharpPlus.EventArgs.MessageReactionRemoveEventArgs e)
        {
            using var sankakuContext = new SankakuModel.SankakuContext();
            using var discordContext = new DiscordContext();

            var message = await discordContext.SankakuPost.FirstOrDefaultAsync(post => post.MessageId == Convert.ToInt64(e.Message.Id));

            if (message != null)
            {
                int VoteValue = 0;

                string discordName = e.Emoji.GetDiscordName();

                if (Config.Emojis.Confirms.Contains(discordName))
                {
                    VoteValue = 1;
                }
                else if (Config.Emojis.Love.Contains(discordName))
                {
                    VoteValue = 3;
                }
                else if (Config.Emojis.Declines.Contains(discordName))
                {
                    VoteValue = -1;
                }
                else if (Config.Emojis.Hate.Contains(discordName))
                {
                    VoteValue = -3;
                }

                var vote = await sankakuContext.ImageVote.FirstOrDefaultAsync(sankakuVote => sankakuVote.ImageId == message.ImageId &&
                                                                              sankakuVote.UserId == Convert.ToInt64(e.User.Id) &&
                                                                              sankakuVote.VoteValue == VoteValue);

                if (vote != null)
                {
                    sankakuContext.ImageVote.Remove(vote);
                }

                await sankakuContext.SaveChangesAsync();
            }
        }
Beispiel #9
0
        public async Task <bool> PostRandom(DiscordChannel channel, int skip = 0)
        {
            using var discordContext = new DiscordContext();

            (Entities.Sankaku.Image Information, byte[] Data)? image = null;

            try
            {
                image = await GetImage(channel, skip);
            }
            catch (Exception)
            {
                return(false);
            }

            string extension = ".jpeg";

            switch (image.Value.Information.FileType)
            {
            case Entities.Sankaku.FileType.ImageGif:
                extension = ".gif";
                break;

            case Entities.Sankaku.FileType.ImageJpeg:
                extension = ".jpeg";
                break;

            case Entities.Sankaku.FileType.ImagePng:
                extension = ".png";
                break;
            }

            DiscordMessage msg = null;

            var outStream = new MemoryStream(image.Value.Data);

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.SpringGreen,
                Title = discordContext.Puns.Skip(Helpers.RandomGenerator.RandomInt(0, discordContext.Puns.Count() - 1)).First().Text
            };

            try
            {
                if (outStream == null)
                {
                    Console.WriteLine("SankakuBot: Outstream was null");
                }

                Console.WriteLine($"SankakuBot: Sending File {Helpers.GetSafeFilename(builder.Title + extension)} to channel \"{channel.Name}\"");
                var msgTask = channel.SendFileAsync(Helpers.GetSafeFilename(builder.Title + extension), outStream, embed: builder.Build());

                int index = 0;
                while (!msgTask.IsCompleted && !msgTask.IsFaulted && index < 6000)
                {
                    await Task.Delay(5);
                }

                if (msgTask.IsCompleted)
                {
                    msg = await msgTask;
                }
                else
                {
                    Console.WriteLine($"SankakuBot: Couldn't send File with name {Helpers.GetSafeFilename(builder.Title + extension)}");
                    outStream.Close();
                    await _client.ReconnectAsync(true);
                }

                Console.WriteLine("SankakuBot: Finished Sending File");
            }
            catch (Exception ex)
            {
                Console.WriteLine("SankakuBot: Something went wrong while trying to send file");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException);
            }
            finally
            {
                try
                {
                    var taskContext = new DiscordContext();

                    taskContext.SankakuPost.Add(new SankakuPost()
                    {
                        Date      = DateTime.Now,
                        ImageId   = image.Value.Information.Id,
                        MessageId = Convert.ToInt64(msg.Id)
                    });

                    await taskContext.SaveChangesAsync();

                    _postedImages.Add(image.Value.Information.Id);

                    outStream.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            return(true);
        }
Beispiel #10
0
        public static async Task PostPrediction(long userId, DiscordChannel channel)
        {
            var context = new DiscordContext();

            SankakuImage imgToPost = null;

            Random rnd = new Random();

            var channelIDLong = Convert.ToInt64(channel.Id);

            var blacklistedTags =
                await context.SankakuTagBlacklist.Where(blackTag => blackTag.ChannelId == channelIDLong).Select(tag => tag.TagId).ToListAsync();

            var startDate = DateTime.Now - TimeSpan.FromDays(90);

            var trainedModel = Train(userId);

            int skip = 0;

            while (imgToPost == null)
            {
                //imgToPost = context.SankakuImage.Where(si => si.SankakuPost.Count == 0).Skip(skip).First();

                imgToPost = context.SankakuImage.Find(88415l);

                if (imgToPost == null)
                {
                    await ScrapeNewest();
                }

                List <MLSankakuPost> posts = new List <MLSankakuPost>();

                MLSankakuPost mlPost = new MLSankakuPost()
                {
                    //imgRating = imgToPost.Rating,
                    //score = Convert.ToSingle(imgToPost.Score),
                    //Tags = context.SankakuImageTag.Where(imageTag => imageTag.ImageId == imgToPost.Id).Select(tag => Convert.ToSingle(tag.TagId)).ToArray(),
                    Tags = 1,
                };

                posts.Add(mlPost);

                var prediction = trainedModel.Predict(posts, true);

                if (prediction.First().Score < 1)
                {
                    skip++;
                    imgToPost = null;
                }
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.Orange,
                Title = context.Puns.Skip(new Random().Next(context.Puns.Count() - 1)).First().Text
            };

            var link = HttpUtility.HtmlDecode(await GetOriginalImageLink(imgToPost.Id));

            var request = Helpers.CreateRequestWithHeaders(link);

            var response = request.GetResponse();

            SKImage img = SKImage.FromEncodedData(response.GetResponseStream());

            if (img.ColorType == SKColorType.Bgra8888)
            {
                //Bgra8888 needs an indexed Colortable, so convert it to Rgba8888 first
                var bitmap = new SKBitmap(new SKImageInfo(img.Width, img.Height, SKColorType.Rgba8888));
                var canvas = new SKCanvas(bitmap);
                canvas.DrawImage(img, 0, 0, null);
                canvas.Flush();
                img = SKImage.FromBitmap(bitmap);
            }

            var imageData = img.Encode(SKEncodedImageFormat.Jpeg, 75); //Encode in Jpeg instead of Webp because of IOS

            using (var outStream = imageData.AsStream())
            {
                var msg = await channel.SendFileAsync(outStream, builder.Title + ".jpeg",
                                                      embed : builder.Build());

                context.SankakuPost.Add(new Models.SankakuPost()
                {
                    Date      = DateTime.Now,
                    Image     = imgToPost,
                    MessageId = Convert.ToInt64(msg.Id)
                });

                await context.SaveChangesAsync();
            }
        }
Beispiel #11
0
        public static async Task PostRandom(DiscordChannel channel, int skip = 0)
        {
            var context = new DiscordContext();

            SankakuImage imgToPost = null;

            Random rnd = new Random(skip);

            var channelIDLong = Convert.ToInt64(channel.Id);

            var blacklistedTags =
                await context.SankakuTagBlacklist.Where(blackTag => blackTag.ChannelId == channelIDLong).Select(tag => tag.TagId).ToListAsync();

            var startDate = DateTime.Now - TimeSpan.FromDays(90);

            var viableImages = context.SankakuImage.Where(si => si.SankakuPost.Count == 0 && si.Score > 4 && si.RatingCount > 6);

            while (imgToPost == null)
            {
                var firstNotPostedPicture = viableImages.Where(si => !si.SankakuImageTag.Any(tag => blacklistedTags.Contains(tag.TagId)))
                                            .Skip(skip).First();

                if (firstNotPostedPicture == null)
                {
                    var oldestPostedPicture = viableImages.Where(si =>
                                                                 si.SankakuPost.OrderByDescending(post => post.Date).First().Date < startDate)
                                              .Skip(skip);
                }
                else
                {
                    imgToPost = firstNotPostedPicture;
                }

                if (imgToPost == null)
                {
                    await ScrapeNewest();
                }
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.SpringGreen,
                Title = context.Puns.Skip(rnd.Next(context.Puns.Count() - 1)).First().Text
            };

            var link = HttpUtility.HtmlDecode(await GetOriginalImageLink(imgToPost.Id));

            var request = Helpers.CreateRequestWithHeaders(link);

            var response = request.GetResponse();

            SKImage img = SKImage.FromEncodedData(response.GetResponseStream());

            if (img.ColorType == SKColorType.Bgra8888)
            {
                //Bgra8888 needs an indexed Colortable, so convert it to Rgba8888 first
                var bitmap = new SKBitmap(new SKImageInfo(img.Width, img.Height, SKColorType.Rgba8888));
                var canvas = new SKCanvas(bitmap);
                canvas.DrawImage(img, 0, 0, null);
                canvas.Flush();
                img = SKImage.FromBitmap(bitmap);
            }

            var imageData = img.Encode(SKEncodedImageFormat.Webp, 70);

            using (var outStream = imageData.AsStream())
            {
                var msg = await channel.SendFileAsync(outStream, builder.Title + ".webp",
                                                      embed : builder.Build());

                context.SankakuPost.Add(new Models.SankakuPost()
                {
                    Date      = DateTime.Now,
                    Image     = imgToPost,
                    MessageId = Convert.ToInt64(msg.Id)
                });

                await context.SaveChangesAsync();
            }
        }
        /// <summary>
        /// OAuth認証のアクセストークン取得。xAuth方式
        /// </summary>
        /// <param name="accessTokenUrl">アクセストークンの取得先URL</param>
        /// <param name="username">認証用ユーザー名</param>
        /// <param name="password">認証用パスワード</param>
        /// <returns>取得結果真偽値</returns>
        public HttpStatusCode AuthenticateXAuth(Uri accessTokenUrl, string username, string password, ref string content)
        {
            // ユーザー・パスワードチェック
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("username is null or empty", "username");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("password is null or empty", "password");
            }

            // xAuthの拡張パラメータ設定
            Dictionary <string, string> parameter = new Dictionary <string, string>();

            parameter.Add("x_auth_mode", "client_auth");
            parameter.Add("x_auth_username", username);
            parameter.Add("x_auth_password", password);

            // アクセストークン取得
            HttpStatusCode httpCode = this.GetOAuthToken(accessTokenUrl, "", "", parameter, ref content);

            if (httpCode != HttpStatusCode.OK)
            {
                return(httpCode);
            }
            NameValueCollection accessTokenData = base.ParseQueryString(content);

            if (accessTokenData != null)
            {
                this.token       = accessTokenData["oauth_token"];
                this.tokenSecret = accessTokenData["oauth_token_secret"];

                // サービスごとの独自拡張対応
                if (!string.IsNullOrEmpty(this.userIdentKey))
                {
                    this.authorizedUsername = accessTokenData[this.userIdentKey];
                }
                else
                {
                    this.authorizedUsername = "";
                }

                if (!string.IsNullOrEmpty(this.userIdIdentKey))
                {
                    try
                    {
                        this.authorizedUserId = Convert.ToInt64(accessTokenData[this.userIdIdentKey]);
                    }
                    catch (Exception)
                    {
                        this.authorizedUserId = 0;
                    }
                }
                else
                {
                    this.authorizedUserId = 0;
                }

                if (string.IsNullOrEmpty(token))
                {
                    throw new InvalidDataException("Token is null.");
                }
                return(HttpStatusCode.OK);
            }
            else
            {
                throw new InvalidDataException("Return value is null.");
            }
        }
        /// <summary>
        /// OAuth認証のアクセストークン取得。PIN入力用の後段
        /// </summary>
        /// <remarks>
        /// 事前にAuthenticatePinFlowRequestを呼んで、ブラウザで認証後に表示されるPINを入力してもらい、その値とともに呼び出すこと
        /// </remarks>
        /// <param name="accessTokenUrl">アクセストークンの取得先URL</param>
        /// <param name="requestToken">AuthenticatePinFlowRequestで取得したリクエストトークン</param>
        /// <param name="pinCode">Webで認証後に表示されるPINコード</param>
        /// <returns>取得結果真偽値</returns>
        public HttpStatusCode AuthenticatePinFlow(string accessTokenUrl, string requestToken, string pinCode)
        {
            // PIN-based flow
            if (string.IsNullOrEmpty(requestToken))
            {
                throw new InvalidOperationException("Sequence error.(requestToken is blank)");
            }

            // アクセストークン取得
            string content = "";
            NameValueCollection accessTokenData;
            HttpStatusCode      httpCode = this.GetOAuthToken(new Uri(accessTokenUrl), pinCode, requestToken, null, ref content);

            if (httpCode != HttpStatusCode.OK)
            {
                return(httpCode);
            }
            accessTokenData = base.ParseQueryString(content);

            if (accessTokenData != null)
            {
                this.token       = accessTokenData["oauth_token"];
                this.tokenSecret = accessTokenData["oauth_token_secret"];

                // サービスごとの独自拡張対応
                if (!string.IsNullOrEmpty(this.userIdentKey))
                {
                    this.authorizedUsername = accessTokenData[this.userIdentKey];
                }
                else
                {
                    this.authorizedUsername = "";
                }

                if (!string.IsNullOrEmpty(this.userIdIdentKey))
                {
                    try
                    {
                        this.authorizedUserId = Convert.ToInt64(accessTokenData[this.userIdIdentKey]);
                    }
                    catch (Exception)
                    {
                        this.authorizedUserId = 0;
                    }
                }
                else
                {
                    this.authorizedUserId = 0;
                }

                if (string.IsNullOrEmpty(token))
                {
                    throw new InvalidDataException("Token is null.");
                }
                return(HttpStatusCode.OK);
            }
            else
            {
                throw new InvalidDataException("Return value is null.");
            }
        }
Beispiel #14
0
        protected static internal object ConvertValue(Type type, NSJSValue value)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            object o = FetchValue(type, value);

            if (type == typeof(int))
            {
                o = (o == null ? 0 : Converter.ToInt32(o));
            }
            else if (type == typeof(uint))
            {
                o = (o == null ? 0u : Converter.ToUInt32(o));
            }
            else if (type == typeof(short))
            {
                o = (o == null ? (short)0 : Converter.ToInt16(o));
            }
            else if (type == typeof(ushort))
            {
                o = (o == null ? (ushort)0 : Converter.ToUInt16(o));
            }
            else if (type == typeof(sbyte))
            {
                o = (o == null ? (sbyte)0 : Converter.ToSByte(o));
            }
            else if (type == typeof(byte))
            {
                o = (o == null ? (byte)0 : Converter.ToByte(o));
            }
            else if (type == typeof(long))
            {
                o = (o == null ? 0L : Converter.ToInt64(o));
            }
            else if (type == typeof(ulong))
            {
                o = (o == null ? 0ul : Converter.ToUInt64(o));
            }
            else if (type == typeof(float))
            {
                o = (o == null ? 0f : Converter.ToSingle(o));
            }
            else if (type == typeof(double))
            {
                o = (o == null ? 0d : Converter.ToDouble(o));
            }
            else if (type == typeof(decimal))
            {
                o = (o == null ? 0m : Converter.ToDecimal(o));
            }
            else if (type == typeof(char))
            {
                o = (o == null ? '\0' : Converter.ToChar(o));
            }
            else if (type == typeof(DateTime))
            {
                long ticks = 0;
                if (o is long)
                {
                    ticks = (long)o;
                }
                else if (o != null)
                {
                    ticks = Converter.ToInt64(o);
                }
                o = NSJSDateTime.LocalDateToDateTime(ticks);
            }
            else if (type == typeof(string))
            {
                if (o == null)
                {
                    o = null;
                }
                else if (!(o is string))
                {
                    o = o.ToString();
                }
            }
            else if (typeof(NSJSValue).IsAssignableFrom(type))
            {
                return(type.IsInstanceOfType(value) ? value : null);
            }
            return(o);
        }
Beispiel #15
0
 public long ToInt64(object value)
     => SystemConvert.ToInt64(value);
Beispiel #16
0
        public async Task <bool> PostRandom(DiscordChannel channel, int skip = 0)
        {
            var context = new DiscordContext();

            var channelIDLong = Convert.ToInt64(channel.Id);

            var startDate = DateTime.Now - TimeSpan.FromDays(90);

            if (!_cachedImages.ContainsKey(channelIDLong))
            {
                Console.WriteLine($"Couldn't find cached Images for Channel {channelIDLong}");
                return(false);
            }

            var images = _cachedImages[Convert.ToInt64(channelIDLong)];

            var imgToPost = images.Where(cImg => !_postedImages.Contains(cImg)).Skip(skip).FirstOrDefault();

            if (imgToPost == 0)
            {
                await Console.Error.WriteLineAsync("Could not find a suitable Sankaku Image").ConfigureAwait(false);

                return(false);
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
            {
                Color = DiscordColor.SpringGreen,
                Title = context.Puns.Skip(Helpers.RandomGenerator.RandomInt(0, context.Puns.Count() - 1)).First().Text
            };

            var imageUri = await GetOriginalImageUrl(imgToPost).ConfigureAwait(false);

            if (imageUri == null)
            {
                return(false);
            }

            var link = HttpUtility.HtmlDecode(imageUri.AbsoluteUri);

            var response = await _httpClient.GetAsync(link);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                await Console.Error.WriteLineAsync($"Could not get Image Link for {imgToPost}").ConfigureAwait(false);

                return(false);
            }

            var stream = await response.Content.ReadAsStreamAsync();

            Stream  outStream = null;
            string  extension = "";
            SKImage img       = SKImage.FromEncodedData(stream);

            if (img != null)
            {
                if (img.ColorType == SKColorType.Bgra8888 || img.ColorType == SKColorType.Gray8)
                {
                    //Convert Types, that need an indexed Colortable to a non-indexed Type
                    var bitmap = new SKBitmap(new SKImageInfo(img.Width, img.Height, SKColorType.Rgba8888));
                    var canvas = new SKCanvas(bitmap);
                    canvas.DrawImage(img, 0, 0, null);
                    canvas.Flush();
                    img = SKImage.FromBitmap(bitmap);
                }

                var imageData = img.Encode(SKEncodedImageFormat.Jpeg, 75);

                outStream = imageData.AsStream();

                extension = ".jpeg";
            }
            else
            {
                return(false);
            }

            if (outStream == null || outStream.Length == 0)
            {
                await Console.Error.WriteLineAsync($"Stream for SankakuImage ({imgToPost}) was 0 length or null").ConfigureAwait(false);

                return(false);
            }

            try
            {
                using (outStream)
                {
                    Console.WriteLine("SankakuBot: Sending File");
                    var msgTask = channel.SendFileAsync(outStream, Helpers.GetSafeFilename(builder.Title + extension),
                                                        embed: builder.Build());

                    msgTask.Wait(30000);

                    DiscordMessage msg = null;

                    if (msgTask.IsCompleted)
                    {
                        msg = await msgTask;
                    }
                    else
                    {
                        Console.WriteLine($"SankakuBot: Couldn't send File with name {Helpers.GetSafeFilename(builder.Title + extension)}");
                        outStream.Close();
                        await _client.ReconnectAsync(true);

                        return(false);
                    }

                    Console.WriteLine("SankakuBot: Finished Sending File");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("SankakuBot: Something went wrong while trying to send file");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException);
            }
            finally
            {
                context.SankakuPost.Add(new SankakuPost()
                {
                    Date      = DateTime.Now,
                    ImageId   = imgToPost,
                    MessageId = -1
                });

                await context.SaveChangesAsync();

                _postedImages.Add(imgToPost);
            }

            return(true);
        }