Exemple #1
0
 public bool Init(ChannelConfig channelConfig, IPEndPoint ep)
 {
     server = new KcpServer();
     server.init(Environment.ProcessorCount, this, channelConfig, ep.Port);
     return(true);
 }
Exemple #2
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

// !tempChannel
            Command newCommand = new Command("tempChannel");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Creates a temporary voice channel. This channel will be destroyed when it becomes empty, with grace period of three minutes since it's creation.";
            newCommand.ManPage             = new ManPage("[userLimit] <channelName>", "`[userLimit]` - Optional user limit.\n\n`<channelName>` - Name of the new temporary voice channel.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (e.Server.Config.TempChannelCategoryId == 0)
                {
                    await e.SendReplySafe("This command has to be configured on the config page (\"other\" section) <https://valkyrja.app/config>");

                    return;
                }

                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}tempChannel <name>` or `{e.Server.Config.CommandPrefix}tempChannel [userLimit] <name>`");

                    return;
                }

                int           limit   = 0;
                bool          limited = int.TryParse(e.MessageArgs[0], out limit);
                StringBuilder name    = new StringBuilder();
                for (int i = limited ? 1 : 0; i < e.MessageArgs.Length; i++)
                {
                    name.Append(e.MessageArgs[i]);
                    name.Append(" ");
                }
                string responseString = string.Format(TempChannelConfirmString, name.ToString());

                try
                {
                    RestVoiceChannel tempChannel = null;
                    if (limited)
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => {
                            c.CategoryId = e.Server.Config.TempChannelCategoryId;
                            c.UserLimit  = limit;
                        });
                    }
                    else
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => c.CategoryId = e.Server.Config.TempChannelCategoryId);
                    }

                    if (e.Server.Config.TempChannelGiveAdmin)
                    {
                        await tempChannel.AddPermissionOverwriteAsync(e.Message.Author, new OverwritePermissions(manageChannel : PermValue.Allow, manageRoles : PermValue.Allow, moveMembers : PermValue.Allow, muteMembers : PermValue.Allow, deafenMembers : PermValue.Allow));
                    }

                    ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    ChannelConfig channel   = dbContext.Channels.AsQueryable().FirstOrDefault(c => c.ServerId == e.Server.Id && c.ChannelId == tempChannel.Id);
                    if (channel == null)
                    {
                        channel = new ChannelConfig {
                            ServerId  = e.Server.Id,
                            ChannelId = tempChannel.Id
                        };

                        dbContext.Channels.Add(channel);
                    }

                    channel.Temporary = true;
                    dbContext.SaveChanges();
                    dbContext.Dispose();
                }
                catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when trying to create a temporary channel.");
                }
                catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    responseString = string.Format(ErrorUnknownString, this.Client.GlobalConfig.AdminUserId);
                }

                await e.SendReplySafe(responseString);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("tmp"));
            commands.Add(newCommand.CreateAlias("tc"));

// !mentionRole
            newCommand                     = new Command("mentionRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Mention a role with a message. Use with the name of the role as the first parameter and the message will be the rest.";
            newCommand.ManPage             = new ManPage("<roleName> <message text>", "`<roleName>` - Name of the role to be mentioned with a ping.\n\n`<message text>` - Text that will be said with the role mention.");
            newCommand.DeleteRequest       = true;
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <roleName> <message text>`");

                    return;
                }

                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = e.Server.Guild.Roles.Where(r => r.Name == e.MessageArgs[0])).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower() == e.MessageArgs[0].ToLower())).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.MessageArgs[0].ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role    = foundRoles.First();
                string     message = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[1]));

                await role.ModifyAsync(r => r.Mentionable = true);

                await Task.Delay(100);

                await e.SendReplySafe($"{role.Mention} {message}", allowedMentions : new AllowedMentions(AllowedMentionTypes.Users | AllowedMentionTypes.Everyone | AllowedMentionTypes.Roles));

                await Task.Delay(100);

                await role.ModifyAsync(r => r.Mentionable = false);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("announce"));

// !cheatsheet
            newCommand                     = new Command("cheatsheet");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send an embed cheatsheet with various moderation commands.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation commands").WithColor(16711816).WithFields(
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}op`").WithValue("Distinguish yourself as a moderator when addressing people, and allow the use of `!mute`, `!kick` & `!ban` commands."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}mute @user(s) duration`").WithValue("Mute mentioned user(s) for `duration` (use `m`, `h` and `d`, e.g. 1h15m. This will effectively move them to the `#chill-zone` channel."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}kick @user(s) reason`").WithValue("Kick mentioned `@users` (or IDs) with specific `reason`."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}ban @user(s) duration reason`").WithValue("Ban mentioned `@users` (or IDs) for `duration` (use `h` and `d`, e.g. 1d12h, or zero `0d` for permanent) with specific `reason`."),
                    new EmbedFieldBuilder().WithName("`reason`").WithValue("Reason parameter of the above `kick` and `ban` commands is stored in the database as a _warning_ and also PMed to the user. Please provide proper descriptions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}issueWarning @user(s) message`").WithValue("The same as `addWarning`, but also PM this message to the user(s)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}addWarning @user(s) message`").WithValue("Add a `message` to the database, taking notes of peoples naughty actions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}removeWarning @user`").WithValue("Remove the last added warning from the `@user` (or ID)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}whois @user`").WithValue("Search for a `@user` (or ID, or name) who is present on the server."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}find expression`").WithValue("Search for a user using more complex search through all the past nicknames, etc... This will also go through people who are not on the server anymore."),
                    new EmbedFieldBuilder().WithName($"`whois/find`").WithValue("Both whois and find commands will return information about the user, when was their account created, when did they join, their past names and nicknames, and all the previous warnings and bans.")
                    );

                RestUserMessage msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();

                embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation guidelines").WithColor(16711816).WithDescription("for implementing the [theory](http://rhea-ayase.eu/articles/2017-04/Moderation-guidelines) in real situations.\n")
                .WithFields(
                    new EmbedFieldBuilder().WithName("__Talking to people__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Don't use threats.").WithValue("a) **Imposed consequences** - what you can do with your power (kick, ban,...) These are direct threats, avoid them.\nb) **Natural consequences** - implied effects of members actions. These can include \"the community is growing to dislike you,\" or \"see you as racist,\" etc..."),
                    new EmbedFieldBuilder().WithName("Identify what is the underlying problem.").WithValue("a) **Motivation problem** - the member is not motivated to behave in acceptable manner - is a troll or otherwise enjoys being mean to people.\nb) **Ability problem** - the member may be direct without \"filters\" and their conversation often comes off as offensive while they just state things the way they see them: http://www.mit.edu/~jcb/tact.html"),
                    new EmbedFieldBuilder().WithName("Conversation should follow:").WithValue("1) **Explain** the current situation / problem.\n2) **Establish safety** - you're not trying to ban them or discourage them from participating.\n3) **Call to action** - make sure to end the conversation with an agreement about what steps will be taken towards improvement.\n"),
                    new EmbedFieldBuilder().WithName("__Taking action__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Always log every action").WithValue("with `warnings`, and always check every member and their history."),
                    new EmbedFieldBuilder().WithName("Contents of our channels should not be disrespectful towards anyone, think about minorities.").WithValue("a) Discussion topic going wild, the use of racial/homophobic or other improper language should be pointed out with an explanation that it is not cool towards minorities within our community.\nb) A member being plain disrespectful on purpose... Mute them, see their reaction to moderation talk and act on it."),
                    new EmbedFieldBuilder().WithName("Posting or even spamming inappropriate content").WithValue("should result in immediate mute and only then followed by explaining correct behavior based on all of the above points."),
                    new EmbedFieldBuilder().WithName("Repeated offense").WithValue("a) 1d ban, 3d ban, 7d ban - are your options depending on how severe it is.\nb) Permanent ban should be brought up for discussion with the rest of the team."),
                    new EmbedFieldBuilder().WithName("Member is disrespectful to the authority.").WithValue("If you get into conflict yourself, someone is disrespectful to you as a moderator, trolling and challenging your authority - step back and ask for help, mention `@Staff` in the mod channel, and let 3rd party deal with it.")
                    );

                msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();
            };
            commands.Add(newCommand);

