コード例 #1
0
ファイル: MainForm.cs プロジェクト: ralph00/LoLNotes
 void GetGeneral()
 {
     try
     {
         using (var wc = new WebClient())
         {
             string raw  = wc.DownloadString("https://raw.github.com/bladecoding/LoLNotes/master/General.txt");
             var    json = JsonConvert.DeserializeObject <JObject>(raw);
             FInvoke(delegate
             {
                 SetChanges(json["Changes"] as JObject);
                 SetRelease(json["Release"] as JObject);
                 SetNews(json["News"] as JObject);
             });
         }
     }
     catch (JsonReaderException jre)
     {
         StaticLogger.Warning(jre);
     }
     catch (WebException we)
     {
         StaticLogger.Warning(we);
     }
 }
コード例 #2
0
        public bool Uninstall()
        {
            try
            {
                var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.MaxAllowed);
                foreach (var cert in Certificates)
                {
                    if (!store.Certificates.Contains(cert))
                    {
                        continue;
                    }
                    store.Remove(cert);
                }
                store.Close();

                return(true);
            }
            catch (SecurityException se)
            {
                StaticLogger.Warning(se);
            }
            catch (Exception e)
            {
                StaticLogger.Error("Failed to uninstall " + e);
            }

            return(false);
        }
コード例 #3
0
        public bool Uninstall()
        {
            try
            {
                var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.MaxAllowed);
                foreach (var cert in Certificates)
                {
                    X509Certificate2 storeCert;
                    while ((storeCert = FindCertificateByCommonName(store.Certificates, cert)) != null)
                    {
                        store.Remove(storeCert);
                    }
                }
                store.Close();

                return(true);
            }
            catch (SecurityException se)
            {
                StaticLogger.Warning(se);
            }
            catch (Exception e)
            {
                StaticLogger.Error("Failed to uninstall " + e);
            }

            return(false);
        }
コード例 #4
0
ファイル: MainForm.cs プロジェクト: ralph00/LoLNotes
 private void InstallButton_Click(object sender, EventArgs e)
 {
     if (!Wow.IsAdministrator)
     {
         MessageBox.Show("You must run LoLNotes as admin to install/uninstall it");
         return;
     }
     try
     {
         if (Installer.IsInstalled)
         {
             Installer.Uninstall();
         }
         else
         {
             Installer.Uninstall();
             Installer.Install();
         }
     }
     catch (UnauthorizedAccessException uaex)
     {
         MessageBox.Show("Unable to fully install/uninstall. Make sure LoL is not running.");
         StaticLogger.Warning(uaex);
     }
     InstallButton.Text = Installer.IsInstalled ? "Uninstall" : "Install";
     UpdateIcon();
 }
コード例 #5
0
ファイル: MainForm.cs プロジェクト: manciuszz/LoLNotes
        private void MainForm_Shown(object sender, EventArgs e)
        {
            SetTitle("(Checking)");
            Task.Factory.StartNew(GetGeneral);
            TrackingQueue.Enqueue("startup");

            Settings_Loaded(this, new EventArgs());
            UpdateIcon();

            //Add this after otherwise it will save immediately due to RegionList.SelectedIndex
            Settings.PropertyChanged += Settings_PropertyChanged;

            //Start after the form is shown otherwise Invokes will fail
            Connection.Start();
            Injector.Start();
            launcher.Start();

            //Fixes the team controls size on start as they keep getting messed up in the WYSIWYG
            MainForm_Resize(this, new EventArgs());

            try
            {
                var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "lolbans", "LoLLoader.dll");
                if (File.Exists(filename))
                {
                    StaticLogger.Info("Uninstalling old loader");

                    var shortfilename = AppInit.GetShortPath(filename);

                    var dlls = AppInit.AppInitDlls32;
                    if (dlls.Contains(shortfilename))
                    {
                        dlls.Remove(AppInit.GetShortPath(shortfilename));
                        AppInit.AppInitDlls32 = dlls;
                    }

                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                }
            }
            catch (SecurityException se)
            {
                StaticLogger.Warning(se);
            }
            catch (Exception ex)
            {
                StaticLogger.Error("Failed to uninstall " + ex);
            }
        }
