示例#1
0
        public void Readme()
        {
            var myObject = new MyType();

            // static usage
            var copy = Ditto.DeepClone(myObject);

            Assert.False(Object.ReferenceEquals(copy, myObject), "copy is not the same object");
            Assert.True(Ditto.Equals(copy, myObject), "copy is equivalent");
            Assert.True(Ditto.GetHashCode(copy) == Ditto.GetHashCode(myObject));

            // instance usage
            var comparer = Ditto.GetComparer <MyType>();

            Assert.True(comparer is IEqualityComparer <MyType>);

            var copy2 = comparer.DeepClone(myObject);

            Assert.False(Object.ReferenceEquals(copy2, myObject), "copy2 is not the same object");
            Assert.True(comparer.Equals(copy2, myObject), "copy2 is equivalent");
            Assert.True(comparer.GetHashCode(copy2) == Ditto.GetHashCode(myObject));
        }
 public void Setup()
 {
     Ditto.RegisterContextAccessor <MockDittoContextAccessor>();
 }
示例#3
0
        public static void Start()
        {
            if (!Initialized)
            {
                Initialized = true;
                if (_cancellationTokenSource.IsCancellationRequested)
                {
                    _cancellationTokenSource = new CancellationTokenSource();
                    Running = false;
                }
                if (!Running)
                {
                    Running = true;
                    try
                    {
                        var _ = Task.Run(async() =>
                        {
                            while (Running)
                            {
                                try
                                {
                                    if ((DateTime.Now - _lastTime) > Delay)
                                    {
                                        // Sort items based on priority and date added
                                        //if (Ditto.Running && Ditto.Client != null
                                        //        && Ditto.Client.ConnectionState == ConnectionState.Connected
                                        //        && Ditto.Client.LoginState == LoginState.LoggedIn)
                                        //{
                                        //    var items = _playingStatusItems.OrderByDescending(e => e.Priority).ThenByDescending(e => e.DateAdded);
                                        //    foreach (var item in items)
                                        //    {
                                        //        var result = await item.Execute(Ditto.Client).ConfigureAwait(false);
                                        //        if (result != null)
                                        //        {
                                        //            if (Ditto.Running && Ditto.Client != null
                                        //                && Ditto.Client.ConnectionState == ConnectionState.Connected
                                        //                && Ditto.Client.LoginState == LoginState.LoggedIn)
                                        //            {
                                        //                await Ditto.Client.SetGameAsync(result.Length == 0 ? null : result);
                                        //            }
                                        //            break;
                                        //        }
                                        //    }
                                        //}

                                        if (await Ditto.IsClientConnectedAsync())
                                        {
                                            var items = _playingStatusItems.OrderByDescending(e => e.Priority).ThenByDescending(e => e.DateAdded);
                                            foreach (var item in items)
                                            {
                                                var result = await item.Execute(await Ditto.Client.DoAsync(c => c)).ConfigureAwait(false);
                                                if (result != null)
                                                {
                                                    if (await Ditto.IsClientConnectedAsync())
                                                    {
                                                        await Ditto.Client.DoAsync(c
                                                                                   => c.SetGameAsync(result.Length == 0 ? null : result)
                                                                                   ).ConfigureAwait(false);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        _lastTime = DateTime.Now;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Error(ex);
                                }
                                await Task.Delay(100).ConfigureAwait(false);
                            }
                        }, _cancellationTokenSource.Token);
                    }
                    catch (Exception ex) when(ex is OperationCanceledException || ex is TaskCanceledException)
                    {
                        if (_cancellationTokenSource.IsCancellationRequested)
                        {
                            _cancellationTokenSource = new CancellationTokenSource();
                        }
                    }
                }
            }
        }
示例#4
0
        public async Task Update()
        {
            if (Permissions.IsAdministratorOrBotOwner(Context))
            {
                var buildInfo = await CheckForUpdates().ConfigureAwait(false);

                if (!buildInfo.IsEqual && (await UpdateList(null, false).ConfigureAwait(false)).Count() > 0)
                {
                    // Add a database link containing the current local branch.
                    await Ditto.Database.DoAsync((uow) =>
                    {
                        var link = uow.Links.GetOrAdd((link) => link.Type == Database.Data.LinkType.Update, new Database.Models.Link()
                        {
                            Type      = Database.Data.LinkType.Update,
                            ChannelId = Context.Channel.Id,
                            GuildId   = Context.Guild.Id,
                            Date      = DateTime.Now,
                            Value     = $"{Context.Message.Id}|{buildInfo.LocalHash}",
                        });

                        link.ChannelId = Context.Channel.Id;
                        link.GuildId   = Context.Guild.Id;
                        link.Date      = DateTime.Now;
                        link.Value     = $"{Context.Message.Id}|{buildInfo.LocalHash}";
                    }, true).ConfigureAwait(false);


                    var pull = RunGit("pull origin master");

                    var startInfo = new ProcessStartInfo()
                    {
                        FileName         = "bash",
                        Arguments        = $"{Ditto.Settings.Paths.BaseDir}/{Ditto.Settings.Paths.ScriptDir}/Run.{(BaseClass.IsLinux() ? "sh" : "bat")}",
                        WorkingDirectory = $"{Ditto.Settings.Paths.BaseDir}/{Ditto.Settings.Paths.ScriptDir}",
                        UseShellExecute  = false,
                        CreateNoWindow   = false,
                    };
                    if (BaseClass.IsWindows())
                    {
                        startInfo.FileName  = "cmd";
                        startInfo.Arguments = "/c " + startInfo.Arguments;
                    }

                    // Start a new instance and close the current process.
                    Log.Info($"Updating bot...");
                    await Ditto.StopAsync().ConfigureAwait(false);

                    using var process = new Process()
                          {
                              StartInfo = startInfo
                          };
                    process.Start();
                    Program.Close();
                }
                else
                {
                    await Context.ApplyResultReaction(CommandResult.SuccessAlt1).ConfigureAwait(false);
                }
            }
            else
            {
                await Context.ApplyResultReaction(CommandResult.FailedUserPermission).ConfigureAwait(false);
            }
        }
 public bool Mutable(Type type)
 {
     return(Ditto.IsMutable(type));
 }
示例#6
0
        static LinkUtility()
        {
            //On client connected
            Ditto.Connected += () =>
            {
                _links?.Clear();
                _cancellationTokenSource?.Cancel();
                _cancellationTokenSource = new CancellationTokenSource();
                Ditto.Database.ReadAsync((uow) =>
                {
                    _links = new ConcurrentDictionary <int, Link>(
                        uow.Links.GetAllWithLinks()
                        .Select(i => new KeyValuePair <int, Link>(i.Id, i))
                        );
                });

                var _ = Task.Run(async() =>
                {
                    while (Ditto.Running)
                    {
                        var databaseModified = false;
                        var tasks            = new List <Task>();
                        var links            = _links.Select(i => i.Value).ToList();
                        foreach (var link in links)
                        {
                            if (!(Ditto.Running && await Ditto.IsClientConnectedAsync().ConfigureAwait(false)))
                            {
                                break;
                            }

                            tasks.Add(Task.Run(async() =>
                            {
                                // Verify that we have access to the channel
                                var channel = link.Channel;
                                if (channel != null &&
                                    channel.GuildId == link.GuildId &&
                                    (await Ditto.Client.DoAsync((c) => c.GetPermissionsAsync(channel))).HasAccess()
                                    )
                                {
                                    var linkItems = await ReadAndPostLinkAsync(link).ConfigureAwait(false);
                                    if (linkItems.Count() > 0)
                                    {
                                        link.Links.AddRange(linkItems);
                                        databaseModified = true;
                                    }
                                }
                                else
                                {
                                    Log.Debug($"Could not access the channel {channel?.Guild?.Name}:{channel?.Name}");
                                }
                            }));
                        }

                        await Task.WhenAll(tasks).ConfigureAwait(false);
                        if (databaseModified)
                        {
                            await Ditto.Database.WriteAsync(uow =>
                            {
                                uow.Links.UpdateRange(links);
                            }).ConfigureAwait(false);
                        }


                        await Task.Delay(500).ConfigureAwait(false);
                    }
                });
                return(Task.CompletedTask);
            };

            // On client disconnected
            Ditto.Exit += () =>
            {
                _links?.Clear();
                _cancellationTokenSource?.Cancel();
                return(Task.CompletedTask);
            };
        }