Пример #1
0
        public static PluginAssemblyLoadContext CreateAssemblyLoadContext(IServiceCollection services)
        {
            var context     = new PluginAssemblyLoadContext(Assemblies);
            var rpcCommands = new Dictionary <string, RpcData>();

            foreach (var info in Assemblies.Where(i => i.AutoLoad))
            {
                var assembly = context.LoadFromInfo(info);

                foreach (var type in assembly.GetTypes().Where(t => typeof(IEventListener).IsAssignableFrom(t)))
                {
                    services.AddScoped(typeof(IEventListener), type);
                }

                foreach (var type in assembly.GetTypes().Where(t => typeof(IRpcListener).IsAssignableFrom(t)))
                {
                    services.AddScoped(type);

                    foreach (var rpcData in RpcData.FromType(type))
                    {
                        // TODO: Check if command already exists.
                        rpcCommands.Add(rpcData.Name, rpcData);
                    }
                }
            }

            services.AddSingleton(new RpcRegistry(new ReadOnlyDictionary <string, RpcData>(rpcCommands)));

            return(context);
        }
Пример #2
0
        static async Task Test001Client(string[] args)
        {
            try
            {
                using (var bd = new BatchDisposable())
                {
                    var client = new RpcClient("StreamedNetTcpRpcEndpoint", "net.tcp://localhost:8834/_000WcfStreamService.RPCInvoke.Rpc");
                    bd.Add(() => (client as IDisposable)?.Dispose());

                    RpcData param = new RpcData()
                    {
                        Data1      = "client",
                        StreamData = new MemoryStream()
                    };
                    bd.Add(() => param.StreamData?.Dispose());

                    RpcData ret = await client.InvokeAsync(param.Data1, param.Data2, param.DataLen, param.DataOffset, param.EnumId, param.Flags, param.StreamData);

                    bd.Add(() => ret.StreamData?.Dispose());

                    Console.WriteLine();
                }
            }
            catch (System.Exception ex)
            {
                CommonHelpers.PrintException(ex, Console.Out, true);
            }
        }
Пример #3
0
        private async Task DownloadModule(RpcData rpcData,
                                          string courseDirectory,
                                          int moduleCounter, Module module)
        {
            var    moduleDirectory = CreateModuleDirectory(courseDirectory, moduleCounter, module.Title);
            var    course          = rpcData.Payload.Course;
            var    clipCounter     = 0;
            string referrer        =
                $"https://{Properties.Settings.Default.SiteHostName}/player?course={course.Name}&author={module.Author}&name={module.Name}&clip={clipCounter - 1}&mode=live";

            HttpHelper httpHelper = new HttpHelper
            {
                AcceptEncoding = string.Empty,
                AcceptHeader   = AcceptHeader.All,
                ContentType    = ContentType.AppJsonUtf8,
                Cookies        = Cookies,
                Referrer       = new Uri(referrer),
                UserAgent      = _userAgent
            };

            foreach (var clip in module.Clips)
            {
                ++clipCounter;
                var postJson = BuildViewclipPostDataJson(rpcData, moduleCounter, clipCounter);

                var fileName = GetFullFileNameWithoutExtension(clipCounter, moduleDirectory, clip);

                if (!File.Exists($"{fileName}.{Properties.Settings.Default.ClipExtensionMp4}"))
                {
                    ResponseEx viewclipResonse = await httpHelper.SendRequest(HttpMethod.Post,
                                                                              new Uri(Properties.Settings.Default.ViewClipUrl),
                                                                              postJson,
                                                                              Properties.Settings.Default.RetryOnRequestFailureCount, _token);

                    if (viewclipResonse.Content == "Unauthorized")
                    {
                        throw new UnauthorizedException(Properties.Resources.CheckYourSubscription);
                    }

                    var clipFile = Newtonsoft.Json.JsonConvert.DeserializeObject <ClipFile>(viewclipResonse.Content);

                    if (rpcData.Payload.Course.CourseHasCaptions)
                    {
                        string unformattedSubtitlesJson = await _subtitleService.DownloadAsync(httpHelper, module.Author, clipCounter - 1, module.Name, _token);

                        Caption[]         unformattedSubtitles = Newtonsoft.Json.JsonConvert.DeserializeObject <Caption[]>(unformattedSubtitlesJson);
                        IList <SrtRecord> formattedSubtitles   = GetFormattedSubtitles(unformattedSubtitles, clip.Duration);
                        _subtitleService.Write($"{fileName}.{Properties.Settings.Default.SubtitilesExtensionMp4}", formattedSubtitles);
                    }

                    await DownloadClip(new Uri(clipFile.Urls[1].Url),
                                       fileName,
                                       clipCounter,
                                       rpcData.Payload.Course.Modules.Sum(m => m.Clips.Length));
                }
            }
        }
 public void PublishRpc(PublishOptions options)
 {
     using var rpcData = new RpcData(Factory, options.Headers);
     rpcData.Channel.BasicPublish(
         "",
         options.TargetQueue,
         rpcData.BasicProperties,
         Encoding.UTF8.GetBytes(options.Message));
 }