コード例 #6
0
ファイル: PlayerCommands.cs プロジェクト: Elophant/Client
        /// <summary>
        /// Used to invoke a service which you don't know what it returns.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="operation"></param>
        /// <param name="args"></param>
        /// <returns>ASObject body</returns>
        public object InvokeServiceUnknown(string service, string operation, params object[] args)
        {
            var msg = new RemotingMessage();

            msg.operation   = operation;
            msg.destination = service;
            msg.headers["DSRequestTimeout"] = 60;
            msg.headers["DSId"]             = RtmpUtil.RandomUidString();
            msg.headers["DSEndpoint"]       = "my-rtmps";
            msg.body      = args;
            msg.messageId = RtmpUtil.RandomUidString();

            string endpoint = service + "." + operation;

            var result = Host.Call(msg);

            if (result == null)
            {
                StaticLogger.Warning(string.Format("Invoking {0} returned null", endpoint));
                return(null);
            }

            if (RtmpUtil.IsError(result))
            {
                var error       = RtmpUtil.GetError(result);
                var errordetail = error != null && error.faultDetail != null?string.Format(" [{0}]", error.faultDetail) : "";

                var errorstr = error != null && error.faultString != null?string.Format(", {0}", error.faultString) : "";

                StaticLogger.Warning(string.Format(
                                         "{0} returned an error{1}{2}",
                                         endpoint,
                                         errorstr,
                                         errordetail
                                         ));
                return(null);
            }

            var body = RtmpUtil.GetBodies(result).FirstOrDefault();

            if (body == null)
            {
                StaticLogger.Debug(endpoint + " RtmpUtil.GetBodies returned null");
                return(null);
            }

            return(body.Item1);
        }
コード例 #7
0
 protected void CheckLoop()
 {
     while (CheckThread != null)
     {
         if (CurrentProcess == null || CurrentProcess.HasExited)
         {
             IsInjected     = false;
             CurrentProcess = Process.GetProcessesByName(ProcessName).FirstOrDefault();
             if (CurrentProcess != null)
             {
                 try
                 {
                     Inject();
                     IsInjected = true;
                 }
                 catch (FileNotFoundException fe)
                 {
                     //LoLClient does not have ws2_32 yet. Lets try again in 1 second.
                     StaticLogger.Trace(fe.Message);
                     CurrentProcess = null;
                     Thread.Sleep(1000);
                     continue;
                 }
                 catch (WarningException we)
                 {
                     IsInjected = true;
                     StaticLogger.Info(we.Message);
                 }
                 catch (NotSupportedException nse)
                 {
                     StaticLogger.Warning(nse);
                 }
                 catch (Exception ex)
                 {
                     StaticLogger.Error(new Exception(string.Format("{0} [{1}]", ex.Message, From), ex));
                 }
             }
         }
         Thread.Sleep(500);
     }
 }
コード例 #8
0
ファイル: MainForm.cs プロジェクト: manciuszz/LoLNotes
        private void RegionList_SelectedIndexChanged(object sender, EventArgs e)
        {
            LeagueRegion region;

            if (!LeagueRegion.TryParse(RegionList.SelectedItem.ToString(), out region))
            {
                StaticLogger.Warning("Unknown enum " + RegionList.SelectedItem);
                return;
            }

            Settings.Region = region;

            var cert = Certificates.FirstOrDefault(kv => kv.Key == Settings.Region).Value;

            if (cert == null)
            {
                cert = Certificates.First().Value;
            }

            Connection.ChangeRemote(cert.Domain, cert.Certificate);
        }
コード例 #9
0
ファイル: MainForm.cs プロジェクト: ralph00/LoLNotes
 void TrackingQueue_Process(object sender, ProcessQueueEventArgs <string> e)
 {
     try
     {
         var hr = (HttpWebRequest)WebRequest.Create("http://bit.ly/unCoIY");
         hr.ServicePoint.Expect100Continue = false;
         hr.UserAgent         = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0";
         hr.Referer           = string.Format("http://lolnotes-{0}-app.org/{1}", Version, e.Item);
         hr.AllowAutoRedirect = false;
         using (var resp = (HttpWebResponse)hr.GetResponse())
         {
         }
     }
     catch (WebException we)
     {
         StaticLogger.Warning(we);
     }
     catch (Exception ex)
     {
         StaticLogger.Warning(ex);
     }
 }