// !embed
            newCommand             = new Command("embed");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Build an embed. Use without arguments for help.";
            newCommand.ManPage     = new ManPage("<options>", "Use any combination of:\n" +
                                                 "`--channel     ` - Channel where to send the embed.\n" +
                                                 "`--edit <msgId>` - Replace a MessageId with a new embed (use after --channel)\n" +
                                                 "`--title       ` - Title\n" +
                                                 "`--description ` - Description\n" +
                                                 "`--footer      ` - Footer\n" +
                                                 "`--color       ` - #rrggbb hex color used for the embed stripe.\n" +
                                                 "`--image       ` - URL of a Hjuge image in the bottom.\n" +
                                                 "`--thumbnail   ` - URL of a smol image on the side.\n" +
                                                 "`--fieldName   ` - Create a new field with specified name.\n" +
                                                 "`--fieldValue  ` - Text value of a field - has to follow a name.\n" +
                                                 "`--fieldInline ` - Use to set the field as inline.\n" +
                                                 "Where you can repeat the field* options multiple times.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                await this.Client.SendEmbedFromCli(e);
            };
            commands.Add(newCommand);

// !addEmoji
            newCommand                     = new Command("addEmoji");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add an emoji reaction to a message.";
            newCommand.ManPage             = new ManPage("<messageId> <emojis>", "`<messageId>` - ID of the message (in the current channel)\n\n`<emojis>` - Emojis that will be added as a reaction.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[0], out guid messageId))
                {
                    await e.SendReplySafe("Invalid parameters:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <IEmote> emotes = new List <IEmote>();
                for (int i = 1; i < e.MessageArgs.Length; i++)
                {
                    if (Emote.TryParse(e.MessageArgs[i], out Emote emote))
                    {
                        emotes.Add(emote);
                    }
                    else
                    {
                        emotes.Add(new Emoji(e.MessageArgs[i]));
                    }
                }

                if (!emotes.Any())
                {
                    await e.SendReplySafe("No emotes found:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                string response = "K.";
                try
                {
                    IMessage msg = await e.Channel.GetMessageAsync(messageId);

                    switch (msg)
                    {
                    case RestUserMessage message:
                        await message.AddReactionsAsync(emotes.ToArray());

                        break;

                    case SocketUserMessage message:
                        await message.AddReactionsAsync(emotes.ToArray());

                        break;

                    default:
                        response = "Failed to fetch a message with that ID. Did you use this command in a correct channel?";
                        break;
                    }
                }
                catch (Exception)
                {
                    response = "You've dun goof'd, eh?";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

            return(commands);
        }
Exemple #3
0
 public Channel(ChannelConfig config, Func <byte, Playlist> playlistFactory, Player player)
 {
     _config   = config;
     _playlist = playlistFactory(Id);
     _player   = player;
 }
        public async Task CheckStreamerInfoAsync()
        {
            try
            {
                StreamerStatus = await streamerInformation();

                bool isStreaming = StreamerStatus.online;

                if (IsOnline != isStreaming)
                {
                    if (IsOnline)
                    {
                        if (++TimeoutCount >= 3)
                        {
                            TimeoutCount = 0;
                            IsOnline     = false;

                            ViewerGraph?.Dispose();
                            ViewerGraph = null;

                            ToUpdate    = new Dictionary <ulong, ulong>();
                            GameChanges = new List <Tuple <string, DateTime> >();

                            if (OnOffline != null)
                            {
                                await OnOffline.Invoke(this);
                            }
                            foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][OFFLINE]).ToList())
                            {
                                await OnMinorChangeTracked(channel, $"{Name} went Offline!");
                            }

                            //SetTimer(600000, 600000);
                        }
                    }
                    else
                    {
                        ViewerGraph = new DatePlot(Name + "Mixer", "Time since start", "Viewers");
                        IsOnline    = true;
                        CurGame     = StreamerStatus.type?.name ?? "Nothing";
                        GameChanges.Add(Tuple.Create(CurGame, DateTime.UtcNow));
                        ViewerGraph.AddValue(CurGame, 0, (await GetBroadcastStartTime()).AddHours(-2));

                        if (OnLive != null)
                        {
                            await OnLive.Invoke(this);
                        }
                        foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][ONLINE]).ToList())
                        {
                            await OnMinorChangeTracked(channel, (string)ChannelConfig[channel]["Notification"]);
                        }

                        //SetTimer(60000, 60000);
                    }
                    await UpdateTracker();
                }
                else
                {
                    TimeoutCount = 0;
                }

                if (isStreaming)
                {
                    if (CurGame.CompareTo(StreamerStatus.type?.name ?? "Nothing") != 0)
                    {
                        CurGame = StreamerStatus.type?.name ?? "Nothing";
                        GameChanges.Add(Tuple.Create(CurGame, DateTime.UtcNow));
                        await UpdateTracker();

                        foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][GAMECHANGE]).ToList())
                        {
                            await OnMinorChangeTracked(channel, $"{Name} switched games to **{CurGame}**");
                        }
                    }

                    if (ChannelConfig.Any(x => (bool)x.Value[SHOWGRAPH]))
                    {
                        await ModifyAsync(x => x.ViewerGraph.AddValue(CurGame, StreamerStatus.viewersCurrent));
                    }

                    foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][SHOWEMBED]).ToList())
                    {
                        await OnMajorChangeTracked(channel, createEmbed(StreamerStatus, (bool)ChannelConfig[channel][THUMBNAIL], (bool)ChannelConfig[channel][SHOWTIMESTAMPS], (bool)ChannelConfig[channel][SHOWGRAPH]));
                    }
                }
            }
            catch (Exception e)
            {
                await Program.MopsLog(new LogMessage(LogSeverity.Error, "", $" error by {Name}", e));
            }
        }
Exemple #5
0
 /// <summary>
 /// Creates a new communication channel.
 /// </summary>
 public virtual ChannelLogic CreateChannel(ILineContext lineContext, ChannelConfig channelConfig)
 {
     return(null);
 }
Exemple #6
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public ChannelView(DriverView parentView, ChannelConfig channelConfig)
     : base(parentView)
 {
     AppConfig     = parentView.AppConfig;
     ChannelConfig = channelConfig ?? throw new ArgumentNullException(nameof(channelConfig));
 }
Exemple #7
0
 public Channel() {
     config = new ChannelConfig();
 }