Пример #5
0
    void OnEquip(int weapon)
    {
        _isEquiping = true;
        var rpc = new RpcData()
        {
            Type = GameConst.RpcEquip, Data = weapon
        };

        MessageBroker.Default.Publish(rpc);
    }
Пример #6
0
        private string BuildViewclipCaptionData(RpcData rpcData, int moduleCounter, int clipCounter)
        {
            Module module = rpcData.Payload.Course.Modules[moduleCounter - 1];
            ViewclipCaptionData viewclipData = new ViewclipCaptionData()
            {
                Author     = module.Author,
                ClipIndex  = clipCounter - 1,
                Locale     = Properties.Settings.Default.EnglishLocale,
                ModuleName = module.Name
            };

            return(Newtonsoft.Json.JsonConvert.SerializeObject(viewclipData));
        }
Пример #7
0
        public async Task DownloadAsync(string productId,
                                        IProgress <CourseDownloadingProgressArguments> downloadingProgress,
                                        IProgress <int> timeoutProgress,
                                        CancellationToken token)
        {
            _timeoutProgress           = timeoutProgress;
            _courseDownloadingProgress = downloadingProgress;
            _token = token;

            var     rpcUri  = Properties.Settings.Default.RpcUri;
            RpcData rpcData = await GetDeserialisedRpcData(rpcUri, productId, _token);

            await DownloadCourse(rpcData);
        }
        public T PublishRpc <T>(PublishOptions options)
        {
            using var rpcData = new RpcData(Factory, options.Headers);
            rpcData.Channel.BasicPublish(
                "",
                options.TargetQueue,
                rpcData.BasicProperties,
                Encoding.UTF8.GetBytes(options.Message));

            rpcData.Channel.BasicConsume(rpcData.Consumer, rpcData.ReplyQueueName, true);
            var received = rpcData.ResponseQueue.Take();

            return(JsonConvert.DeserializeObject <T>(received));
        }
Пример #9
0
    void OnReload()
    {
        if (_data.MagCount < 1)
        {
            return;
        }
        _isReloading = true;
        var rpc = new RpcData()
        {
            Type = GameConst.RpcReload
        };

        MessageBroker.Default.Publish(rpc);
    }
 private void OnControllerColliderHit(ControllerColliderHit hit)
 {
     if (hit.transform.root.CompareTag(GameConst.TagPickup))
     {
         var view = hit.transform.root.GetComponent <Photon.Pun.PhotonView>();
         if (view != null)
         {
             var rpc = new RpcData()
             {
                 Type = GameConst.RpcPickup, Data = view
             };
             MessageBroker.Default.Publish(rpc);
         }
     }
 }