コード例 #10
0
ファイル: RtmpsProxyClient.cs プロジェクト: Elophant/Client
        protected override void OnSend(byte[] buffer, int idx, int len)
        {
            if (postbuffer != null)
            {
                postbuffer.Append(buffer, idx, len);
                if (postbuffer.Length > 4)
                {
                    int num = postbuffer.GetInt();
                    postbuffer.Dispose();
                    postbuffer = null;
                    if (num == 0x504f5354)
                    {
                        StaticLogger.Trace(string.Format("Rejecting POST request", len));
                        Stop();
                        return;
                    }
                }
            }

            StaticLogger.Trace(string.Format("Send {0} bytes", len));

            if (logtofiles)
            {
                using (var fs = File.Open("realsend.dmp", FileMode.Append, FileAccess.Write))
                {
                    fs.Write(buffer, idx, len);
                }
            }

            sendbuffer.Append(buffer, idx, len);

            var objs = RtmpProtocolDecoder.DecodeBuffer(sourcecontext, sendbuffer);

            if (objs != null)
            {
                foreach (var obj in objs)
                {
                    var pck = obj as RtmpPacket;
                    if (pck != null)
                    {
                        var inv = pck.Message as Notify;
                        if (inv != null)
                        {
                            lock (InvokeList)
                            {
                                InvokeList.Add(inv);
                            }
                            StaticLogger.Trace(
                                string.Format("Call {0}({1}) (Id:{2})",
                                              inv.ServiceCall.ServiceMethodName,
                                              string.Join(", ", inv.ServiceCall.Arguments.Select(o => o.ToString())),
                                              pck.Header.ChannelId
                                              )
                                );
                        }
                        else
                        {
                            StaticLogger.Trace(string.Format("Sent {0} (Id:{1})", pck.Message.GetType(), pck.Header.ChannelId));
                        }
                    }
                    else if (obj is ByteBuffer)
                    {
                        //Just handshakes, ignore
                    }
                    else
                    {
                        StaticLogger.Warning(string.Format("Unknown object {0}", obj.GetType()));
                    }

                    if (obj != null && encode)
                    {
                        if (pck != null && pck.Message is Notify)
                        {
                            InternalSend((Notify)pck.Message, true);
                            sourcecontext.ObjectEncoding = ObjectEncoding.AMF3;
                        }
                        else
                        {
                            var buf = RtmpProtocolEncoder.Encode(sourcecontext, obj);
                            if (buf == null)
                            {
                                StaticLogger.Fatal("Unable to encode " + obj);
                            }
                            else
                            {
                                var buff = buf.ToArray();
                                if (logtofiles)
                                {
                                    using (var fs = File.Open("send.dmp", FileMode.Append, FileAccess.Write))
                                    {
                                        fs.Write(buff, 0, buff.Length);
                                    }
                                }
                                if (encode)
                                {
                                    base.OnSend(buff, 0, buff.Length);
                                }
                            }
                        }
                    }
                }
            }

            if (!encode)
            {
                base.OnSend(buffer, idx, len);
            }
        }