Exemple #8
0
        public DataPackageScope GetScopeData()
        {
            if (timeOrigin == null)
            {
                return(null);
            }
            if (viewportUpdateLock == null)
            {
                return(null);
            }
            if (timeOrigin == null)
            {
                return(null);
            }
            if (acquisitionRunning == null)
            {
                return(null);
            }

            //Sleep to simulate USB delay
            System.Threading.Thread.Sleep(usbLatency);
            TimeSpan timeOffset = DateTime.Now - timeOrigin;

            List <AnalogChannel> channelsToAcquireDataFor = new List <AnalogChannel> ();

            if (isAudio)
            {
                channelsToAcquireDataFor.Add(AnalogChannel.ChA);
            }
            else
            {
                channelsToAcquireDataFor.AddRange(AnalogChannel.List);
            }

            if (acquisitionRunning)
            {
                lock (viewportUpdateLock)
                {
                    viewportUpdate = true;
                }
                int triggerHoldoffInSamples = 0;
                int triggerIndex            = 0;
                Dictionary <AnalogChannel, List <float> > waveAnalog = new Dictionary <AnalogChannel, List <float> >();
                foreach (AnalogChannel ch in AnalogChannel.List)
                {
                    waveAnalog.Add(ch, new List <float>((int)waveLength));
                }
                List <byte> waveDigital = new List <byte>();

                bool triggerDetected = false;

                //loop until trigger condition is met
                while (true)
                {
                    //in case the stop button has been pressed, this section makes sure the last-shown acquisition is kept on the display (otherwise it is replaced by a new acquisition)
                    if ((StopPending || !acquisitionRunning) && (lastCommittedDataPackage != null))
                    {
                        acquisitionRunning = false;
                        return(lastCommittedDataPackage);
                    }

                    AcquisitionMode AcquisitionModeCurrent;
                    lock (acquisitionSettingsLock)
                    {
                        acquisitionBufferAnalog     = new Dictionary <AnalogChannel, float[]>();
                        AcquisitionModeCurrent      = acquisitionMode;
                        acquisitionDepthCurrent     = AcquisitionDepth;
                        TriggerHoldoffCurrent       = triggerHoldoff;
                        SamplePeriodCurrent         = SamplePeriod;
                        waveLengthCurrent           = waveLength;
                        logicAnalyserChannelCurrent = logicAnalyserChannel;
                        logicAnalyserEnabledCurrent = LogicAnalyserEnabled;
                    }

                    acquistionId++;

                    //Stop trying to find a trigger at some point to avoid running out of memory
                    if (waveAnalog.Where(x => x.Value.Count > GENERATION_LENGTH_MAX).Count() > 0 || waveDigital.Count > GENERATION_LENGTH_MAX)
                    {
                        System.Threading.Thread.Sleep(10);
                        return(null);
                    }

                    //ANALOG CHANNELS DATA GENERATION
                    foreach (AnalogChannel channel in channelsToAcquireDataFor)
                    {
                        if (!ChannelConfig.ContainsKey(channel))
                        {
                            return(null);
                        }

                        if (logicAnalyserEnabledCurrent && channel == logicAnalyserChannelCurrent)
                        {
                            continue;
                        }
                        float[] wave;
                        if (HardwareInterface.Serial == DummyInterface.Generator)
                        {
                            wave = DummyScope.GenerateWave(waveLengthCurrent,
                                                           SamplePeriodCurrent,
                                                           timeOffset.Ticks / 1e7,
                                                           ChannelConfig[channel]);
                        }
                        else if (HardwareInterface.Serial == DummyInterface.File)
                        {
                            float[] data = (hardwareInterface as DummyInterfaceFromFile).GetWaveFromFile <float>(channel, ref waveLengthCurrent, ref SamplePeriodCurrent); //in case of FileReader, the file actually dictates most of the settings
                            if (data.Length > 0)
                            {
                                wave = data;
                                acquisitionDepthCurrent = waveLengthCurrent;
                            }
                            else
                            {
                                wave = new float[waveLengthCurrent];
                            }
                            //timeOffset = new TimeSpan((long)(timeOffsetFromFile * 1e7));
                            //ViewPortTimeSpan = SamplePeriodCurrent * (double)waveLengthCurrent;
                            //ViewPortOffset = 0; //MUSTFIX
                            //acquisitionDepthCurrent = waveLengthCurrent;
                        }
#if ANDROID
                        else if (hardwareInterface.Serial == DummyInterface.Audio)
                        {
                            //fetch audio data
                            if (audioJack == null)
                            {
                                return(null);
                            }
                            byte[] audioData = new byte[audioBufferLengthInBytes];
                            int    bytesRead = audioJack.Read(audioData, 0, audioBufferLengthInBytes);                           //2 bytes per sample
                            int    watchdog  = 0;
                            while (bytesRead <= 0 && watchdog++ < 1000)
                            {
                                System.Threading.Thread.Sleep(1);
                                bytesRead = audioJack.Read(audioData, 0, audioBufferLengthInBytes);                                  //2 bytes per sample
                            }

                            //convert bytes to shorts
                            short[] sampleData = new short[audioData.Length / 2];
                            Buffer.BlockCopy(audioData, 0, sampleData, 0, sampleData.Length * 2);

                            //and then into floats
                            wave = new float[sampleData.Length];
                            for (int i = 0; i < wave.Length; i++)
                            {
                                wave [i] = (float)sampleData [i] / (float)short.MaxValue;
                            }

                            //in case of large zoomouts, decimation will be > 0
                            //FIXME: this is not the best location to do this. time-errors will accumulate. better to do this on eventual wave. but then trigger index etc needs to be adjusted
                            int skip = 1 << (int)decimation;
                            wave = wave.Where((x, i) => i % skip == 0).ToArray();
                        }
#endif
                        else
                        {
                            throw new Exception("Unsupported dummy interface");
                        }

                        //coupling, noise injection in SW. Not needed for File or Audio generators
                        if (isGenerator)
                        {
                            if (ChannelConfig [channel].coupling == Coupling.AC)
                            {
                                DummyScope.RemoveDcComponent(ref wave, ChannelConfig [channel].frequency, SamplePeriodCurrent);
                            }
                            else
                            {
                                DummyScope.AddDcComponent(ref wave, (float)ChannelConfig [channel].dcOffset);
                            }
                            DummyScope.AddNoise(wave, ChannelConfig [channel].noise);
                        }
                        waveAnalog[channel].AddRange(wave);
                    }

                    //DIGITAL CHANNELS DATA GENERATION
                    if (logicAnalyserEnabledCurrent)
                    {
                        if (isFile)
                        {
                            byte[] data = (HardwareInterface as DummyInterfaceFromFile).GetWaveFromFile <byte>(LogicAnalyserChannel.LA, ref waveLengthCurrent, ref SamplePeriodCurrent);
                            if (data.Length > 0)
                            {
                                waveDigital.AddRange(data);
                                acquisitionDepthCurrent = waveLengthCurrent;
                            }
                            else
                            {
                                waveDigital.AddRange(new byte[waveLengthCurrent]);
                            }
                        }
                        else if (!isAudio) //MUSTFIX: add LA support for FileReader
                        {
                            waveDigital.AddRange(DummyScope.GenerateWaveDigital(waveLengthCurrent, SamplePeriodCurrent, timeOffset.TotalSeconds));
                        }
                    }

                    //SEARCH TRIGGER POSITION. STORE IN triggerIndex
                    triggerHoldoffInSamples = (int)(TriggerHoldoffCurrent / SamplePeriodCurrent);
                    double triggerTimeout = 0.0;
                    if (AcquisitionModeCurrent == AcquisitionMode.AUTO)
                    {
                        triggerTimeout = SamplePeriodCurrent * acquisitionDepthCurrent * 1.0;                         //Give up after twice the acqbuffer timespan
                    }
                    //detect digital trigger
                    if (logicAnalyserEnabledCurrent && this.triggerValue.mode == TriggerMode.Digital)
                    {
                        triggerDetected = DummyScope.DoTriggerDigital(waveDigital.ToArray(), triggerHoldoffInSamples, digitalTrigger, acquisitionDepthCurrent, out triggerIndex);
                        if (isAudio)
                        {
                            triggerDetected = false;
                        }
                    }
                    else
                    //detect analog trigger
                    {
                        if (this.isFile)
                        {
                            triggerDetected = true; //causes CPU load reduction (as skipping trigger detection) and required to jump out of while loop
                            triggerIndex    = triggerHoldoffInSamples;
                        }
                        else
                        {
                            if (triggerValue == null)
                            {
                                return(null);
                            }
                            if (triggerValue.source == null)
                            {
                                return(null);
                            }

                            if (triggerValue.source == TriggerSource.External)
                            {
                                triggerDetected = false;
                            }
                            triggerDetected = DummyScope.DoTriggerAnalog(waveAnalog[triggerValue.channel].ToArray(), triggerValue,
                                                                         triggerHoldoffInSamples, triggerThreshold, triggerWidth,
                                                                         acquisitionDepthCurrent, out triggerIndex);
                        }
                    }
                    awaitingTrigger = !triggerDetected;

                    //END DATA GENERATION WHILE LOOP
                    //break out of while loop if trigger was detected
                    if (triggerDetected)
                    {
                        forceTrigger    = false;
                        awaitingTrigger = false;
                        break;
                    }

                    //break out of while loop if triggerWasForced or synthetical 10ms limit was reached
                    if (
                        forceTrigger ||
                        (triggerTimeout > 0 && waveAnalog[AnalogChannel.ChA].Count * SamplePeriodCurrent >= triggerTimeout))
                    {
                        forceTrigger    = false;
                        triggerIndex    = triggerHoldoffInSamples;
                        awaitingTrigger = false;
                        break;
                    }

                    //HOUSEKEEPING WHILE LOOP
                    //keep track of time of first samplemoment
                    var timePassed = new TimeSpan((long)(waveLengthCurrent * SamplePeriodCurrent * 1e7));
                    timeOffset = timeOffset.Add(timePassed);
                } // end of while loop -- at this point 'waveAnalog' and 'waveDigital' contains useful data. Either because the trigger has been found, too much time has passed or data has been read from file

                //CPU-GPU OPTIMISATION
                //crop wave to only displayable part and store in buffer
                foreach (AnalogChannel channel in channelsToAcquireDataFor)
                {
                    if (logicAnalyserEnabledCurrent && channel == logicAnalyserChannelCurrent)
                    {
                        continue;
                    }
                    else if (isFile)
                    {
                        acquisitionBufferAnalog[channel] = waveAnalog[channel].ToArray();
                    }
                    else
                    {
                        acquisitionBufferAnalog[channel] = DummyScope.CropWave(acquisitionDepthCurrent, waveAnalog[channel].ToArray(), triggerIndex, triggerHoldoffInSamples);
                    }
                }
                acquisitionBufferDigital = DummyScope.CropWave(acquisitionDepthCurrent, waveDigital.ToArray(), triggerIndex, triggerHoldoffInSamples);
                //from this point onwards, 'waveAnalog' and 'waveDigital' are no longer used. data now stored instead in 'acquisitionBufferAnalog' and 'acquisitionBufferDigital'

                if (StopPending)
                {
                    acquisitionRunning = false;
                }
            }// ends 'if (acquisitionRunning)'. so when stopped both buffers contain the data of the previous call.

            lock (viewportUpdateLock)
            {
                if (!viewportUpdate)
                {
                    return(null);
                }
                viewportUpdate = false;
            }

            if (acquisitionBufferAnalog == null)
            {
                return(null);
            }
            if (acquisitionBufferAnalog.Count == 0)
            {
                return(null);
            }

            //VIEWPORT DECIMATION.
            //Decrease the number of samples till viewport sample period is larger than
            //or equal to the full sample rate
            uint samples            = VIEWPORT_SAMPLES_MAX;
            int  viewportDecimation = 0;
            if (!isFile)
            {
                while (true)
                {
                    viewportDecimation = (int)Math.Ceiling(Math.Log(ViewPortTimeSpan / (samples + 2) / SamplePeriodCurrent, 2));
                    if (viewportDecimation >= 0)
                    {
                        break;
                    }
                    samples /= 2;
                }

                if (viewportDecimation > VIEW_DECIMATION_MAX)
                {
                    Logger.Warn("Clipping view decimation! better decrease the sample rate!");
                    viewportDecimation = VIEW_DECIMATION_MAX;
                }
            }
            int viewportSamples     = (int)(ViewPortTimeSpan / (SamplePeriodCurrent * Math.Pow(2, viewportDecimation))) + 2;
            int viewportOffsetLocal = (int)(ViewPortOffset / SamplePeriodCurrent);

            //CREATE DATAPACKAGESCOPE
            p = new DataPackageScope(this.GetType(),
                                     acquisitionDepthCurrent, SamplePeriodCurrent,
                                     viewportSamples, (Int64)(ViewPortOffset / SamplePeriodCurrent),
                                     TriggerHoldoffCurrent, (Int64)(TriggerHoldoffCurrent / SamplePeriodCurrent), false, acquistionId, TriggerValue);
            p.FullAcquisitionFetchProgress = 1f;
            p.samplePeriod[ChannelDataSourceScope.Viewport] = SamplePeriodCurrent * Math.Pow(2, viewportDecimation);
            p.offset[ChannelDataSourceScope.Viewport]       = ViewPortOffset;

            //set values, needed for ETS to work properly
            if (acquisitionBufferAnalog != null && acquisitionBufferAnalog.ContainsKey(AnalogChannel.ChA))
            {
                p.samplePeriod[ChannelDataSourceScope.Overview] = SamplePeriodCurrent * (float)acquisitionBufferAnalog[AnalogChannel.ChA].Length / (float)OVERVIEW_LENGTH;
                p.offset[ChannelDataSourceScope.Overview]       = 0;
            }

            if (acquisitionBufferAnalog.Count == 0)
            {
                return(lastCommittedDataPackage);
            }

            foreach (AnalogChannel ch in channelsToAcquireDataFor)
            {
                if (logicAnalyserEnabledCurrent && ch == logicAnalyserChannelCurrent)
                {
                    continue;
                }
                if (SendOverviewBuffer)
                {
                    Array arr = DecimateViewport(acquisitionBufferAnalog[ch], 0, (int)(Math.Log(acquisitionDepthCurrent / OVERVIEW_LENGTH, 2)), OVERVIEW_LENGTH);
                    p.SetData(ChannelDataSourceScope.Overview, ch, arr);
                }
                var decimatedViewport = DecimateViewport(acquisitionBufferAnalog[ch], viewportOffsetLocal, viewportDecimation, viewportSamples);
                p.SetData(ChannelDataSourceScope.Viewport, ch, decimatedViewport);
                p.SetData(ChannelDataSourceScope.Acquisition, ch, acquisitionBufferAnalog[ch]);

                //set dummy minmax values
                p.SaturationLowValue[ch]  = float.MinValue;
                p.SaturationHighValue[ch] = float.MaxValue;

                //set 20mV as resolution, which is needed for some processors (like freqdetection). Don't go too low, as ETS uses this in its difference detector
                p.Resolution[ch] = 0.020f;
            }

            if (logicAnalyserEnabledCurrent)
            {
                if (SendOverviewBuffer)
                {
                    p.SetData(ChannelDataSourceScope.Overview, LogicAnalyserChannel.LA, DecimateViewport(acquisitionBufferDigital, 0, (int)(Math.Log(acquisitionDepthCurrent / OVERVIEW_LENGTH, 2)), OVERVIEW_LENGTH));
                }
                p.SetData(ChannelDataSourceScope.Viewport, LogicAnalyserChannel.LA, DecimateViewport(acquisitionBufferDigital, viewportOffsetLocal, viewportDecimation, viewportSamples));
                p.SetData(ChannelDataSourceScope.Acquisition, LogicAnalyserChannel.LA, acquisitionBufferDigital);
            }

            //in case of reading from file: increment to next record
            if (isFile)
            {
                (HardwareInterface as DummyInterfaceFromFile).IncrementRecord();
            }

            if (acquisitionMode == AcquisitionMode.SINGLE)
            {
                acquisitionRunning = false;
            }

            lastCommittedDataPackage = p;
            return(p);
        }