Пример #11
0
    void OnShoot()
    {
        if (_data.BulletCount < 1)
        {
            Audio.clip = NoBulletSound;
            Audio.Play();
            return;
        }
        _shootTimer = _data.FireRate;
        var rpc = new RpcData()
        {
            Type = GameConst.RpcShoot
        };

        MessageBroker.Default.Publish(rpc);
    }
        private async Task DownloadCourse(RpcData rpcData)
        {
            string destinationFolder = _configProvider.DownloadsPath;

            var course = rpcData.Payload.Course;

            _timeoutBetweenClipDownloadingTimer.Elapsed += OnTimerElapsed;

            var courseDirectory = CreateCourseDirectory(GetBaseCourseDirectoryName(destinationFolder, course.Title));

            try
            {
                var moduleCounter = 0;
                foreach (var module in course.Modules)
                {
                    ++moduleCounter;
                    await DownloadModule(rpcData, courseDirectory, moduleCounter, module);
                }

                _lastFinishedMessageComposer.SetState(1);
            }
            catch (OperationCanceledException)
            {
                _lastFinishedMessageComposer.SetState(2);
            }
            catch (Exception ex)
            {
                _lastFinishedMessageComposer.SetState(3);
            }
            finally
            {
                var progressArgs = new CourseDownloadingProgressArguments
                {
                    ClipName       = string.Empty,
                    CourseProgress = 0,
                    ClipProgress   = 0
                };
                _timeoutBetweenClipDownloadingTimer.Elapsed -= OnTimerElapsed;
                _courseDownloadingProgress.Report(progressArgs);
                if (_timeoutBetweenClipDownloadingTimer != null)
                {
                    _timeoutBetweenClipDownloadingTimer.Enabled = false;
                }
                _timeoutProgress.Report(0);
            }
        }
Пример #13
0
        public async Task <string> GetTableOfContentAsync(string productId, CancellationToken token)
        {
            var           rpcUri         = Properties.Settings.Default.RpcUri;
            StringBuilder tableOfContent = new StringBuilder();
            RpcData       rpcData        = await GetDeserialisedRpcData(rpcUri, productId, token);

            foreach (var module in rpcData.Payload.Course.Modules)
            {
                tableOfContent.AppendLine($"{module.Title} {module.FormattedDuration}");
                foreach (var clip in module.Clips)
                {
                    tableOfContent.AppendLine($" {clip.Title}  {clip.FormattedDuration}");
                }
                tableOfContent.AppendLine();
            }
            return(tableOfContent.ToString());
        }
Пример #14
0
        private string BuildViewclipPostDataJson(RpcData rpcData, int moduleCounter, int clipCounter)
        {
            Module           module       = rpcData.Payload.Course.Modules[moduleCounter - 1];
            ViewclipPostData viewclipData = new ViewclipPostData()
            {
                Author          = module.Author,
                IncludeCaptions = rpcData.Payload.Course.CourseHasCaptions,
                ClipIndex       = clipCounter - 1,
                CourseName      = rpcData.Payload.Course.Name,
                Locale          = Properties.Settings.Default.EnglishLocale,
                ModuleName      = module.Name,
                MediaType       = Properties.Settings.Default.ClipExtensionMp4,
                Quality         = rpcData.Payload.Course.SupportsWideScreenVideoFormats ? Properties.Settings.Default.Resolution1280x720 : Properties.Settings.Default.Resolution1024x768
            };

            return(Newtonsoft.Json.JsonConvert.SerializeObject(viewclipData));
        }
