Exemplo n.º 1
0
        static void Main(string[] args)
        {
            if(args.Length!=1)
            {
                Console.WriteLine("Please set a config file!");
                return;
            }

            //CancelEvent verdrahten
            Console.CancelKeyPress+=new ConsoleCancelEventHandler(Console_CancelKeyPress);

            //Highscore Pfad bauen
            string highscorePath=FileSystem.GetPath(args[0])+"highscore.xml";

            //Config auslesen
            XmlData Options=new XmlData(args[0]);

            string username=Options.GetElementAsString("xml.IRC.UserName");
            string realname=Options.GetElementAsString("xml.IRC.RealName");
            string ident=Options.GetElementAsString("xml.IRC.Ident");
            string server=Options.GetElementAsString("xml.IRC.Server");
            string channel=Options.GetElementAsString("xml.IRC.Channel");
            string userpassword=Options.GetElementAsString("xml.IRC.Password");

            //Bot anlegen
            Arbiter arbiter=new Arbiter(server, username, realname, ident, channel, highscorePath);

            //Jokes einlesen
            List<XmlNode> jokeNodes=Options.GetElements("xml.Jokes.Joke");

            foreach(XmlNode jokeNode in jokeNodes)
            {
                string category=jokeNode.Attributes["category"]!=null?jokeNode.Attributes["category"].Value:"";
                string jokeText=jokeNode.InnerText;
                arbiter.Jokes.Add(new Joke(category, jokeText));
            }

            //Quizfragen einlesen
            List<XmlNode> questionsNodes=Options.GetElements("xml.Quiz.Question");

            foreach(XmlNode questionNode in questionsNodes)
            {
                string category=questionNode.Attributes["category"].Value;
                string question=questionNode.Attributes["question"].Value;
                string success=questionNode.Attributes["success"]!=null?questionNode.Attributes["success"].Value:"";
                int points=Convert.ToInt32(questionNode.Attributes["points"].Value);
                List<string> hints=new List<string>();

                int keywordWeight=1;
                if(questionNode.Attributes.GetNamedItem("keywordWeight")!=null)
                {
                    keywordWeight=Convert.ToInt32(questionNode.Attributes["keywordWeight"].Value);
                }

                List<Keyword> keywords=new List<Keyword>();

                foreach(XmlNode child in questionNode.ChildNodes)
                {
                    if(child.Name=="Keyword")
                    {
                        int weight=1;

                        if(child.Attributes.GetNamedItem("keywordWeight")!=null)
                        {
                            string weightValue=child.Attributes["keywordWeight"].Value;

                            if(weightValue=="MAX")
                                weight=Int32.MaxValue;
                            else
                                weight=Convert.ToInt32(weightValue);
                        }

                        Keyword keyword=new Keyword(child.InnerText, weight);
                        keywords.Add(keyword);
                    }
                    else if(child.Name=="Hint")
                    {
                        hints.Add(child.InnerText);
                    }
                }

                //Frage zum Bot hinzufügen
                arbiter.Quiz.Questions.Add(new Question(category, question, hints, success, points, keywordWeight, keywords));
            }

            //Quotes einlesen
            List<XmlNode> quodeNodes=Options.GetElements("xml.Quotes.Quote");

            foreach(XmlNode quodeNode in quodeNodes)
            {
                string author=quodeNode.Attributes["author"].Value;
                string quoteText=quodeNode.InnerText;
                arbiter.Quotes.Add(new Quote(author, quoteText));
            }

            //Bot starten
            arbiter.Start(userpassword);
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            //Options
            if(!FileSystem.ExistsFile("config.xml"))
            {
                Console.WriteLine("No config.xml file found.");
                return;
            }

            XmlData Options=new XmlData("config.xml");

            recieverMail=Options.GetElementAsString("xml.SMTP.RecieverMail");

            smtpserver=Options.GetElementAsString("xml.SMTP.Server");
            senderMail=Options.GetElementAsString("xml.SMTP.SenderMail");
            smtpUsername=Options.GetElementAsString("xml.SMTP.Username");
            smtpPassword=Options.GetElementAsString("xml.SMTP.Password");

            //Files
            Dictionary<string, string> commandLine=CommandLineHelpers.GetCommandLine(args);
            List<string> files=new List<string>();

            bool book=commandLine.ContainsKey("book");
            string bookname = "";
            if(book) bookname = commandLine["book"];

            List<string> clFiles=CommandLineHelpers.GetFilesFromCommandline(commandLine);

            foreach(string clFile in clFiles)
            {
                if(FileSystem.IsFile(clFile))
                {
                    files.Add(clFile);
                }
                else
                {
                    files.AddRange(FileSystem.GetFiles(clFile, true));
                }
            }

            if(files.Count==0)
            {
                Console.WriteLine("No files specified.");
                return;
            }

            //Send Files
            foreach(string file in files)
            {
                string fileSend=file;

                //CSCL.
                //Sending
                string subject=FileSystem.GetFilenameWithoutExt(file);
                if(book)
                {
                    subject = String.Format("{0} @{1}", subject, bookname);
                }

                Console.WriteLine("Send file {0}...", FileSystem.GetFilename(file));
                SMTP.SendMailMessageWithAuthAndAttachment(smtpserver, smtpUsername, smtpPassword, senderMail, "everloaduploader", recieverMail, recieverMail, subject, "", fileSend);
            }
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            //Load config
            XmlData config;

            try
            {
                config=new XmlData("tweetstatus.xml");
            }
            catch(Exception e)
            {
                Console.WriteLine("Konfiguration konnte nicht gelesen werden.");
                Console.WriteLine(e.ToString());
                return;
            }

            string miscCheckCertificates=config.GetElementAsString("xml.misc.checkcertificates");

            if(miscCheckCertificates.ToLower()=="false")
            {
                //Disable certificate check
                ServicePointManager.ServerCertificateValidationCallback=delegate
                {
                    return true;
                };
            }

            string apiToken=config.GetElementAsString("xml.api.token");
            string apiUrl=config.GetElementAsString("xml.api.url");

            string twitterConsumerKey=config.GetElementAsString("xml.twitter.consumerkey");
            string twitterConsumerSecret=config.GetElementAsString("xml.twitter.consumersecret");

            string twitterAccessToken=config.GetElementAsString("xml.twitter.accesstoken");
            string twitterAccessTokenSecret=config.GetElementAsString("xml.twitter.accesstokensecret");

            //Create twitter token
            OAuthInfo token=null;

            if(twitterAccessToken==""||twitterAccessTokenSecret=="")
            {
                Console.WriteLine("Set access token in config file");
                return;
            }
            else
            {
                token=new OAuthInfo {
                    AccessToken=twitterAccessToken,
                    AccessSecret=twitterAccessTokenSecret,
                    ConsumerKey=twitterConsumerKey,
                    ConsumerSecret=twitterConsumerSecret
                };
            }

            //Check status database
            Console.WriteLine("Check status database");

            //Database
            RestClient client=new RestClient(apiUrl);
            string parameters=String.Format("entities/?token={0}", apiToken);

            string value=client.Request(parameters);
            int entityCount=Convert.ToInt32(value);

            Console.WriteLine("Entity count from api: {0}", entityCount);

            //Check status file and tweet if nessesary
            //Load known entries
            string entryFile="status.txt";

            Entry oldStatus=new Entry(0);

            if(File.Exists(entryFile))
            {
                oldStatus=new Entry(File.ReadAllLines(entryFile)[0]);
            }

            Entry newStatus=new Entry(entityCount);

            if(oldStatus!=newStatus)
            {
                //Tweet
                DateTime now=DateTime.Now;
                string datetimeHash="#"+CRC16.ComputeChecksum(BitConverter.GetBytes(now.Ticks)).ToString("x4");

                string statusGreen=String.Format("Der Hackerspace ist besetzt ({0}:{1:00} Uhr) und kann besucht werden. #status {2}", now.Hour, now.Minute, datetimeHash);
                string statusYellow="";
                string statusRed=String.Format("Der Hackerspace ist nicht mehr besetzt ({0}:{1:00} Uhr). #status {2}", now.Hour, now.Minute, datetimeHash);

                string tweetText="";

                if(newStatus.EntityCount==0)
                {
                    tweetText=statusRed;
                }
                else
                {
                    if(oldStatus.EntityCount>0)
                    {
                        Console.WriteLine("Update not necessary.");
                        return;
                    }

                    tweetText=statusGreen;
                }

                bool success=true;

                try
                {
                    Console.WriteLine("Token: {0}", token.ToString());

                    var twitter=new TinyTwitter.TinyTwitter(token);
                    twitter.UpdateStatus(tweetText);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    success=false;
                }

                if(success)
                {
                    //Write success on console
                    Console.WriteLine("Tweet sended: {0}", tweetText);

                    //Write new status
                    File.WriteAllText(entryFile, newStatus.ToString());
                }
                else
                {
                    Console.WriteLine("Tweet not sended: {0}", tweetText);
                }
            }
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            //Console
            Console.WriteLine("Initializing sensor...");

            //Load config
            XmlData config;

            try
            {
                config=new XmlData("sensor.xml");
            }
            catch(Exception e)
            {
                Console.WriteLine("Konfiguration konnte nicht gelesen werden.");
                Console.WriteLine(e.ToString());
                return;
            }

            bool miscCheckCertificates=Convert.ToBoolean(config.GetElementAsString("xml.misc.checkcertificates"));

            if(miscCheckCertificates==false)
            {
                //Disable certificate check
                ServicePointManager.ServerCertificateValidationCallback=delegate
                {
                    return true;
                };
            }

            bool verbose=Convert.ToBoolean(config.GetElementAsString("xml.misc.verbose"));

            string apiToken=config.GetElementAsString("xml.api.token");
            string apiUrl=config.GetElementAsString("xml.api.url");

            //EAPI Setup
            EAPI eAPI=new EAPI(apiUrl, apiToken);

            #region Network scan
            Console.WriteLine("Scan network...");

            //Scan network
            Dictionary<string, List<NetworkEntry>> networkScans=new Dictionary<string, List<NetworkEntry>>();
            List<XmlNode> networkSegments=config.GetElements("xml.network.segment");

            foreach(XmlNode node in networkSegments)
            {
                bool active=Convert.ToBoolean(node["active"].InnerText);
                if(!active) continue;

                string key=node.Attributes["key"].Value;
                Console.WriteLine("Scan network segment {0}...", key);

                //IP Ranges
                List<string> segmentIPRanges=new List<string>();
                foreach(XmlNode childNode in node.ChildNodes)
                {
                    if(childNode.LocalName=="iprange") segmentIPRanges.Add(childNode.InnerText);
                }

                //Scan ranges
                List<NetworkEntry> entries=new List<NetworkEntry>();

                foreach(string segmentIPRange in segmentIPRanges)
                {
                    NetworkScanner scanner=new NetworkScanner();

                    List<NetworkEntry> segmentEntries=scanner.GetNetworkInformation(segmentIPRange);
                    Console.WriteLine("Detected network devices in segment {0}/{1}: {2}", key, segmentIPRange, segmentEntries.Count);

                    if(verbose)
                    {
                        foreach(NetworkEntry networkEntry in segmentEntries)
                        {
                            Console.WriteLine("Detected network device: {0} / {1} ({2}, {3} ms)", networkEntry.IP, networkEntry.Hostname, networkEntry.Up?"online":"offline", networkEntry.RoundtripTime);
                        }
                    }

                    entries.AddRange(segmentEntries);
                }

                networkScans.Add(key, entries);
            }
            #endregion

            #region Detection
            Console.WriteLine("Start detection...");

            //Entity Detection
            int countEntities=0;

            bool entityDetection=Convert.ToBoolean(config.GetElementAsString("xml.detection.entity.active"));

            if(entityDetection)
            {
                Console.WriteLine("Start entity detection...");

                string sensorType=config.GetElementAsString("xml.detection.entity.sensortype");
                string networkSegment=config.GetElementAsString("xml.detection.entity.networksegment");
                int minimumCount=Convert.ToInt32(config.GetElementAsString("xml.detection.entity.minimumcount"));
                TimeSpan minimumTime=new TimeSpan(0, 0, Convert.ToInt32(config.GetElementAsString("xml.detection.entity.minimumtime")));

                long significantTimeAsLong=Convert.ToInt64(config.GetElementAsString("xml.detection.entity.significanttime"));
                DateTime significantTime=new DateTime(significantTimeAsLong);

                if(sensorType=="network")
                {
                    Console.WriteLine("Start entity detection with sensor type network...");

                    if(networkScans.ContainsKey(networkSegment))
                    {
                        List<NetworkEntry> segmentEntries=networkScans[networkSegment];

                        //Check if minimum count is reached
                        if(segmentEntries.Count>minimumCount)
                        {
                            if(significantTimeAsLong==0)
                            {
                                significantTime=DateTime.Now;
                                config.WriteElement("xml.detection.entity.significanttime", significantTime.Ticks.ToString());
                            }

                            //Check if minimum time is reached
                            if(DateTime.Now>significantTime+minimumTime)
                            {
                                countEntities=segmentEntries.Count;
                            }
                        }
                        else
                        {
                            config.WriteElement("xml.detection.entity.significanttime", "0");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Network segment for detection not found.");
                    }
                }
            }
            #endregion

            #region API
            Console.WriteLine("Transfer sensor data to API...");

            //Write Network informations into API Database
            int countDevices=0;

            foreach(KeyValuePair<string, List<NetworkEntry>> pair in networkScans)
            {
                countDevices+=pair.Value.Count;
                eAPI.SetStatus(pair.Key, pair.Value.Count);
            }

            eAPI.SetStatus("devices", countDevices);

            //Write Entites
            eAPI.SetStatus("entities", countEntities);
            #endregion

            //set last run
            config.WriteElement("xml.misc.lastrun", DateTime.Now.Ticks.ToString());
            config.Save();
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            #region Init
            if(args.Length!=1)
            {
                Console.WriteLine("Argument fehlt:");
                Console.WriteLine("z.B. mono autoupdate.exe autoupdate.xml");
                return;
            }

            if(!FileSystem.ExistsFile(args[0]))
            {
                Console.WriteLine("Angegebene Datei existiert nicht.");
                return;
            }

            XmlData config;

            try
            {
                config=new XmlData(args[0]);
            }
            catch(Exception e)
            {
                Console.WriteLine("Konfiguration konnte nicht gelesen werden.");
                Console.WriteLine(e.ToString());
                return;
            }

            Console.WriteLine("Autoupdate 1.2.1 wurde gestartet...");

            string workfolder_original=Directory.GetCurrentDirectory();

            string misc_servername=config.GetElementAsString("xml.misc.servername");

            string ftp_data_server=config.GetElementAsString("xml.ftp.data.server");
            string ftp_data_user=config.GetElementAsString("xml.ftp.data.user");
            string ftp_data_password=config.GetElementAsString("xml.ftp.data.password");

            bool irc_active=false;
            string irc_network="";
            string irc_channel="";

            if(config.GetElementAsString("xml.irc.active")!="")
            {
                irc_active=Convert.ToBoolean(config.GetElementAsString("xml.irc.active"));
                irc_network=config.GetElementAsString("xml.irc.network");
                irc_channel=config.GetElementAsString("xml.irc.channel");
            }

            string ftp_update_server=config.GetElementAsString("xml.ftp.update.server");
            string ftp_update_user=config.GetElementAsString("xml.ftp.update.user");
            string ftp_update_password=config.GetElementAsString("xml.ftp.update.password");

            bool activate_data=Convert.ToBoolean(config.GetElementAsString("xml.activate.data"));
            bool activate_update=Convert.ToBoolean(config.GetElementAsString("xml.activate.update"));

            string path_temp_folder=FileSystem.GetPathWithPathDelimiter(config.GetElementAsString("xml.path.temp"));

            string path_repostiory_trunk=FileSystem.GetPathWithPathDelimiter(config.GetElementAsString("xml.path.repository.trunk"));
            string path_repostiory_server=path_repostiory_trunk+"server/";
            string path_repostiory_data=path_repostiory_trunk+"data/";
            string path_repostiory_data_scripts=path_repostiory_data+"/scripts/";
            string path_repostiory_data_maps=path_repostiory_data+"/maps/";

            string path_server_root=FileSystem.GetPathWithPathDelimiter(config.GetElementAsString("xml.path.server.root"));
            string path_server_data=path_server_root+"data/";
            string path_server_data_scripts=path_server_data+"scripts/";
            string path_server_data_maps=path_server_data+"maps/";
            string path_server_start_script=path_server_root+"start-server.sh";
            string path_server_stop_script=path_server_root+"stop-server.sh";

            List<string> ExcludesDirsClient=new List<string>();
            ExcludesDirsClient.Add("maps_templates");
            ExcludesDirsClient.Add("maps_rules");
            ExcludesDirsClient.Add("scripts");
            ExcludesDirsClient.Add(".git");

            List<string> ExcludesDirsServer=new List<string>();
            ExcludesDirsServer.Add("maps_templates");
            ExcludesDirsServer.Add("maps_rules");
            ExcludesDirsServer.Add("graphics");
            ExcludesDirsServer.Add("music");
            ExcludesDirsServer.Add("sfx");
            ExcludesDirsServer.Add(".git");

            List<string> ExcludeFiles=new List<string>();
            ExcludeFiles.Add("CMakeLists.txt");
            #endregion

            #region IRC Message absetzen
            if(irc_active)
            {
                Console.WriteLine("Sende IRC Nachricht...");

                irc.SendDelay=200;
                irc.AutoRetry=true;
                irc.ActiveChannelSyncing=true;

                string[] serverlist=new string[] { irc_network };
                int port=6667;

                irc.Connect(serverlist, port);
                irc.Login("Autoupdate", "Autoupdate", 0, "AutoupdateIRC");
                irc.RfcJoin("#invertika");

                Random rnd=new Random();
                string funkyWord=FunkyWords[rnd.Next(FunkyWords.Length)];
                irc.SendMessage(SendType.Message, irc_channel, String.Format("Autoupdate wurde auf dem Server {0} gestartet. {1}", misc_servername, funkyWord));

                new Thread(new ThreadStart(StartIRCListen)).Start();
            }
            #endregion

            #region Repository updaten
            Console.WriteLine("Update Repository...");
            Directory.SetCurrentDirectory(path_repostiory_data);
            ProcessHelpers.StartProcess("git", "pull", true);
            #endregion

            #region Server stoppen und Serverdaten löschen
            Console.WriteLine("Stoppe Server...");
            Directory.SetCurrentDirectory(path_server_root);
            ProcessHelpers.StartProcess(path_server_stop_script, "", false);

            Console.WriteLine("Lösche Serverdaten...");
            if(FileSystem.ExistsDirectory(path_server_data))
            {
                FileSystem.RemoveDirectory(path_server_data, true, true);
            }

            Console.WriteLine("Lösche temporäres Verzeichnis...");
            if(FileSystem.ExistsDirectory(path_temp_folder))
            {
                FileSystem.RemoveDirectory(path_temp_folder, true, true);
            }
            #endregion

            #region Neue Serverdaten kopieren
            Directory.SetCurrentDirectory(path_server_root);
            Console.WriteLine("Kopiere neue Serverdaten...");

            FileSystem.CreateDirectory(path_server_data_maps, true);

            FileSystem.CopyDirectory(path_repostiory_data, path_server_data, true, ExcludesDirsServer, ExcludeFiles);
            #endregion

            #region Clientdaten
            Console.WriteLine("Erzeuge Verzeichnis mit Clientdaten...");
            string clientPath=path_temp_folder+"clientdata"+FileSystem.PathDelimiter;

            FileSystem.CreateDirectory(clientPath, true);
            FileSystem.CreateDirectory(clientPath+"data"+FileSystem.PathDelimiter, true);
            FileSystem.CopyDirectory(path_repostiory_data, clientPath+"data"+FileSystem.PathDelimiter, true, ExcludesDirsClient);

            List<string> clientDataFiles=FileSystem.GetFiles(clientPath, true);
            #endregion

            #region Clientdaten Update erzeugen und hochladen
            if(activate_update)
            {
                Console.WriteLine("Erstelle Zip Datei für Update...");
                clientPath=clientPath+"data"+FileSystem.PathDelimiter;

                //Zip erstellen
                string zipFilename=path_temp_folder+"update-"+Various.GetTimeID()+".zip";
                ZipFile z=ZipFile.Create(zipFilename);

                z.BeginUpdate();

                int fivePercent=clientDataFiles.Count/20;
                int countZipFiles=0;

                foreach(string i in clientDataFiles)
                {
                    countZipFiles++;

                    if(FileSystem.GetExtension(i).ToLower()=="ogg")
                    {
                        Console.WriteLine("Datei {0} aus dem Update ausgeschlossen.", FileSystem.GetFilename(i));
                        continue;
                    }

                    string rel=FileSystem.GetRelativePath(i, clientPath, true);
                    z.Add(i, rel);

                    if(countZipFiles%fivePercent==0)
                    {
                        Console.Write(".");
                    }
                }

                z.CommitUpdate();
                z.Close();

                //adler 32
                ICSharpCode.SharpZipLib.Checksums.Adler32 adler=new ICSharpCode.SharpZipLib.Checksums.Adler32();

                FileStream fs=new FileStream(zipFilename, FileMode.Open, FileAccess.Read);
                BinaryReader br=new BinaryReader(fs);

                byte[] textToHash=br.ReadBytes((int)fs.Length);

                adler.Reset();
                adler.Update(textToHash);
                string adler32=String.Format("{0:x}", adler.Value);

                //Ressources
                string resFile=path_temp_folder+FileSystem.PathDelimiter+"resources2.txt";
                StreamWriter sw=new StreamWriter(resFile);
                sw.WriteLine("{0} {1}", FileSystem.GetFilename(zipFilename), adler32);
                sw.Close();

                //Newsfile
                string newsFile=path_temp_folder+FileSystem.PathDelimiter+"news.txt";
                sw=new StreamWriter(newsFile);

                sw.WriteLine("##3 Serenity");
                sw.WriteLine("##0");
                sw.WriteLine("##0 Entwicklerserver des Invertika Projektes");
                sw.WriteLine("##0 Automatisches Update wird nach jedem");
                sw.WriteLine("##0 Commit im Repository vorgenommen.");
                sw.WriteLine("##0");
                sw.WriteLine("##0 Status: in Betrieb");
                sw.WriteLine("##0 Autoupdate vom {0}, {1} Uhr.", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());
                sw.WriteLine("##0");
                sw.WriteLine("##2 Das Invertika Development Team");
                sw.WriteLine("##0");
                sw.Close();

                //Upload
                Console.WriteLine("Beginne FTP Upload der Update Dateien...");
                FTPSClient Client=new FTPSClient();

                NetworkCredential networkCredential=new NetworkCredential();
                networkCredential.Domain=ftp_update_server;
                networkCredential.UserName=ftp_update_user;
                networkCredential.Password=ftp_update_password;

                Console.WriteLine("Verbinde mich mit FTP {0} mittels des Nutzers {1}.", ftp_update_server, ftp_update_user);

                Client.Connect(networkCredential.Domain, networkCredential, ESSLSupportMode.ClearText);

                List<string> currentFTPFiles=Client.GetDirectoryFiles(""); //TODO muss getestet werden

                Console.WriteLine("Lösche bestehende Updatedateien auf dem FTP Server...");
                foreach(string i in currentFTPFiles)
                {
                    if(i.IndexOf("update")!=-1)
                    {
                        Client.DeleteFile(i);
                    }
                }

                Console.WriteLine("Lade Updatedatei hoch...");
                Client.PutFile(zipFilename, FileSystem.GetFilename(zipFilename));
                Client.PutFile(resFile, FileSystem.GetFilename(resFile));
                Client.PutFile(newsFile, FileSystem.GetFilename(newsFile));

                Client.Close();
            }
            #endregion

            #region Server wieder starten
            Console.WriteLine("Starte Server neu...");
            Directory.SetCurrentDirectory(path_server_root);
            ProcessHelpers.StartProcess(path_server_start_script, "", false);
            #endregion

            #region Clientdaten Data erzeugen und hochladen
            if(activate_data)
            {
                //Upload
                Console.WriteLine("Beginne FTP Upload der Data Dateien...");
                FTPSClient ClientData=new FTPSClient();

                NetworkCredential networkCredential=new NetworkCredential();
                networkCredential.Domain=ftp_data_server;
                networkCredential.UserName=ftp_data_user;
                networkCredential.Password=ftp_data_password;

                Console.WriteLine("Verbinde mich mit FTP {0} mittels des Nutzers {1}.", ftp_data_server, ftp_data_user);

                ClientData.Connect(networkCredential.Domain, networkCredential, ESSLSupportMode.ClearText);

                Console.WriteLine("Lade Data Dateien hoch...");

                foreach(string ftpfile in clientDataFiles)
                {
                    string relativeName=FileSystem.GetRelativePath(ftpfile, clientPath);
                    string dirToCreate=FileSystem.GetPath(relativeName, true);

                    if(dirToCreate!="")
                    {
                        string[] folders=dirToCreate.Split(FileSystem.PathDelimiter);
                        string dirTemp="";

                        foreach(string i in folders)
                        {
                            if(i.Trim()=="") continue;
                            if(i=="/") continue;

                            dirTemp+=i+FileSystem.PathDelimiter;

                            try
                            {
                                ClientData.CreateDirectory(dirTemp);
                            }
                            catch
                            {
                            }
                        }
                    }

                    Console.WriteLine("Datei {0} wird hochgeladen...", relativeName);
                    ClientData.PutFile(ftpfile, relativeName);
                }

                ClientData.Close();
            }
            #endregion

            #region IRC Message absetzen und aus Channel verschwinden
            if(irc_active)
            {
                Console.WriteLine("Sende IRC Nachricht...");
                irc.SendMessage(SendType.Message, irc_channel, String.Format("Autoupdate wurde auf dem Server {0} beendet und manaserv wieder gestartet.", misc_servername));
                Thread.Sleep(15000);
                irc.Disconnect();
            }
            #endregion

            #region Ende
            Console.WriteLine("Autoupdate beenden");
            #endregion
        }
Exemplo n.º 6
0
        public static void Main(string[] args)
        {
            //Options
            if(!FileSystem.ExistsFile("config.xml"))
            {
                Console.WriteLine("No config.xml file found.");
                return;
            }

            XmlData Options=new XmlData("config.xml");

            recieverMail=Options.GetElementAsString("xml.SMTP.RecieverMail");

            smtpserver=Options.GetElementAsString("xml.SMTP.Server");
            senderMail=Options.GetElementAsString("xml.SMTP.SenderMail");
            smtpUsername=Options.GetElementAsString("xml.SMTP.Username");
            smtpPassword=Options.GetElementAsString("xml.SMTP.Password");

            //Files
            Dictionary<string, string> commandLine=CommandLineHelpers.GetCommandLine(args);
            List<string> files=new List<string>();

            bool convert=commandLine.ContainsKey("convert");
            bool merge=commandLine.ContainsKey("merge");

            List<string> clFiles=CommandLineHelpers.GetFilesFromCommandline(commandLine);

            foreach(string clFile in clFiles)
            {
                if(FileSystem.IsFile(clFile))
                {
                    files.Add(clFile);
                }
                else
                {
                    files.AddRange(FileSystem.GetFiles(clFile, true));
                }
            }

            if(files.Count==0)
            {
                Console.WriteLine("No files specified.");
                return;
            }

            if(merge)
            {
                string name=FileSystem.GetValidFilename(files[0]) + " (merged).html";
                StreamWriter writer=new StreamWriter(name);

                writer.WriteLine("<html>");
                writer.WriteLine("<head>");
                writer.WriteLine("</head>");
                writer.WriteLine("<body>");

                foreach(string file in files)
                {
                    string[] lines=File.ReadAllLines(file);

                    if(FileSystem.GetExtension(file)=="txt") //Txt aufbereiten
                    {
                        foreach(string line in lines)
                        {
                            writer.WriteLine("{0}<br/>", line);
                        }
                    }
                    else
                    {
                        foreach(string line in lines)
                        {
                            writer.WriteLine(line);
                        }
                    }
                }

                writer.WriteLine("</body>");
                writer.WriteLine("</html>");

                writer.Close();

                files.Clear();
                files.Add(name);
            }

            //Send Files
            foreach(string file in files)
            {
                string fileSend=file;

                //Preconvert
                if(FileSystem.GetExtension(fileSend)=="txt") //Txt aufbereiten
                {
                    string htmlFile=FileSystem.GetPath(file)+FileSystem.GetFilenameWithoutExt(file)+".html";
                    ConvertTextFile(file, htmlFile);
                    fileSend=htmlFile;
                }

                //Sending
                string subject="";
                if(convert)
                {
                    subject="convert";
                }

                Console.WriteLine("Send file {0}...", FileSystem.GetFilename(file));
                SMTP.SendMailMessageWithAuthAndAttachment(smtpserver, smtpUsername, smtpPassword, senderMail, "kindleuploader", recieverMail, recieverMail, subject, "", fileSend);
                //FileSystem.RemoveFile(htmlFile);
            }
        }
Exemplo n.º 7
0
        public Observer(string configFile)
        {
            //Config auslesen
            XmlData Options=new XmlData(configFile);

            recieverMail=Options.GetElementAsString("xml.SMTP.RecieverMail");

            smtpserver=Options.GetElementAsString("xml.SMTP.Server");
            senderMail=Options.GetElementAsString("xml.SMTP.SenderMail");
            smtpUsername=Options.GetElementAsString("xml.SMTP.Username");
            smtpPassword=Options.GetElementAsString("xml.SMTP.Password");

            username=Options.GetElementAsString("xml.IRC.UserName");
            realname=Options.GetElementAsString("xml.IRC.RealName");
            ident=Options.GetElementAsString("xml.IRC.Ident");
            server=Options.GetElementAsString("xml.IRC.Server");
            channel=Options.GetElementAsString("xml.IRC.Channel");

            //Timer verbinden
            Timer.Interval=5000;
            Timer.Elapsed+=new ElapsedEventHandler(timer_Tick);
            Timer.Enabled=true;

            //IRC Setup
            irc.SendDelay=200;
            irc.AutoRetry=true;
            irc.ActiveChannelSyncing=true;
            irc.OnChannelMessage+=new IrcEventHandler(OnChannelMessage);

            irc.AutoRejoin=true;
            irc.AutoRejoinOnKick=true;
            irc.AutoRelogin=true;
            irc.AutoRetry=true;

            string[] serverlist;
            serverlist=new string[] { server };
            int port=6667;

            Task.Factory.StartNew( () => {
                while(true)
                {
                    try
                    {
                        irc.Connect(serverlist, port);
                        irc.Login(username, realname, 0, ident);
                        irc.RfcJoin(channel);

                        Console.WriteLine("Connected to "+server+" -> "+channel);

                        irc.Listen();
                        irc.Disconnect();
                    }
                    catch(ConnectionException ex)
                    {
                        string msg="Couldn't connect! Reason: "+ex.Message;
                        Conversion.Add(msg);
                        Console.WriteLine(msg);
                    }
                    catch(Exception ex)
                    {
                        string msg="Another exception: "+ex.Message;
                        Conversion.Add(msg);
                        Console.WriteLine(msg);
                    }

                    Thread.Sleep(75000);
                }
            });
        }