Exemple #9
0
 /// <summary>
 /// Creates a new communication channel user interface.
 /// </summary>
 public virtual ChannelView CreateChannelView(ChannelConfig channelConfig)
 {
     return(null);
 }
Exemple #10
0
 /// <summary>
 /// Creates a new communication channel.
 /// </summary>
 public override ChannelLogic CreateChannel(ILineContext lineContext, ChannelConfig channelConfig)
 {
     return(channelConfig.TypeCode == "MqttClient"
         ? new MqttClientChannelLogic(lineContext, channelConfig)
         : null);
 }
Exemple #11
0
        public async override void CheckForChange_Elapsed(object stateinfo)
        {
            try
            {
                if (VideoId == null)
                {
                    VideoId = await scrapeLivestreamId(Name);

                    //Not live
                    if (VideoId == null)
                    {
                        return;
                    }

                    //New livestream
                    else
                    {
                        while (StreamInfo == null)
                        {
                            await Task.Delay(60000);
                        }

                        ViewerGraph = new DatePlot(Name, "Time since start", "Viewers");

                        ViewerGraph.AddValue("Viewers", 0, StreamInfo.liveStreamingDetails.actualStartTime);

                        foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][ONLINE]).ToList())
                        {
                            await OnMinorChangeTracked(channel, (string)ChannelConfig[channel]["Notification"]);
                        }

                        //SetTimer(120000, 120000);

                        IconUrl = (await fetchChannel()).snippet.thumbnails.medium.url;

                        await UpdateTracker();
                    }
                }

                if (StreamInfo == null)
                {
                    await Task.Delay(120000);
                }
                bool isStreaming = StreamInfo?.snippet?.liveBroadcastContent?.Equals("live") ?? false;

                if (!isStreaming)
                {
                    await Program.MopsLog(new LogMessage(LogSeverity.Verbose, "", $"Stream went offline for {Name}, investigate please:\n{(StreamInfo != null ? JsonConvert.SerializeObject(StreamInfo) :  "Was null")}"));

                    VideoId = null;
                    //SetTimer(900000);
                    try{
                        if (ChannelConfig.Any(x => (bool)x.Value[SENDGRAPH]))
                        {
                            var png = ViewerGraph.DrawPlot(false, $"{Name}-{DateTime.UtcNow.ToString("MM-dd-yy_hh-mm")}", true);
                            foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][SENDGRAPH]).ToList())
                            {
                                await(Program.Client.GetChannel(channel) as SocketTextChannel)?.SendFileAsync(png, "Graph for personal use:");
                            }
                            File.Delete(png);
                        }
                    } catch (Exception e) {
                        await Program.MopsLog(new LogMessage(LogSeverity.Error, "", $" error sending graph by {Name}", e));
                    }

                    ViewerGraph?.Dispose();
                    ViewerGraph = null;

                    ToUpdate = new Dictionary <ulong, ulong>();

                    foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][OFFLINE]).ToList())
                    {
                        await OnMinorChangeTracked(channel, $"{StreamInfo?.snippet?.channelTitle ?? "Streamer"} went Offline!");
                    }

                    StreamInfo = null;

                    await UpdateTracker();
                }
                else
                {
                    if (ChannelConfig.Any(x => (bool)x.Value[SHOWGRAPH]))
                    {
                        if (StreamInfo.liveStreamingDetails?.concurrentViewers != null)
                        {
                            ViewerGraph.AddValue("Viewers", double.Parse(StreamInfo.liveStreamingDetails.concurrentViewers));
                        }
                        else
                        {
                            ViewerGraph.AddValue("Viewers", 0);
                        }
                        await UpdateTracker();
                    }

                    foreach (ulong channel in ChannelConfig.Keys.Where(x => (bool)ChannelConfig[x][SHOWEMBED]).ToList())
                    {
                        await OnMajorChangeTracked(channel, await createEmbed((bool)ChannelConfig[channel][THUMBNAIL], (bool)ChannelConfig[channel][SHOWCHAT], (bool)ChannelConfig[channel][SHOWGRAPH]));
                    }
                }
            }
            catch (Exception e)
            {
                await Program.MopsLog(new LogMessage(LogSeverity.Error, "", $" error by {Name}", e));
            }
        }