Пример #15
0
        private void HandleReport(object sender, RpcData rpcData)
        {
            var report = rpcData.GetData(AppInfo.PluginManager);

            tabletVisualizer.SetData(rpcData);

            if (report is IDeviceReport deviceReport)
            {
                reportPeriod += (stopwatch.Restart().TotalMilliseconds - reportPeriod) / 10.0f;
                reportRateBox.Update($"{(uint)(1000 / reportPeriod)}hz");

                string formatted = ReportFormatter.GetStringFormat(deviceReport);
                tabletBox.Update(formatted);

                string raw = ReportFormatter.GetStringRaw(deviceReport);
                rawTabletBox.Update(raw);
            }
        }
        public async Task DownloadAsync(string productId,
                                        IProgress <CourseDownloadingProgressArguments> downloadingProgress,
                                        IProgress <int> timeoutProgress,
                                        CancellationToken token,
                                        PluralsightMainViewModel.LastFinishedMessageComposer lastFinishedMessage)
        {
            _timeoutProgress           = timeoutProgress;
            _courseDownloadingProgress = downloadingProgress;
            _token = token;

            _lastFinishedMessageComposer = lastFinishedMessage;
            _lastFinishedMessageComposer.SetState(0);

            var     rpcUri  = Properties.Settings.Default.RpcUri;
            RpcData rpcData = await GetDeserialisedRpcData(rpcUri, productId, _token);

            await DownloadCourse(rpcData);
        }
        private async Task <RpcData> GetDeserialisedRpcData(string rpcUri, string productId, CancellationToken token)
        {
            var httpHelper = new HttpHelper
            {
                AcceptHeader   = AcceptHeader.JsonTextPlain,
                AcceptEncoding = string.Empty,
                ContentType    = ContentType.AppJsonUtf8,
                Cookies        = Cookies,
                Referrer       = new Uri($"https://{Properties.Settings.Default.SiteHostName}"),
                UserAgent      = _userAgent
            };
            var courseRespone = await httpHelper.SendRequest(HttpMethod.Get, new Uri($"https://app.pluralsight.com/learner/content/courses/{productId}"), "", Properties.Settings.Default.RetryOnRequestFailureCount, token);

            CourseRpc courseRpc = JsonConvert.DeserializeObject <CourseRpc>(courseRespone.Content);

            var graphQlRequest    = GraphQl.GetCourseExtraInfoRequest(productId);
            var extraInfoResponse =
                await httpHelper.SendRequest(HttpMethod.Post,
                                             new Uri($"https://{Properties.Settings.Default.SiteHostName}/player/api/graphql"), graphQlRequest,
                                             Properties.Settings.Default.RetryOnRequestFailureCount, token);

            dynamic courseExtraInfo = JsonConvert.DeserializeObject <ExpandoObject>(extraInfoResponse.Content, new ExpandoObjectConverter());

            courseRpc.CourseHasCaptions = courseExtraInfo.data.rpc.bootstrapPlayer.extraInfo.courseHasCaptions;
            courseRpc.SupportsWideScreenVideoFormats = courseExtraInfo.data.rpc.bootstrapPlayer.extraInfo.supportsWideScreenVideoFormats;

            courseRpc.Modules.ToList().ForEach(m => m.Name = m.Id?.Substring(m.Id.LastIndexOf('|') + 1));

            var r = new RpcData
            {
                Payload = new PayloadRpc
                {
                    Course = courseRpc
                }
            };

            return(r);
        }
Пример #18
0
        private async Task DownloadCourse(RpcData rpcData)
        {
            string destinationFolder = _configProvider.DownloadsPath;

            var course = rpcData.Payload.Course;

            _timer.Elapsed += OnTimerElapsed;

            var courseDirectory = CreateCourseDirectory(GetBaseCourseDirectoryName(destinationFolder, course.Title));

            try
            {
                var moduleCounter = 0;
                foreach (var module in course.Modules)
                {
                    ++moduleCounter;
                    await DownloadModule(rpcData, courseDirectory, moduleCounter, module);
                }
            }
            finally
            {
                var progressArgs = new CourseDownloadingProgressArguments
                {
                    ClipName       = string.Empty,
                    CourseProgress = 0,
                    ClipProgress   = 0
                };
                _timer.Elapsed -= OnTimerElapsed;
                _courseDownloadingProgress.Report(progressArgs);
                if (_timer != null)
                {
                    _timer.Enabled = false;
                }
                _timeoutProgress.Report(0);
            }
        }