コード例 #11
0
ファイル: PlayerCommands.cs プロジェクト: Elophant/Client
        public T InvokeService <T>(string service, string operation, params object[] args) where T : class
        {
            var msg = new RemotingMessage();

            msg.operation   = operation;
            msg.destination = service;
            msg.headers["DSRequestTimeout"] = 60;
            msg.headers["DSId"]             = RtmpUtil.RandomUidString();
            msg.headers["DSEndpoint"]       = "my-rtmps";
            msg.body      = args;
            msg.messageId = RtmpUtil.RandomUidString();

            string endpoint = service + "." + operation;

            var result = Host.Call(msg);

            if (result == null)
            {
                StaticLogger.Warning(string.Format("Invoking {0} returned null", endpoint));
                return(null);
            }

            if (RtmpUtil.IsError(result))
            {
                var error       = RtmpUtil.GetError(result);
                var errordetail = error != null && error.faultDetail != null?string.Format(" [{0}]", error.faultDetail) : "";

                var errorstr = error != null && error.faultString != null?string.Format(", {0}", error.faultString) : "";

                StaticLogger.Warning(string.Format(
                                         "{0} returned an error{1}{2}",
                                         endpoint,
                                         errorstr,
                                         errordetail
                                         ));
                return(null);
            }

            var body = RtmpUtil.GetBodies(result).FirstOrDefault();

            if (body == null)
            {
                StaticLogger.Debug(endpoint + " RtmpUtil.GetBodies returned null");
                return(null);
            }

            if (body.Item1 == null)
            {
                StaticLogger.Debug(endpoint + " Body.Item1 returned null");
                return(null);
            }

            object obj = null;

            if (body.Item1 is ASObject)
            {
                var ao = (ASObject)body.Item1;
                obj = MessageTranslator.Instance.GetObject <T>(ao);
                if (obj == null)
                {
                    StaticLogger.Debug(endpoint + " expected " + typeof(T) + ", got " + ao.TypeName);
                    return(null);
                }
            }
            else if (body.Item1 is ArrayCollection)
            {
                try
                {
                    obj = Activator.CreateInstance(typeof(T), (ArrayCollection)body.Item1);
                }
                catch (Exception ex)
                {
                    StaticLogger.Warning(endpoint + " failed to construct " + typeof(T));
                    StaticLogger.Debug(ex);
                    return(null);
                }
            }
            else
            {
                StaticLogger.Debug(endpoint + " unknown object " + body.Item1.GetType());
                return(null);
            }

            if (obj is MessageObject)
            {
                ((MessageObject)obj).TimeStamp = body.Item2;
            }

            return((T)obj);
        }
コード例 #12
0
        /// <summary>
        /// Helper method which sets all the properties in the class to their respected FlashObject field.
        /// Use InternalNameAttribute to specify a property which has a FlashObject counter-part.
        /// SetFields does not travel the hierarchy. So Derived types must make their own separate call to SetFields.
        /// </summary>
        /// <param name="obj">Object to change properties</param>
        /// <param name="flash">Flash object to get fields from</param>
        public static void SetFields <T>(T obj, ASObject flash)
        {
            if (flash == null)
            {
                return;
            }

            foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                var intern = prop.GetAttribute <InternalNameAttribute>();
                if (intern == null)
                {
                    continue;
                }

                var    type = prop.PropertyType;
                object value;

                if (!flash.TryGetValue(intern.Name, out value))
                {
                    StaticLogger.Warning(string.Format("{0} missing ASObject property {1}", typeof(T).FullName, intern.Name));
                    continue;
                }

                try
                {
                    if (type == typeof(string))
                    {
                        value = Convert.ToString(flash[intern.Name]);
                    }
                    else if (type == typeof(Int32))
                    {
                        value = Convert.ToInt32(flash[intern.Name]);
                    }
                    else if (type == typeof(Int64))
                    {
                        value = Convert.ToInt64(flash[intern.Name]);
                    }
                    else if (type == typeof(double))
                    {
                        value = Convert.ToInt64(flash[intern.Name]);
                    }
                    else if (type == typeof(bool))
                    {
                        value = Convert.ToBoolean(flash[intern.Name]);
                    }
                    else if (type == typeof(DateTime))
                    {
                        value = Convert.ToDateTime(flash[intern.Name]);
                    }
                    else if (type == typeof(ASObject))
                    {
                        value = flash[intern.Name] as ASObject;
                    }
                    else if (type == typeof(ArrayCollection))
                    {
                        value = flash[intern.Name] as ArrayCollection;
                    }
                    else if (type == typeof(object))
                    {
                        value = flash[intern.Name];
                    }
                    else
                    {
                        try
                        {
                            value = Activator.CreateInstance(type, flash[intern.Name]);
                        }
                        catch (Exception e)
                        {
                            throw new NotSupportedException(string.Format("Type {0} not supported by flash serializer", type.FullName), e);
                        }
                    }
                    prop.SetValue(obj, value, null);
                }
                catch (Exception e)
                {
                    StaticLogger.Error(new Exception(string.Format("Error parsing {0}#{1}", typeof(T).FullName, prop.Name), e));
                }
            }
        }