Exemple #12
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public ChannelLogic(ILineContext lineContext, ChannelConfig channelConfig)
 {
     LineContext   = lineContext ?? throw new ArgumentNullException(nameof(lineContext));
     ChannelConfig = channelConfig ?? throw new ArgumentNullException(nameof(channelConfig));
     Title         = channelConfig.TypeName;
 }
Exemple #13
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += (s, e) =>
            {
                if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                {
                    if (cmdCancelSource != null && !cmdCancelSource.IsCancellationRequested)
                    {
                        e.Cancel = true;
                        cmdCancelSource.Cancel();
                        Console.WriteLine("Cancelled");
                    }
                }
            };

            //TODO command line args to select channel and config
            FtdiStatus status;
            uint       channels = Channel.GetNumChannels();

            if (channels == 0)
            {
                ConsoleManager.WriteLine("No channels detected");
                return;
            }

            channel = new Channel(0);
            if (channel.IsDisposed)
            {
                ConsoleManager.WriteLine("Error initializing channel");
                return;
            }

            ChannelConfig con = new ChannelConfig(ClockRate.FastMode, 5, 0);

            status = channel.Initialize(ref con);
            if (status != FtdiStatus.Ok)
            {
                ConsoleManager.WriteLine("Error Initialize: " + status);
                return;
            }

            ConsoleManager.WriteLine("Initialized channel 0");

            //main loop
            running = true;
            while (running)
            {
                //write input string, read line
                ConsoleManager.Write("MPSSE >");
                string line = ConsoleManager.ReadLine();

                ConsoleManager.WriteCommand(line);

                //Handle user pressing enter without typing anything
                if (string.IsNullOrWhiteSpace(line))
                {
                    ConsoleManager.WriteLine("Type h or help to view a list of commands.");
                    continue;
                }

                //strip comments
                int commentIndex = line.IndexOf('#');
                if (commentIndex != -1)
                {
                    line = line.Substring(0, commentIndex);
                }

                //split into args
                string[] lineWords = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                //comment-only lines get skipped
                if (lineWords.Length == 0)
                {
                    continue;
                }

                //find the command
                Command cmd;
                if (!Commands.TryGetValue(lineWords[0], out cmd))
                {
                    ConsoleManager.WriteLine("Unknown command \"" + lineWords[0] + "\".");
                    continue;
                }

                //reset cancellation token
                cmdCancelSource = new CancellationTokenSource();

                //create task to run cmd async
                Task cmdRunTask = new Task(() => cmd.Run(lineWords), cmdCancelSource.Token);

                //run and wait for the task to complete
                cmdRunTask.Start();
                cmdRunTask.Wait(Timeout.Infinite);
            }

            //cleanly exit
            channel.Dispose();
        }
Exemple #14
0
        private void ConnectionsManagerThread()
        {
            for (; ;)
            {
                try
                {
                    byte[]   sender;
                    string[] command;
                    ArraySegment <byte>[] content;

                    {
                        var item = _receiveMessageQueue.Dequeue();

                        if (item.Key == null)
                        {
                            continue;
                        }
                        sender = item.Key;

                        if (item.Value == null)
                        {
                            continue;
                        }
                        if (item.Value.Command == null)
                        {
                            continue;
                        }
                        command = ServerManager.Split(item.Value.Command);
                        if (item.Value.Content.Array == null)
                        {
                            continue;
                        }
                        content = ServerManager.FromBuffer(item.Value.Content, _bufferManager);
                    }

                    if (this.State == ManagerState.Stop)
                    {
                        return;
                    }

                    if (command[0] == "user")
                    {
                        if (command[1] == "nick")
                        {
                        }
                        else if (command[1] == "message")
                        {
                        }
                    }
                    else if (command[0] == "channel")
                    {
                        if (command[1] == "join" && command.Length < 3)
                        {
                            var channelName = command[2];
                            if (channelName == null || channelName.Trim() == "")
                            {
                                continue;
                            }

                            var channelConfig = _settings.ChannelConfigs.FirstOrDefault(n => n.Name == channelName);

                            if (channelConfig == null)
                            {
                                channelConfig = new ChannelConfig()
                                {
                                    Name = channelName
                                };
                                _settings.ChannelConfigs.Add(channelConfig);
                            }

                            if (channelConfig.State == ChannelState.Private)
                            {
                                if (!channelConfig.Managers.Any(n => Collection.Equals(n, sender)) ||
                                    !channelConfig.Members.Any(n => Collection.Equals(n, sender)))
                                {
                                    continue;
                                }
                            }

                            _channelUsersDictionary[channelName].Add(sender);

                            foreach (byte[] id in _channelUsersDictionary[channelName])
                            {
                                using (DeadlockMonitor.Lock(_sendMessageQueue.ThisLock))
                                {
                                    if (!_sendMessageQueue.ContainsKey(id))
                                    {
                                        _sendMessageQueue[id] = new WaitQueue <IEnumerable <CommandMessage> >();
                                    }
                                }

                                _sendMessageQueue[id].Enqueue(new CommandMessage[] {
                                    new CommandMessage()
                                    {
                                        Command = string.Format("channel join \\1"),
                                        Content = ServerManager.ToBuffer(new byte[][] { id }, _bufferManager)
                                    }
                                });
                            }
                        }
                        else if (command[1] == "quit")
                        {
                        }
                        else if (command[1] == "kick")
                        {
                        }
                        else if (command[1] == "invite")
                        {
                        }
                        else if (command[1] == "message" && command.Length < 4)
                        {
                            var channelName = command[2];
                            if (channelName == null || channelName.Trim() == "")
                            {
                                continue;
                            }

                            var channelConfig = _settings.ChannelConfigs.FirstOrDefault(n => n.Name == channelName);
                            if (channelConfig == null)
                            {
                                continue;
                            }

                            if (channelConfig.State == ChannelState.Private)
                            {
                                if (!channelConfig.Managers.Any(n => Collection.Equals(n, sender)) ||
                                    !channelConfig.Members.Any(n => Collection.Equals(n, sender)))
                                {
                                    continue;
                                }
                            }

                            var channelMessage = command[3];
                            if (channelMessage == null || channelMessage.Trim() == "")
                            {
                                continue;
                            }

                            foreach (byte[] id in _channelUsersDictionary[channelName])
                            {
                                using (DeadlockMonitor.Lock(_sendMessageQueue.ThisLock))
                                {
                                    if (!_sendMessageQueue.ContainsKey(id))
                                    {
                                        _sendMessageQueue[id] = new WaitQueue <IEnumerable <CommandMessage> >();
                                    }
                                }

                                _sendMessageQueue[id].Enqueue(new CommandMessage[] {
                                    new CommandMessage()
                                    {
                                        Command = string.Format("channel message \\1 {1}", channelMessage),
                                        Content = ServerManager.ToBuffer(new byte[][] { id }, _bufferManager)
                                    }
                                });
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Exemple #15
0
 public void OnBtnClickDetail(ChannelConfig config)
 {
     ChangeCurPage(ConfigPage.detail);
     RefreshPage();
     detailpage.Init(config);
 }
Exemple #16
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

// !tempChannel
            Command newCommand = new Command("tempChannel");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Creates a temporary voice channel. This channel will be destroyed when it becomes empty, with grace period of three minutes since it's creation.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (e.Server.Config.TempChannelCategoryId == 0)
                {
                    await e.SendReplySafe("This command has to be configured on the config page (social) <https://valkyrja.app/config>");

                    return;
                }

                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}tempChannel <name>` or `{e.Server.Config.CommandPrefix}tempChannel [userLimit] <name>`");

                    return;
                }

                int           limit   = 0;
                bool          limited = int.TryParse(e.MessageArgs[0], out limit);
                StringBuilder name    = new StringBuilder();
                for (int i = limited ? 1 : 0; i < e.MessageArgs.Length; i++)
                {
                    name.Append(e.MessageArgs[i]);
                    name.Append(" ");
                }
                string responseString = string.Format(TempChannelConfirmString, name.ToString());

                try
                {
                    RestVoiceChannel tempChannel = null;
                    if (limited)
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => {
                            c.CategoryId = e.Server.Config.TempChannelCategoryId;
                            c.UserLimit  = limit;
                        });
                    }
                    else
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => c.CategoryId = e.Server.Config.TempChannelCategoryId);
                    }

                    ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    ChannelConfig channel   = dbContext.Channels.FirstOrDefault(c => c.ServerId == e.Server.Id && c.ChannelId == tempChannel.Id);
                    if (channel == null)
                    {
                        channel = new ChannelConfig {
                            ServerId  = e.Server.Id,
                            ChannelId = tempChannel.Id
                        };

                        dbContext.Channels.Add(channel);
                    }

                    channel.Temporary = true;
                    dbContext.SaveChanges();
                    dbContext.Dispose();
                }
                catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    responseString = string.Format(ErrorUnknownString, this.Client.GlobalConfig.AdminUserId);
                }
                await e.SendReplySafe(responseString);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("tmp"));
            commands.Add(newCommand.CreateAlias("tc"));

// !mentionRole
            newCommand                     = new Command("mentionRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Mention a role with a message. Use with the name of the role as the first parameter and the message will be the rest.";
            newCommand.DeleteRequest       = true;
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplyUnsafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <roleName> <message text>`");

                    return;
                }

                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = e.Server.Guild.Roles.Where(r => r.Name == e.MessageArgs[0])).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower() == e.MessageArgs[0].ToLower())).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.MessageArgs[0].ToLower()))).Any())
                {
                    await e.SendReplyUnsafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplyUnsafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role    = foundRoles.First();
                string     message = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[1]));

                await role.ModifyAsync(r => r.Mentionable = true);

                await Task.Delay(100);

                await e.SendReplySafe($"{role.Mention} {message}");

                await Task.Delay(100);

                await role.ModifyAsync(r => r.Mentionable = false);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("announce"));