Пример #19
0
 public void SetData(RpcData data) => this.data           = data;
        private async Task DownloadModule(RpcData rpcData,
                                          string courseDirectory,
                                          int moduleCounter, Module module)
        {
            var    moduleDirectory = CreateModuleDirectory(courseDirectory, moduleCounter, module.Title);
            var    course          = rpcData.Payload.Course;
            var    clipCounter     = 0;
            string referrer        =
                $"https://{Properties.Settings.Default.SiteHostName}/player?course={course.Name}&author={module.Author}&name={module.Name}&clip={clipCounter - 1}&mode=live";

            HttpHelper httpHelper = new HttpHelper
            {
                AcceptEncoding = string.Empty,
                AcceptHeader   = AcceptHeader.All,
                ContentType    = ContentType.AppJsonUtf8,
                Cookies        = Cookies,
                Referrer       = new Uri(referrer),
                UserAgent      = _userAgent
            };

            foreach (var clip in module.Clips)
            {
                ++clipCounter;

                var s = GraphQl.GetClipsRequest(course, module, clipCounter - 1);

                var clipUrlResponse =
                    await httpHelper.SendRequest(HttpMethod.Post,
                                                 new Uri($"https://{Properties.Settings.Default.SiteHostName}/player/api/graphql"),
                                                 s,
                                                 Properties.Settings.Default.RetryOnRequestFailureCount, _token);

                dynamic courseExtraInfo = JsonConvert.DeserializeObject <ExpandoObject>(clipUrlResponse.Content, new ExpandoObjectConverter());

                dynamic courseUrl;
                try
                {
                    courseUrl = courseExtraInfo.data.viewClip.urls[0].url;
                }
                catch (Exception e)
                {
                    var a = 42;
                    throw;
                }


                var fileName = GetFullFileNameWithoutExtension(clipCounter, moduleDirectory, clip);

                if (!File.Exists($"{fileName}.{Properties.Settings.Default.ClipExtensionMp4}"))
                {
                    if (rpcData.Payload.Course.CourseHasCaptions)
                    {
                        string unformattedSubtitlesJson =
                            await _subtitleService.DownloadAsync(httpHelper, course.GetAuthorNameId(module.AuthorId), clipCounter - 1, module.ModuleId, clip.PureId, _token);

                        Caption[] unformattedSubtitles =
                            unformattedSubtitlesJson != "{\"message\":\"An error has occurred.\"}"
                                ? JsonConvert.DeserializeObject <Caption[]>(unformattedSubtitlesJson)
                                : new Caption[] { };
                        IList <SrtRecord> formattedSubtitles =
                            unformattedSubtitles.Any()
                                ? GetFormattedSubtitles(unformattedSubtitles, clip.Duration)
                                : new List <SrtRecord>();
                        _subtitleService.Write($"{fileName}.{Properties.Settings.Default.SubtitilesExtensionMp4}", formattedSubtitles);
                    }

                    await DownloadClip(
                        new Uri(courseUrl),
                        fileName,
                        clipCounter,
                        rpcData.Payload.Course.Modules.Sum(m => m.Clips.Length));
                }
            }
        }
Пример #21
0
 //Recieving
 static void GetRpc(RpcData rpc)
 {
     NetScript inst = NetScript.Find(rpc.sceneId);
     if (inst != null) {
         inst.RecieveRpc(rpc);
     } else {
         Debug.LogError(string.Format("NetScript {0} not found when trying to call {1}.", rpc.sceneId, rpc.methodId));
     }
 }
Пример #22
0
    //Recieving
    public void RecieveRpc(RpcData rpc)
    {
        MethodInfo m = rpcs[rpc.methodId];
        InputCommandAttribute attr = null;

        foreach (Attribute a in m.GetCustomAttributes(true)) {
            if (a is RpcServerAttribute && !backstab.IsServer) {
                Debug.LogError("Can't recieve server Rpcs if not the server. " +m.Name);
                return;
            }
            if (a is RpcClientsAttribute && !backstab.IsClient) {
                Debug.LogError("Can't recieve client Rpcs if not a client. " +m.Name);
                return;
            }
            if (a is InputCommandAttribute && backstab.IsServer) {
                attr = (a as InputCommandAttribute);
            }
        }

        try {
            m.Invoke(this, rpc.args);
        } catch (TargetParameterCountException e) {
            Debug.LogError(e.GetType().ToString() + " when attempting to call " +m.Name + " Expected " +m.GetParameters().Length + " parameters; Actual " +rpc.args.Length);
        } catch (Exception e) {
            Debug.LogError(e.GetType().ToString() + " when attempting to call " +m.Name);
            Debug.LogError(e.ToString());
        }

        if (attr != null) {
            RpcClients(rpc.methodId, attr.qosType, rpc.args);
        }
    }