コード例 #13
0
ファイル: MainForm.cs プロジェクト: ralph00/LoLNotes
        void launcher_ProcessFound(object sender, ProcessMonitor.ProcessEventArgs e)
        {
            try
            {
                if (!Settings.DeleteLeaveBuster)
                {
                    return;
                }

                var dir = Path.GetDirectoryName(e.Process.MainModule.FileName);
                if (dir == null)
                {
                    StaticLogger.Warning("Launcher module not found");
                    return;
                }

                var needle = "\\RADS\\";
                var i      = dir.LastIndexOf(needle, StringComparison.InvariantCulture);
                if (i == -1)
                {
                    StaticLogger.Warning("Launcher Rads not found");
                    return;
                }

                dir = dir.Remove(i + needle.Length);
                dir = Path.Combine(dir, "projects\\lol_air_client\\releases");

                if (!Directory.Exists(dir))
                {
                    StaticLogger.Warning("lol_air_client directory not found");
                    return;
                }

                foreach (var ver in new DirectoryInfo(dir).GetDirectories())
                {
                    var filename = Path.Combine(ver.FullName, "deploy\\preferences\\global\\global.properties");
                    if (!File.Exists(filename))
                    {
                        StaticLogger.Warning(filename + " not found");
                        continue;
                    }

                    ASObject obj = null;
                    using (var amf = new AMFReader(File.OpenRead(filename)))
                    {
                        try
                        {
                            obj = amf.ReadAMF3Data() as ASObject;
                            if (obj == null)
                            {
                                StaticLogger.Warning("Failed to read " + filename);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            StaticLogger.Warning("LeaverBuster: Unable to read global.properties '" + filename + "'");
                            continue;
                        }
                    }
                    object leaver;
                    object locale;
                    if ((obj.TryGetValue("leaverData", out leaver) && leaver != null) ||
                        (obj.TryGetValue("localeData", out locale) && locale != null))
                    {
                        obj["leaverData"] = null;
                        obj["localeData"] = null;
                        using (var amf = new AMFWriter(File.Open(filename, FileMode.Create, FileAccess.Write)))
                        {
                            try
                            {
                                amf.WriteAMF3Data(obj);
                                StaticLogger.Info("Removed leaverData/localeData from global.properties");
                            }
                            catch (Exception ex)
                            {
                                StaticLogger.Warning("LeaverBuster: Unable to write global.properties '" + filename + "'");
                                continue;
                            }
                        }
                    }
                    else
                    {
                        StaticLogger.Info("leaverData/localeData already removed from global.properties");
                    }
                }
            }
            catch (Exception ex)
            {
                StaticLogger.Error(ex);
            }
        }
コード例 #14
0
        private void MainForm_Shown(object sender, EventArgs e)
        {
            TrackingQueue.Enqueue("startup");

            Settings_Loaded(this, new EventArgs());
            UpdateStatus();

            //Add this after otherwise it will save immediately due to RegionList.SelectedIndex
            Settings.PropertyChanged += Settings_PropertyChanged;

            Settings.ModuleResolver = "Toolhelp32Snapshot";

            VersionLabel.Text = "v" + Version;

            //Start after the form is shown otherwise Invokes will fail
            Connection.Start();
            Injector.Start();
            launcher.Start();

            //Fixes the team controls size on start as they keep getting messed up in the WYSIWYG
            MainForm_Resize(this, new EventArgs());

            try
            {
                RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
                string[]    version_names      = installed_versions.GetSubKeyNames();
                //version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
                double framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture);

                if (framework < 4.0)
                {
                    if (MessageBox.Show("The Elophant Client requires the .NET Framework 4.0 Full version. Would you like to download it?", ".NET Framework 4.0 Full Not Found", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Process.Start("http://www.microsoft.com/en-us/download/details.aspx?id=17718");
                    }

                    MessageBox.Show("The Elophant Client will now close.");
                    Process.GetCurrentProcess().Kill();
                    return;
                }
            }
            catch (Exception ex)
            {
                StaticLogger.Error(ex.ToString());
                MessageBox.Show("An unknown exception has occurred. Check the log for more information.");
                Process.GetCurrentProcess().Kill();
                return;
            }

            try
            {
                var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "lolbans", "LoLLoader.dll");
                if (File.Exists(filename))
                {
                    StaticLogger.Info("Uninstalling old loader.");

                    var shortfilename = AppInit.GetShortPath(filename);

                    var dlls = AppInit.AppInitDlls32;
                    if (dlls.Contains(shortfilename))
                    {
                        dlls.Remove(AppInit.GetShortPath(shortfilename));
                        AppInit.AppInitDlls32 = dlls;
                    }

                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                }
            }
            catch (SecurityException se)
            {
                StaticLogger.Warning(se);
            }
            catch (Exception ex)
            {
                StaticLogger.Error("Failed to uninstall. Message: " + ex);
            }

            // NOT SURE IF THIS WORKS - TRYING TO AVOID THE USE OF AN INSTALL BUTTON
            try
            {
                if (!Installer.IsInstalled)
                {
                    if (!Wow.IsAdministrator)
                    {
                        MessageBox.Show("Please run the Elophant Client as the Administrator to install it.");
                        Process.GetCurrentProcess().Kill();
                        return;
                    }
                    try
                    {
                        Installer.Install();
                    }
                    catch (UnauthorizedAccessException uaex)
                    {
                        MessageBox.Show("Unable to fully install/uninstall. Make sure LoL is not running.");
                        StaticLogger.Warning(uaex);
                    }
                    //InstallButton.Text = Installer.IsInstalled ? "Uninstall" : "Install";
                    UpdateStatus();
                }
            }
            catch
            {
            }

            TryToCheckForUpdates();
        }
