Form1.cs 12.7 KB
using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
using System.Xml;
using System.IO;


namespace update_
{
    public partial class UpdateView : Form
    {
        WebClient webClient;

        System.Diagnostics.Stopwatch sw;
        public UpdateView(string[] _args)
        {
           
            InitializeComponent();
            this.args = _args;
            webClient = new WebClient();
            start();

        }

        public void start()

        {
           
            if (args.Length==3)
            { 
                switch (args[1])
                {
                    case "installer":
                        download(args[0], "vlibras_installer.exe");
                        lbInforGeral.Text = "Baixando nova versão do VLibras...";

                        break;
                    case "dictionary":
                        download(args[0], "vlibras_dicionario.zip");
                        lbInforGeral.Text = "Baixando nova versão do VLibras Dicionário...";
                        break;

                    default:
                        lbInforGeral.ForeColor = Color.Red;
                        this.btCancel.Enabled = false;
                        this.btOk.Enabled = true;
                        lbInforGeral.Text = "Nao foi possível fazer atualização!";
                        break;
                }
            }
            else if(args.Length == 0)
            {
                string[] compareVersion = checkVersion();


                if (compareVersion[0] != null && compareVersion[2] != null)
                {

                    if (compareVersion[2].EndsWith(".exe") && compareVersion[2].StartsWith("htt"))
                    {
                        this.args = new string[3];
                        this.args[1] = "installer";
                        this.args[2] = compareVersion[1];
                        download(compareVersion[2], "vlibras_installer.exe");
                        lbInforGeral.Text = "Baixando nova versão do VLibras...";

                    }
                    }

                    else if (compareVersion[3] != null && compareVersion[5] != null)
                    {
                    
                        if (compareVersion[5].EndsWith(".zip") && compareVersion[5].StartsWith("htt"))
                        {
                            this.args = new string[3];
                            this.args[1] = "dictionary";
                            this.args[2] = compareVersion[4];
                            download(compareVersion[5], "vlibras_dicionario.zip");
                            lbInforGeral.Text = "Baixando nova versão do VLibras Dicionário...";

                        }
                 }

                else
                {
                    lbInforGeral.ForeColor = Color.Green;
                    this.btCancel.Enabled = false;
                    this.btOk.Enabled = true;
                    lbInforGeral.Text = "VLibras está atualizado!";
                }
      
            }

            
            
           
        }

        bool extractZip(string zipPath, string extractPath)
        {
            try
            {
                if (!File.Exists(zipPath))
                    return false;

               //this.Close();

                if (!Directory.Exists(extractPath))
                    Directory.CreateDirectory(extractPath);

                Shell32.Shell objShell = new Shell32.Shell();
                Shell32.Folder destinationFolder = objShell.NameSpace(extractPath);
                Shell32.Folder sourceFile = objShell.NameSpace(zipPath);

                foreach (var file in sourceFile.Items())
                {

                    destinationFolder.CopyHere(file, 4 | 16);
                }

            }
            catch (Exception e)
            {
                return false;
            }

            return true;
        }

        bool saveNewXmlVersion(string playerVersion, string dictionaryVersion)
        {
            XmlDocument xmlDocLocal;
            XmlNodeList filesLocal;
            try
            {
                xmlDocLocal = new XmlDocument();
                //xml version local
                StreamReader readerLocal = new StreamReader("c:\\vlibras-libs\\update\\updateVersion.xml");

                String responseLocal = readerLocal.ReadToEnd();

                xmlDocLocal.LoadXml(responseLocal);

                filesLocal = xmlDocLocal.GetElementsByTagName("version");

                if (playerVersion.Length > 0)
                    filesLocal[0]["playerVersion"].InnerText = playerVersion;

                if (dictionaryVersion.Length > 0)
                {
                    
                    filesLocal[0]["dictionaryVersion"].InnerText = dictionaryVersion;
                }


                // Cleanup the streams and the response.
                readerLocal.Close();

                xmlDocLocal.Save("c:\\vlibras-libs\\update\\updateVersion.xml");
            }
            catch (Exception e)
            {

            }

            return true;
        }


       public string[] checkVersion()
        {
            lbInforGeral.Text = "Verificando versão...";
            
           

            XmlDocument xmlDoc;
            XmlNodeList files;
            string[] updates = new string[6];
            string[] localversion = getLocalVersion();
            try
            {
                xmlDoc = new XmlDocument();

                string url = "http://vlibras.lavid.ufpb.br/api/dicionario/" + localversion[3] + "?type=windows";
                
                WebRequest request = WebRequest.Create(url);
                // If required by the server, set the credentials.
                request.Credentials = CredentialCache.DefaultCredentials;
                // Get the response.
                HttpWebResponse response = (HttpWebResponse)(request.GetResponse());
                if (!(response.StatusDescription == "OK"))
                    return updates;

               // MessageBox.Show("Olá " + url);
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                String responseFromServer = reader.ReadToEnd();
                xmlDoc.LoadXml(responseFromServer);
                files = xmlDoc.GetElementsByTagName("version");
                long numitems = files.Count;

                //for (int i=0;i<numitems;i++)
                if (numitems > 0)
                {
                    string playerVersion = files[0]["playerVersion"].InnerText;
                    string dictionaryVersion = files[0]["dictionaryVersion"].InnerText;

                    if (!playerVersion.Equals(localversion[1]))
                    {
                        updates[0] = "playerVersion";
                        updates[1] = playerVersion;
                        updates[2] = files[0]["playerUrl"].InnerText;
                    }
                    if (!dictionaryVersion.Equals(localversion[3]))
                    {
                        updates[3]="dictionaryVersion";
                        updates[4]= dictionaryVersion;
                        updates[5] = files[0]["dictionaryUrl"].InnerText;
                    }        

                }

                reader.Close();
                dataStream.Close();
            }
            catch (Exception e)
            {
                return updates;
            }

            return updates;
        }