// !cheatsheet
            newCommand                     = new Command("cheatsheet");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send an embed cheatsheet with various moderation commands.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation commands").WithColor(16711816).WithFields(
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}op`").WithValue("Distinguish yourself as a moderator when addressing people, and allow the use of `!mute`, `!kick` & `!ban` commands."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}mute @user(s) duration`").WithValue("Mute mentioned user(s) for `duration` (use `m`, `h` and `d`, e.g. 1h15m. This will effectively move them to the `#chill-zone` channel."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}kick @user(s) reason`").WithValue("Kick mentioned `@users` (or IDs) with specific `reason`."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}ban @user(s) duration reason`").WithValue("Ban mentioned `@users` (or IDs) for `duration` (use `h` and `d`, e.g. 1d12h, or zero `0d` for permanent) with specific `reason`."),
                    new EmbedFieldBuilder().WithName("`reason`").WithValue("Reason parameter of the above `kick` and `ban` commands is stored in the database as a _warning_ and also PMed to the user. Please provide proper descriptions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}issueWarning @user(s) message`").WithValue("The same as `addWarning`, but also PM this message to the user(s)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}addWarning @user(s) message`").WithValue("Add a `message` to the database, taking notes of peoples naughty actions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}removeWarning @user`").WithValue("Remove the last added warning from the `@user` (or ID)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}whois @user`").WithValue("Search for a `@user` (or ID, or name) who is present on the server."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}find expression`").WithValue("Search for a user using more complex search through all the past nicknames, etc... This will also go through people who are not on the server anymore."),
                    new EmbedFieldBuilder().WithName($"`whois/find`").WithValue("Both whois and find commands will return information about the user, when was their account created, when did they join, their past names and nicknames, and all the previous warnings and bans.")
                    );

                RestUserMessage msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();

                embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation guidelines").WithColor(16711816).WithDescription("for implementing the [theory](http://rhea-ayase.eu/articles/2017-04/Moderation-guidelines) in real situations.\n")
                .WithFields(
                    new EmbedFieldBuilder().WithName("__Talking to people__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Don't use threats.").WithValue("a) **Imposed consequences** - what you can do with your power (kick, ban,...) These are direct threats, avoid them.\nb) **Natural consequences** - implied effects of members actions. These can include \"the community is growing to dislike you,\" or \"see you as racist,\" etc..."),
                    new EmbedFieldBuilder().WithName("Identify what is the underlying problem.").WithValue("a) **Motivation problem** - the member is not motivated to behave in acceptable manner - is a troll or otherwise enjoys being mean to people.\nb) **Ability problem** - the member may be direct without \"filters\" and their conversation often comes off as offensive while they just state things the way they see them: http://www.mit.edu/~jcb/tact.html"),
                    new EmbedFieldBuilder().WithName("Conversation should follow:").WithValue("1) **Explain** the current situation / problem.\n2) **Establish safety** - you're not trying to ban them or discourage them from participating.\n3) **Call to action** - make sure to end the conversation with an agreement about what steps will be taken towards improvement.\n"),
                    new EmbedFieldBuilder().WithName("__Taking action__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Always log every action").WithValue("with `warnings`, and always check every member and their history."),
                    new EmbedFieldBuilder().WithName("Contents of our channels should not be disrespectful towards anyone, think about minorities.").WithValue("a) Discussion topic going wild, the use of racial/homophobic or other improper language should be pointed out with an explanation that it is not cool towards minorities within our community.\nb) A member being plain disrespectful on purpose... Mute them, see their reaction to moderation talk and act on it."),
                    new EmbedFieldBuilder().WithName("Posting or even spamming inappropriate content").WithValue("should result in immediate mute and only then followed by explaining correct behavior based on all of the above points."),
                    new EmbedFieldBuilder().WithName("Repeated offense").WithValue("a) 1d ban, 3d ban, 7d ban - are your options depending on how severe it is.\nb) Permanent ban should be brought up for discussion with the rest of the team."),
                    new EmbedFieldBuilder().WithName("Member is disrespectful to the authority.").WithValue("If you get into conflict yourself, someone is disrespectful to you as a moderator, trolling and challenging your authority - step back and ask for help, mention `@Staff` in the mod channel, and let 3rd party deal with it.")
                    );

                msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();
            };
            commands.Add(newCommand);

// !embed
            newCommand                     = new Command("embed");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Build an embed. Use without arguments for help.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage) || e.TrimmedMessage == "-h" || e.TrimmedMessage == "--help")
                {
                    await e.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
                                          "[ --channel     ] Channel where to send the embed.\n" +
                                          "[ --title       ] Short title\n" +
                                          "[ --description ] Short description\n" +
                                          "[ --color       ] #rrggbb hex color used for the embed stripe.\n" +
                                          "[ --image       ] URL of a Hjuge image in the bottom.\n" +
                                          "[ --thumbnail   ] URL of a smol image on the side.\n" +
                                          "[ --fieldName   ] Create a new field with specified name.\n" +
                                          "[ --fieldValue  ] Text value of a field - has to follow a name.\n" +
                                          "[ --fieldInline ] Use to set the field as inline.\n" +
                                          "Where you can repeat the field* options multiple times.\n```"
                                          );

                    return;
                }

                bool debug = false;
                SocketTextChannel channel      = e.Channel;
                EmbedFieldBuilder currentField = null;
                EmbedBuilder      embedBuilder = new EmbedBuilder();

                foreach (Match match in this.EmbedParamRegex.Matches(e.TrimmedMessage))
                {
                    string optionString = this.EmbedOptionRegex.Match(match.Value).Value;

                    if (optionString == "--debug")
                    {
                        if (this.Client.IsGlobalAdmin(e.Message.Author.Id) || this.Client.IsSupportTeam(e.Message.Author.Id))
                        {
                            debug = true;
                        }
                        continue;
                    }

                    if (optionString == "--fieldInline")
                    {
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldInline` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithIsInline(true);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting inline for field `{currentField.Name}`");
                        }
                        continue;
                    }

                    string value;
                    if (match.Value.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = match.Value.Substring(optionString.Length + 1).Trim()))
                    {
                        await e.SendReplySafe($"Invalid value for `{optionString}`");

                        return;
                    }

                    if (value.Length >= UserProfileOption.ValueCharacterLimit)
                    {
                        await e.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                        return;
                    }

                    switch (optionString)
                    {
                    case "--channel":
                        if (!guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = e.Server.Guild.GetTextChannel(id)) == null)
                        {
                            await e.SendReplySafe($"Channel {value} not found.");

                            return;
                        }
                        if (debug)
                        {
                            await e.SendReplySafe($"Channel set: `{channel.Name}`");
                        }

                        break;

                    case "--title":
                        embedBuilder.WithTitle(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Title set: `{value}`");
                        }

                        break;

                    case "--description":
                        embedBuilder.WithDescription(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Description set: `{value}`");
                        }

                        break;

                    case "--image":
                        embedBuilder.WithImageUrl(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Image URL set: `{value}`");
                        }

                        break;

                    case "--thumbnail":
                        embedBuilder.WithThumbnailUrl(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Thumbnail URL set: `{value}`");
                        }

                        break;

                    case "--color":
                        uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                        embedBuilder.WithColor(color);
                        if (debug)
                        {
                            await e.SendReplySafe($"Color `{value}` set.");
                        }

                        break;

                    case "--fieldName":
                        if (currentField != null && currentField.Value == null)
                        {
                            await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                            return;
                        }

                        embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
                        if (debug)
                        {
                            await e.SendReplySafe($"Creating new field `{currentField.Name}`");
                        }

                        break;

                    case "--fieldValue":
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldValue` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithValue(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
                        }

                        break;

                    default:
                        await e.SendReplySafe($"Unknown option: `{optionString}`");

                        return;
                    }
                }

                if (currentField != null && currentField.Value == null)
                {
                    await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                    return;
                }

                await channel.SendMessageAsync(embed : embedBuilder.Build());
            };
            commands.Add(newCommand);

            return(commands);
        }