コード例 #15
0
        protected void CheckLoop()
        {
            bool showedError = false;

            while (CheckThread != null)
            {
                if (CurrentProcess != null)
                {
                    try
                    {
                        if (CurrentProcess.HasExited)
                        {
                            CurrentProcess = null;
                            IsInjected     = false;                         // update icon
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!showedError)
                        {
                            ErrorMessage = "Privilege of LoLNotes must be greater or equal to that of the LoLClient.\n\nSituations where LoLClient is run as admin and LoLNotes is not are no good.";
                            showedError  = true;
                        }
                        StaticLogger.Error(ex);
                        CurrentProcess = null;
                        IsInjected     = false;                     // update icon
                    }
                }

                if (CurrentProcess == null)
                {
                    CurrentProcess = Process.GetProcessesByName(ProcessName).FirstOrDefault();
                    if (CurrentProcess != null)
                    {
                        try
                        {
                            Inject();
                            IsInjected = true;
                        }
                        catch (FileNotFoundException fe)
                        {
                            //LoLClient does not have ws2_32 yet. Lets try again in 1 second.
                            StaticLogger.Trace(fe.Message);
                            CurrentProcess = null;
                            Thread.Sleep(1000);
                            continue;
                        }
                        catch (WarningException we)
                        {
                            IsInjected = true;
                            StaticLogger.Info(we.Message);
                        }
                        catch (NotSupportedException nse)
                        {
                            StaticLogger.Warning(nse);
                        }
                        catch (Exception ex)
                        {
                            StaticLogger.Error(new Exception(string.Format("{0} [{1}]", ex.Message, From), ex));
                        }
                    }
                }
                Thread.Sleep(500);
            }
        }