        string[] getLocalVersion()
        {
            XmlDocument xmlDocLocal;
            XmlNodeList filesLocal;
            string[] updates = new string[6];
            try
            {
                xmlDocLocal = new XmlDocument();
                //xml version local
                StreamReader readerLocal = new StreamReader("c:\\vlibras-libs\\update\\updateVersion.xml");

                String responseLocal = readerLocal.ReadToEnd();

                xmlDocLocal.LoadXml(responseLocal);

                filesLocal = xmlDocLocal.GetElementsByTagName("version");

                updates[0] = "playerVersion";

                updates[1] = filesLocal[0]["playerVersion"].InnerText;
                updates[2] = "dictionaryVersion";
                updates[3] = filesLocal[0]["dictionaryVersion"].InnerText;

                // Cleanup the streams and the response.
                readerLocal.Close();
            }
            catch (Exception e)
            {
                return updates;
            }

            return updates;
        }





        private void btOk_Click(object sender, EventArgs e)
        {

            this.Dispose();
            this.Close();
            //MessageBox.Show("Olá "+args.Length);

        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            if (args.Length > 1)
                args[1] = "faill";
            
            webClient.CancelAsync();
            btCancel.Enabled = false;
            btOk.Enabled = true;
            lbInforGeral.Text = "Atualização cancelada. Click em OK para fechar";
            lbinforDownload.Text = "Download cancelado.";

        }

        private void download(string url, string fileName)
        {
            try
            {

                sw = System.Diagnostics.Stopwatch.StartNew();

                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadCompleto);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadCallback);
                webClient.DownloadFileAsync(new Uri(url), @"c:\vlibras-libs\update\" + fileName);
            }
            catch (Exception ex)
            {
                lbInforGeral.Text = "Ocorreu um erro ao tentar baixar atualização!";
                this.btOk.Enabled = true;
                this.btCancel.Enabled = false;
            }
        }

        private void downloadCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            lbinforDownload.Text = ((float)e.BytesReceived / 1024 / 1024).ToString("0.00") + " (MB) baixado de " + ((float)e.TotalBytesToReceive / 1024 / 1024).ToString("0.00") + " (MB) Tempo decorrido -." + (int)sw.Elapsed.TotalSeconds + " (seg) | " + e.ProgressPercentage + "%";
        }



        private void downloadCompleto(object sender, AsyncCompletedEventArgs e)
        {
           
            
           
            this.btOk.Enabled = true;
            this.btCancel.Enabled = false;
            if (args.Length > 1)
            {
                lbInforGeral.ForeColor = Color.Black;
                switch (args[1])
                {

                    case "installer":

                        lbInforGeral.Text = "VLibras baixado com sucesso!";
                        try
                        {
                            System.Diagnostics.Process vlibrasinstall = new System.Diagnostics.Process();
                            vlibrasinstall.StartInfo.FileName = @"C:\vlibras-libs\update\vlibras_installer.exe";
                            vlibrasinstall.StartInfo.Arguments = " / SILENT /SUPPRESSMSGBOXES /NORESTART ";
                            vlibrasinstall.Start();
                            saveNewXmlVersion(args[2], "");
                            this.Dispose();
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            lbInforGeral.ForeColor = Color.Red;
                            lbInforGeral.Text = "Ocorreu um erro ao atualizar o VLibras ";
                        }
                        break;
                    case "dictionary":

                        lbInforGeral.Text = "Atualizando VLibras Dicionário...";
                        if (extractZip("C:\\vlibras-libs\\update\\vlibras_dicionario.zip", "C:\\vlibras-libs\\Player\\VLibrasPlayer_Data\\Bundles"))
                        {
                            lbInforGeral.ForeColor = Color.Green;
                            lbInforGeral.Text = "VLibras Dicionário atualizado com sucesso!";
                            saveNewXmlVersion("", args[2]);
                        }
                        else
                        {
                            lbInforGeral.ForeColor = Color.Red;
                            lbInforGeral.Text = "Ocorreu um erro ao atualizar VLibras Dicionário...";
                        }
                        break;
      

                }
                if (args.Length == 4)
                {
                    this.Dispose();
                    this.Close();
                }

            }
        }



    }

    }