Exemple #17
0
        static public void BuildForAndroid(HS_EditDefine.HS_ChannelDefine channelDefine)
        {
            LoadConfig();

            string androidPath = Application.dataPath + "/Plugins/Android";

            HS_Directory.CreateDirectory(androidPath);
            try
            {
                HS_Base.SystemDeleteFolder(androidPath);
            }
            catch (System.Exception _e)
            {
                D.LogForce("Ignore: " + _e.ToString());
            }
            string rootPath = S_RootPath;

            ChannelConfig channelConfig = S_AllChannelConfig[channelDefine.ToString()];
            string        channel       = channelConfig.channel;
            string        packerName    = channelConfig.packerName;

            HS_Base.SystemCopyDirectory(rootPath + @"/Channel/" + channel + "/Android/", androidPath);

            string lastDefineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android);

            if (!string.IsNullOrEmpty(channelConfig.defineSymbols))
            {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, channelConfig.defineSymbols);
            }
            else
            {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "");
            }
            PlayerSettings.bundleIdentifier            = packerName;
            PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
            string path = rootPath + "/Client/Android";

            HS_Directory.CreateDirectory(path);
            path += "/" + packerName + ".apk";
            //FilterEditorDLL(FilterEditorDLLModel.Assets2Backups);

            //更新SVN并且拷贝到streamingAssets
            SVNUpdate(RuntimePlatform.Android);

            BuildPipeline.BuildPlayer(GetBuildScenes(), path, BuildTarget.Android, BuildOptions.None);
            //FilterEditorDLL(FilterEditorDLLModel.Backups2Assets);
            if (!string.IsNullOrEmpty(lastDefineSymbols))
            {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, lastDefineSymbols);
            }
            RemoveSVNResources();
            AssetDatabase.Refresh();

            System.Diagnostics.Process.Start(HS_Path.GetDirectoryName(path));
            try
            {
                HS_Base.SystemDeleteFolder(androidPath);
            }
            catch (System.Exception _e)
            {
                D.LogForce("Ignore: " + _e.ToString());
            }
        }
 public AttendanceHandler(ChannelConfig channelConfig)
 {
     this.ChannelConfig = channelConfig;
 }
Exemple #19
0
 /// <summary>
 /// 设置配置信息
 /// </summary>
 /// <param name="config"></param>
 public void SetConfig(ChannelConfig config) {
     this.config = config;
 }
Exemple #20
0
        public async override void CheckForChange_Elapsed(object stateinfo)
        {
            try
            {
                var newInformation = await getResults();

                if (PastInformation == null)
                {
                    PastInformation = newInformation;
                }

                var embed = createEmbed(newInformation, PastInformation, out bool changed);
                if (changed)
                {
                    var graphMembers = newInformation.Where(x => x.Key.Contains("graph:"));

                    foreach (var graphValue in graphMembers)
                    {
                        if (DataGraph == null)
                        {
                            foreach (var graphTest in graphMembers)
                            {
                                if (!graphTest.Equals(default(KeyValuePair <string, string>)))
                                {
                                    bool succeeded = double.TryParse(graphTest.Value, out double test);
                                    var  format    = graphTest.Key.Split("->").First().Split(":").First();
                                    if (format.Contains("graph"))
                                    {
                                        format = "dd-MMM|false";
                                    }
                                    var relative = Boolean.Parse(format.Split("|").Last());
                                    if (succeeded)
                                    {
                                        var chosenName = graphTest.Key.Contains("as:") ? graphTest.Key.Split(":").Last() : graphTest.Key;
                                        if (DataGraph == null)
                                        {
                                            DataGraph = new DatePlot("JSON" + Name.GetHashCode(), "Date", "Value", format: format.Split("|").First(), relativeTime: relative, multipleLines: true);
                                        }
                                    }

                                    else
                                    {
                                        throw new Exception("Graph value is not a number!");
                                    }
                                }
                            }
                        }
                        var name = graphValue.Key.Contains("as:") ? graphValue.Key.Split(":").Last() : graphValue.Key;
                        if (!graphValue.Equals(default(KeyValuePair <string, string>)))
                        {
                            DataGraph.AddValueSeperate(name, double.Parse(PastInformation[graphValue.Key]));
                            DataGraph.AddValueSeperate(name, double.Parse(graphValue.Value));
                        }
                    }

                    foreach (var channel in ChannelConfig.Keys.ToList())
                    {
                        await OnMajorChangeTracked(channel, DataGraph == null?embed : createEmbed(newInformation, PastInformation, out changed), (string)ChannelConfig[channel]["Notification"]);
                    }
                    if (!ChannelConfig.Any(x => (bool)x.Value[UPDATEUNTILNULL]))
                    {
                        ToUpdate = new Dictionary <ulong, ulong>();
                    }

                    PastInformation = newInformation;
                    await UpdateTracker();
                }
            }
            catch (Exception e)
            {
                if (ChannelConfig.Any(x => (bool)x.Value[UPDATEUNTILNULL]) && e.Message.Contains("access child value"))
                {
                    ToUpdate  = new Dictionary <ulong, ulong>();
                    DataGraph = null;
                    await UpdateTracker();
                }
                await Program.MopsLog(new LogMessage(LogSeverity.Error, "", $" error by {Name}", e));
            }
        }
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmMqttClientChannelOptions(ChannelConfig channelConfig)
     : this()
 {
     this.channelConfig = channelConfig ?? throw new ArgumentNullException(nameof(channelConfig));
     options            = new MqttConnectionOptions(channelConfig.CustomOptions);
 }