コード例 #16
0
ファイル: RtmpsProxyClient.cs プロジェクト: Elophant/Client
        protected override void OnReceive(byte[] buffer, int idx, int len)
        {
            StaticLogger.Trace(string.Format("Recv {0} bytes", len));

            if (logtofiles)
            {
                using (var fs = File.Open("realrecv.dmp", FileMode.Append, FileAccess.Write))
                {
                    fs.Write(buffer, idx, len);
                }
            }

            receivebuffer.Append(buffer, idx, len);

            var objs = RtmpProtocolDecoder.DecodeBuffer(remotecontext, receivebuffer);

            if (objs != null)
            {
                foreach (var obj in objs)
                {
                    var pck = obj as RtmpPacket;
                    if (pck != null)
                    {
                        var result = pck.Message as Notify;
                        if (result != null)
                        {
                            Notify inv = null;
                            if (RtmpUtil.IsResult(result))
                            {
                                lock (InvokeList)
                                {
                                    int fidx = InvokeList.FindIndex(i => i.InvokeId == result.InvokeId);
                                    if (fidx != -1)
                                    {
                                        inv = InvokeList[fidx];
                                        InvokeList.RemoveAt(fidx);
                                    }
                                }

                                if (inv != null)
                                {
                                    OnCall(inv, result);

                                    StaticLogger.Trace(
                                        string.Format(
                                            "Ret  ({0}) (Id:{1})",
                                            string.Join(", ", inv.ServiceCall.Arguments.Select(o => o.ToString())),
                                            pck.Header.ChannelId
                                            )
                                        );
                                }
                            }
                            else
                            {
                                OnNotify(result);
                            }
                        }
                        else
                        {
                            StaticLogger.Trace(string.Format("Recv {0} (Id:{1})", pck.Message, pck.Header.ChannelId));
                        }
                    }
                    else if (obj is ByteBuffer)
                    {
                        //Just handshakes, ignore
                    }
                    else
                    {
                        StaticLogger.Warning(string.Format("Unknown object {0}", obj.GetType()));
                    }

                    if (obj != null && encode)
                    {
                        if (pck != null && pck.Message is Notify)
                        {
                            InternalReceive((Notify)pck.Message);
                            remotecontext.ObjectEncoding = ObjectEncoding.AMF3;
                        }
                        else
                        {
                            var buf = RtmpProtocolEncoder.Encode(remotecontext, obj);
                            if (buf == null)
                            {
                                StaticLogger.Fatal("Unable to encode " + obj);
                            }
                            else
                            {
                                var buff = buf.ToArray();
                                if (logtofiles)
                                {
                                    using (var fs = File.Open("recv.dmp", FileMode.Append, FileAccess.Write))
                                    {
                                        fs.Write(buff, 0, buff.Length);
                                    }
                                }
                                if (encode)
                                {
                                    base.OnReceive(buff, 0, buff.Length);
                                }
                            }
                        }
                    }
                }
            }

            if (!encode)
            {
                base.OnReceive(buffer, idx, len);
            }
        }
コード例 #17
0
ファイル: MainForm.cs プロジェクト: ralph00/LoLNotes
        /// <summary>
        /// Query and cache player data
        /// </summary>
        /// <param name="player">Player to load</param>
        /// <param name="control">Control to update</param>
        void LoadPlayer(PlayerParticipant player, PlayerControl control)
        {
            PlayerCache existing;
            var         ply = new PlayerCache();

            try
            {
                lock (PlayersCache)
                {
                    //Clear the cache every 1000 players to prevent crashing afk lobbies.
                    if (PlayersCache.Count > 1000)
                    {
                        PlayersCache.Clear();
                    }

                    //Does the player already exist in the cache?
                    if ((existing = PlayersCache.Find(p => p.Player != null && p.Player.Id == player.SummonerId)) == null)
                    {
                        PlayersCache.Add(ply);
                    }
                }

                //If another thread is loading the player data, lets wait for it to finish and use its data.
                if (existing != null)
                {
                    existing.LoadWait.WaitOne();
                    LoadPlayerUIFinish(existing, control);
                    return;
                }


                using (SimpleLogTimer.Start("Player query"))
                {
                    var entry = Recorder.GetPlayer(player.SummonerId);
                    ply.Player = entry ?? ply.Player;
                }

                using (SimpleLogTimer.Start("Stats query"))
                {
                    var cmd      = new PlayerCommands(Connection);
                    var summoner = cmd.GetPlayerByName(player.Name);
                    if (summoner != null)
                    {
                        ply.Summoner     = summoner;
                        ply.Stats        = cmd.RetrievePlayerStatsByAccountId(summoner.AccountId);
                        ply.RecentChamps = cmd.RetrieveTopPlayedChampions(summoner.AccountId, "CLASSIC");
                        ply.Games        = cmd.GetRecentGames(summoner.AccountId);
                    }
                    else
                    {
                        StaticLogger.Debug(string.Format("Player {0} not found", player.Name));
                        ply.LoadWait.Set();
                        return;
                    }
                }

                using (SimpleLogTimer.Start("Seen query"))
                {
                    if (SelfSummoner != null && SelfSummoner.SummonerId != ply.Summoner.SummonerId && ply.Games != null)
                    {
                        ply.SeenCount = ply.Games.GameStatistics.Count(pgs => pgs.FellowPlayers.Any(fp => fp.SummonerId == SelfSummoner.SummonerId));
                    }
                }

                ply.LoadWait.Set();
                LoadPlayerUIFinish(ply, control);
            }
            catch (Exception ex)
            {
                ply.LoadWait.Set();                 //
                StaticLogger.Warning(ex);
            }
        }