Exemple #22
0
    public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
    {
        if (sCurBuildChannels == null)
        {
            return;
        }

        string buildPath     = Application.dataPath + "/../../Builds/";
        string outPutPath    = Path.GetDirectoryName(pathToBuiltProject);
        string outFolderName = Path.GetFileNameWithoutExtension(pathToBuiltProject);
        string tempPath      = "";

        switch (target)
        {
        case BuildTarget.Android:
            tempPath = Path.Combine(outPutPath, outFolderName);
            if (Directory.Exists(tempPath))
            {
                Directory.Delete(tempPath, true);
            }
            break;

        case BuildTarget.iOS:
            tempPath = pathToBuiltProject;
            break;

        case BuildTarget.StandaloneWindows:
            tempPath = Path.GetDirectoryName(pathToBuiltProject);
            break;
        }

        Process          p = new Process();
        ProcessStartInfo pi;

        if (target == BuildTarget.Android)
        {
            pi = new ProcessStartInfo(Application.dataPath + "/../../tools/apktool.bat", "d " + pathToBuiltProject);
            pi.WorkingDirectory = outPutPath;
            pi.UseShellExecute  = false;
            pi.CreateNoWindow   = true;
            p.StartInfo         = pi;
            p.Start();
            p.WaitForExit();

            File.Delete(pathToBuiltProject);

            string ymlPath = Path.Combine(tempPath, "apktool.yml");
            SetApktoolYmlFile(ymlPath);
        }

        string streamingDir = "";

        switch (target)
        {
        case BuildTarget.Android:
            streamingDir = tempPath + "/assets/";
            break;

        case BuildTarget.iOS:
            streamingDir = tempPath + "/Data/Raw/";
            break;

        case BuildTarget.StandaloneWindows:
            streamingDir = tempPath + "/game_Data/StreamingAssets/";
            break;
        }
        if (!Directory.Exists(streamingDir))
        {
            Directory.CreateDirectory(streamingDir);
        }

        CopyGameResources(target, streamingDir + "GameResources/", true);
        ClientBuildSettings setting = new ClientBuildSettings();

        foreach (BuildChannel buildChannel in sCurBuildChannels)
        {
            if (!buildChannel.Active)
            {
                continue;
            }

            if (!buildChannel.BuildMini)
            {
                continue;
            }

            if (!BuildProjectWindow.sChannelConfigs.ContainsKey(buildChannel.ChannelName))
            {
                UnityEngine.Debug.LogError("Build channel : " + buildChannel.ChannelName + " fail!   the ChannelConfig don't have key : " + buildChannel.ChannelName);
                continue;
            }

            ChannelConfig channelConfig = BuildProjectWindow.sChannelConfigs.GetUnit(buildChannel.ChannelName);

            if (string.IsNullOrEmpty(channelConfig.BundleID))
            {
                UnityEngine.Debug.LogError("Build channel : " + buildChannel.ChannelName + " fail!   the ChannelConfig bundleID is null!");
                continue;
            }

            if (string.IsNullOrEmpty(channelConfig.DownloadName))
            {
                UnityEngine.Debug.LogError("Build channel : " + buildChannel.ChannelName + " fail!   the ChannelConfig downloadName is null!");
                continue;
            }

            setting.SelectIp  = buildChannel.SelectIp;
            setting.Debug     = buildChannel.Debug;
            setting.MiniBuild = true;
            File.WriteAllText(streamingDir + "setting.txt", JsonMapper.ToJson(setting));

            CopyPlugins(target, buildChannel.PluginsPath);

            string miniDir = buildPath + "_" + channelConfig.DownloadName;

            if (target == BuildTarget.Android)
            {
                miniDir             = miniDir + ".apk";
                p                   = new Process();
                pi                  = new ProcessStartInfo(Application.dataPath + "/../../tools/apktool.bat", "b " + outFolderName);
                pi.WorkingDirectory = outPutPath;
                pi.UseShellExecute  = false;
                pi.CreateNoWindow   = true;
                p.StartInfo         = pi;
                p.Start();
                p.WaitForExit();

                if (File.Exists(miniDir))
                {
                    File.Delete(miniDir);
                }
                File.Move(tempPath + "/dist/" + Path.GetFileName(pathToBuiltProject), miniDir);

                p  = new Process();
                pi = new ProcessStartInfo(Application.dataPath + "/../../tools/sign.bat", miniDir.Replace("/", "\\"));
                pi.UseShellExecute = false;
                pi.CreateNoWindow  = true;
                p.StartInfo        = pi;
                p.Start();
                p.WaitForExit();
            }
            else
            {
                if (Directory.Exists(miniDir))
                {
                    Directory.Delete(miniDir, true);
                }
                FileHelper.CopyFolder(tempPath, miniDir, true);
            }
        }


        CopyGameResources(target, streamingDir + "GameResources/", false);
        foreach (BuildChannel buildChannel in sCurBuildChannels)
        {
            if (!buildChannel.Active)
            {
                continue;
            }

            if (!buildChannel.BuildAll)
            {
                continue;
            }

            if (!BuildProjectWindow.sChannelConfigs.ContainsKey(buildChannel.ChannelName))
            {
                UnityEngine.Debug.LogError("Build channel : " + buildChannel.ChannelName + " fail!   the ChannelConfig don't have key : " + buildChannel.ChannelName);
                continue;
            }

            ChannelConfig channelConfig = BuildProjectWindow.sChannelConfigs.GetUnit(buildChannel.ChannelName);

            if (string.IsNullOrEmpty(channelConfig.BundleID))
            {
                UnityEngine.Debug.LogError("Build channel : " + buildChannel.ChannelName + " fail!   the ChannelConfig bundleID is null!");
                continue;
            }

            if (string.IsNullOrEmpty(channelConfig.DownloadName))
            {
                UnityEngine.Debug.LogError("Build channel : " + buildChannel.ChannelName + " fail!   the ChannelConfig downloadName is null!");
                continue;
            }

            setting.SelectIp  = buildChannel.SelectIp;
            setting.Debug     = buildChannel.Debug;
            setting.MiniBuild = false;
            File.WriteAllText(streamingDir + "setting.txt", JsonMapper.ToJson(setting));

            CopyPlugins(target, buildChannel.PluginsPath);

            string allDir = buildPath + channelConfig.DownloadName;

            if (target == BuildTarget.Android)
            {
                allDir = allDir + ".apk";
                p      = new Process();
                pi     = new ProcessStartInfo(Application.dataPath + "/../../tools/apktool.bat", "b " + outFolderName);
                pi.WorkingDirectory = outPutPath;
                pi.UseShellExecute  = false;
                pi.CreateNoWindow   = true;
                p.StartInfo         = pi;
                p.Start();
                p.WaitForExit();

                if (File.Exists(allDir))
                {
                    File.Delete(allDir);
                }
                File.Move(tempPath + "/dist/" + Path.GetFileName(pathToBuiltProject), allDir);

                p  = new Process();
                pi = new ProcessStartInfo(Application.dataPath + "/../../tools/sign.bat", allDir.Replace("/", "\\"));
                pi.UseShellExecute = false;
                pi.CreateNoWindow  = true;
                p.StartInfo        = pi;
                p.Start();
                p.WaitForExit();
            }
            else
            {
                if (Directory.Exists(allDir))
                {
                    Directory.Delete(allDir, true);
                }
                FileHelper.CopyFolder(tempPath, allDir, true);
            }
        }

        Directory.Delete(tempPath, true);
    }
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmUdpChannelOptions(ChannelConfig channelConfig)
     : this()
 {
     this.channelConfig = channelConfig ?? throw new ArgumentNullException(nameof(channelConfig));
     options            = new UdpChannelOptions(channelConfig.CustomOptions);
 }
Exemple #24
0
 /// <summary>
 /// ChannelConfig
 /// </summary>
 /// <param name="config"></param>
 /// <returns></returns>
 public TBootstrap Config(ChannelConfig config)
 {
     this.ChannelConfig = config;
     return((TBootstrap)this);
 }
 public static extern FTDI.FT_STATUS SPI_InitChannel(IntPtr handle, ChannelConfig config);
Exemple #26
0
 private void SetConfig_Compile(ChannelConfig config, BuildTarget target, BuildCfg cfg)
 {
     Debug.Log("SetConfig_Compile");
     Tools.WriteChannelConst(config);
     Tools.AddScriptingDefineSymbols(config.DefineSymbol);
 }
Exemple #27
0
        static async Task RunExample()
        {
            var config = new ChannelConfig
            {
                ReceiveTimeout = TimeSpan.FromSeconds(20),
                SendTimeout    = TimeSpan.FromSeconds(20)
            };

            var host = new ServiceHost <Service>(9091);

            host.AddContract <IService>(config);

            host.ServiceInstantiated += s =>
            {
                //construct the created instance
            };

            await host.Open();

            var client = await ChannelFactory <IService> .CreateProxy("localhost", 9091, config, true);

            using ((IClientChannel)client)
            {
                var str = await client.Echo("message");

                Console.WriteLine(str);

                var msg = new Msg {
                    Id = 1, Body = "From Client"
                };
                var result = await client.EchoMsg(msg);

                Console.WriteLine(result.Body);

                var msg1 = new Msg {
                    Body = "M1"
                };
                var msg2 = new Msg {
                    Body = "M2"
                };

                var multiParams = await client.EchoMany(msg1, msg2, "hello world", -123);

                Console.WriteLine(multiParams.Body);

                var noParam = await client.EchoNoParam();

                Console.WriteLine(noParam);

                //try
                //{
                //    var err = await client.EchoServerError();
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex.Message);
                //}
            }

            //client = await ChannelFactory<IService>.CreateProxy("localhost", 9091, config);
            //var channel = (IClientChannel)client;

            //await channel.Open();


            //await channel.Close();

            Console.ReadLine();
        }
Exemple #28
0
 public void RevertSimulate(ChannelConfig config, BuildTarget target, BuildCfg cfg)
 {
     _config = config;
     RevertConfig();
     RemovePlugin(config, target, cfg);
 }
 public static void Configure(this TcpClient client, ChannelConfig channelConfig)
 {
     client.Client.Configure(channelConfig);
 }
Exemple #30
0
 public static ChannelConfiguration Create(ChannelConfig channel)
 {
     return(channel.ChannelConnection == ChannelConnection.Local ?
            BuildLocalChannel(channel) : BuildCloudChannel(channel));
 }