コード例 #1
0
        static void Main(string[] args)
        {
            try
            {
                if (System.Threading.Thread.CurrentThread.CurrentCulture.Name.StartsWith("zh"))
                {
                    language = JsonConvert.DeserializeObject <Language>(Encoding.UTF8.GetString(Properties.Resources.zh_tw));                                                                            //假如是中文語系,就使用中文
                }
                else
                {
                    language = new Language();  //否則,英文
                }
            }
            catch (Exception) { language = new Language(); /*這邊是當跳出錯誤時,使用英文。正常來說是不會有錯誤才對,但有次比賽拿來做測試的時候出了錯誤,也抓不到點,就先認定是語系的問題了*/ }

            Console.Title = language.AppTitle;

            if (OsuPathResolver.Instance.OsuIsRunning)
            {
                FormatWrite(language.DetectionOsuIsRunning, ConsoleColor.Red);
            }

            OpenFileDialog openFileDialog = new OpenFileDialog(); //選擇收藏夾檔案的對話方塊

            openFileDialog.AddExtension    = true;
            openFileDialog.CheckFileExists = true;
            openFileDialog.CheckPathExists = true;
            openFileDialog.DefaultExt      = "json";
            openFileDialog.Filter          = language.OpenFileFilter;
            openFileDialog.Multiselect     = false;

            if (openFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                Exit(language.PleaseSelectCollection, true);
            }

            JsonData collectionData = null;

            try { collectionData = JsonConvert.DeserializeObject <JsonData>(File.ReadAllText(openFileDialog.FileName)); } //讀取收藏夾資料
            catch (Exception) { }
            if (collectionData == null || collectionData.collection_data == null)
            {
                Exit(language.ReadCollectionFail, true);
            }

            string osuPath = OsuPathResolver.Instance.GetOsuDir((path) => { //第一次會先偵測osu的路徑,然後提示使用者是否正確
                var dialogResult = MessageBox.Show(
                    string.Format(
                        language.ConfirmOsuPath, Environment.NewLine + path, Environment.NewLine),
                    "", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                return(dialogResult == DialogResult.Yes);
            }, (text) => {
                FolderBrowserDialog dialog = new FolderBrowserDialog(); //假如是錯誤的,那就開個資料夾選擇對話框,讓使用者自行選擇osu的路徑

                dialog.ShowNewFolderButton = false;
                dialog.Description         = language.PleaseSelectOsuPath;
                dialog.RootFolder          = Environment.SpecialFolder.MyComputer;
                if (dialog.ShowDialog() == DialogResult.OK && Directory.Exists(dialog.SelectedPath))
                {
                    return(dialog.SelectedPath);
                }
                return("");
            });

            if (osuPath == string.Empty || !Directory.Exists(osuPath))
            {
                Exit(language.NeedValidOsuPath, true);
            }
            if (!osuPath.EndsWith("\\"))
            {
                osuPath += "\\";
            }

            FormatWrite(string.Format(language.OsuPath, osuPath), ConsoleColor.Yellow);
            OsuFileIo.OsuSettings.Load(osuPath);
            OsuFileIo.OsuDatabase.Load(osuPath + "osu!.db"); //載入osu的資料庫來抓取songs的資料夾路徑

            List <BeatmapData> needDownloadBeatmapList = new List <BeatmapData>();
            var collectionManager = new CollectionsManager(OsuFileIo.OsuDatabase.LoadedMaps.Beatmaps); Collection collection;                          //初始化目前osu所有的Beatmap

            collectionManager.EditCollection(CollectionEditArgs.AddCollections(OsuFileIo.CollectionLoader.LoadCollection(osuPath + "collection.db"))); //載入原先的收藏夾

            foreach (CollectionData item in collectionData.collection_data)
            {
                FormatWrite(string.Format(language.CollectionName, item.collection_name), ConsoleColor.Yellow);

                if (collectionManager.CollectionNameExists(item.collection_name))
                {
                    collection = collectionManager.GetCollectionByName(item.collection_name);                                                               //如果收藏夾已經存在,就讀取出來
                }
                else
                {
                    collection = new Collection(OsuFileIo.LoadedMaps)
                    {
                        Name = item.collection_name
                    }
                };                                                                                      //否則新建一個

                foreach (BeatmapData item2 in item.beatmap_data)
                {
                    if (!collection.AllBeatmaps().Any((x) => x.MapId == item2.beatmap_id)) //讀取收藏夾內的Beatmap,如果要匯入的收藏夾Beatmap ID不存在於收藏夾內,那就新增進去
                    {
                        FormatWrite(string.Format(language.AddBeatmapToCollection, item2.beatmap_name), ConsoleColor.Green);
                        collection.AddBeatmapByHash(item2.beatmap_md5);                                         //新增Beatmap,使用Hash新增法
                        if (!OsuFileIo.OsuDatabase.LoadedMaps.Beatmaps.Any((x) => x.MapId == item2.beatmap_id)) //如果osu資料庫裡面沒有該Beatmap
                        {
                            needDownloadBeatmapList.Add(item2);                                                 //就新增到下載清單內
                            FormatWrite(language.NeedDownloadBeatmap, ConsoleColor.Cyan);
                        }
                    }
                }

                collectionManager.EditCollection(CollectionEditArgs.RemoveCollections(new Collections()
                {
                    collection
                }));                                                                                                      //先把收藏夾移除
                collectionManager.EditCollection(CollectionEditArgs.AddCollections(new Collections()
                {
                    collection
                }));                                                                                                   //再把收藏夾新增,以達成重整的效果
            }

            if (needDownloadBeatmapList.Count != 0) //如果下載清單數量不為0,就進入下載程序
            {
                FormatWrite(language.DownloadBeatmapInfo, ConsoleColor.Green);
                CookieAwareWebClient cookieAwareWebClient = new CookieAwareWebClient(); //CollectionManager提供的class,可以讓WebClient使用cookie的功能
                string username, password;
                do
                {
                    Console.Write(language.OsuUsername); username = Console.ReadLine();
                    Console.Write(language.OsuPassword); password = "";
                    do
                    {
                        ConsoleKeyInfo key = Console.ReadKey(true);
                        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                        {
                            password += key.KeyChar;
                            Console.Write("*");
                        }
                        else
                        {
                            if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                            {
                                password = password.Substring(0, (password.Length - 1));
                                Console.Write("\b \b");
                            }
                            else if (key.Key == ConsoleKey.Enter)
                            {
                                Console.WriteLine();
                                break;
                            }
                        }
                    } while (true);

                    try { if (!cookieAwareWebClient.Login(loginAddress, string.Format(loginDataStr, username, password)).Contains("I don't have an account"))
                          {
                              break;
                          }
                    }                                                                                                                                                  //登入失敗的話,回傳的網頁資料會有I don't have an account
                    catch (Exception ex) { Exit(string.Format(language.LoginErrorElseReason, ex.Message)); }

                    FormatWrite(language.LoginError, ConsoleColor.Red);
                } while (true);

                bool downloadVideo = MessageBox.Show(language.DownloadBeatmapWithVideo, "", MessageBoxButtons.YesNo) == DialogResult.Yes; //提示下載時是否包含背景影片

                needDownloadBeatmapList.ForEach((item) => {
                    string savePath = OsuFileIo.OsuSettings.CustomBeatmapDirectoryLocation + item.beatmap_setid + " " + StripInvalidCharacters(item.beatmap_name) + ".osz"; //存放路徑: osu的songs資料夾 + BeatmapSet ID + BeatmapSet Name
                    if (!File.Exists(savePath))
                    {
                        FormatWrite(string.Format(language.DownloadBeatmapName, Path.GetFileName(savePath)), ConsoleColor.Green);
                        try { File.WriteAllBytes(savePath, cookieAwareWebClient.DownloadData("https://osu.ppy.sh/d/" + item.beatmap_setid + (downloadVideo ? "n" : ""))); }
                        catch (Exception ex) { Console.WriteLine(string.Format(language.DownloadFali, ex.Message)); }
                    }
                    else
                    {
                        FormatWrite(string.Format(language.DownloadDone, Path.GetFileName(savePath)), ConsoleColor.Yellow);
                    }
                });
            }

            string backupName = "collection.db-" + DateTime.Now.ToFileTime() + ".bak"; //備份舊的收藏夾檔案

            File.Move(osuPath + "collection.db", osuPath + backupName);                //然後覆蓋新的收藏夾檔案
            Console.WriteLine(string.Format(language.BackupCollectionTo, osuPath + backupName));

            Console.WriteLine(language.WritingNewCollection);
            OsuFileIo.CollectionLoader.SaveOsuCollection(collectionManager.LoadedCollections, osuPath + "collection.db");

            if (OsuPathResolver.Instance.OsuIsRunning)
            {
                if (needDownloadBeatmapList.Count != 0)
                {
                    Exit(language.WriteDone1);
                }
                else
                {
                    Exit(language.WriteDone2);
                }
            }
            else
            {
                if (needDownloadBeatmapList.Count != 0)
                {
                    Exit(language.WriteDone3);
                }
                else
                {
                    Exit(language.WriteDone4);
                }
            }
        }
コード例 #2
0
ファイル: WebpageService.cs プロジェクト: emcc4691/SpiderVlad
 public WebpageService()
 {
     WebClient = new CookieAwareWebClient();
     WebClient.Login(Settings.LoginUrl, Settings.LoginPostUrl);
 }
コード例 #3
0
    static void Main()
    {
        try{
            String[] configs       = File.ReadAllText(Directory.GetCurrentDirectory() + @"/configs.csv").Split(',');
            var      email         = configs[0];
            var      password      = configs[1];
            var      finalLocation = configs[2];
            var      smtpUser      = configs[3];
            var      smtpPass      = configs[4];
            var      alertEmail    = configs[5];
            var      phone         = configs[6];

            var location = Directory.GetCurrentDirectory() + "/";

            //Json copy pasted from a "get all" request to MISO's api
            var json = "{\"QueryValues\":{\"rctype\":\"Load Pocket Report\"},\"NavigationItem\":{\"ParentPropertyValue\":\"Load Pocket Report\",\"ChildPropertySystemName\":null,\"DisplayResultInGrid\":false,\"GridMetadataColumns\":[],\"ResultSortField\":null,\"ResultSortDirection\":null,\"UseDynamicChoiceMode\":null,\"UseDynamicDateNavigation\":false,\"UseDynamicYearNavigation\":false,\"UseDynamicQuarterNavigation\":false,\"UseDynamicMonthNavigation\":false,\"UseDynamicDayNavigation\":false,\"ChildDocumentNavigationItems\":null,\"Title\":\"\",\"Summary\":\"<p><a title=\\\"MISO Load Pocket Report Readers Guide\\\" href=\\\"/api/documents/getbyguid/c35f6b50-fdc2-5742-bd3c-cf185c23ee57\\\">MISO Load Pocket Report Readers Guide</a></p>\",\"LoadedNavigableDocuments\":[{\"FileName\":\"Load_Pocket_20171121.zip\",\"Name\":\"Load Pocket 20171121\",\"Url\":\"/api/documents/getbymediaid/129294\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129294,\"Uploaded\":\"2018-02-26T19:42:50Z\",\"UploadedBy\":34,\"ObjectId\":137504,\"Created\":\"2018-02-26T19:43:06Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:10Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"221e5d05-c71b-5d66-996c-d9c22d10437c\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171122.zip\",\"Name\":\"Load Pocket 20171122\",\"Url\":\"/api/documents/getbymediaid/129295\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129295,\"Uploaded\":\"2018-02-26T19:42:56Z\",\"UploadedBy\":34,\"ObjectId\":137505,\"Created\":\"2018-02-26T19:43:12Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:15Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"e3aaf099-2679-5c51-a1d3-5d309a0447be\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171123.zip\",\"Name\":\"Load Pocket 20171123\",\"Url\":\"/api/documents/getbymediaid/129233\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129233,\"Uploaded\":\"2018-02-26T19:27:55Z\",\"UploadedBy\":34,\"ObjectId\":137443,\"Created\":\"2018-02-26T19:28:11Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:17Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"018ab122-2ac6-52cc-a241-9f033d9b5143\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171124.zip\",\"Name\":\"Load Pocket 20171124\",\"Url\":\"/api/documents/getbymediaid/129234\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129234,\"Uploaded\":\"2018-02-26T19:28:05Z\",\"UploadedBy\":34,\"ObjectId\":137444,\"Created\":\"2018-02-26T19:28:21Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:27Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"f026d520-5e27-51c1-9858-a08fea7fefdd\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171125.zip\",\"Name\":\"Load Pocket 20171125\",\"Url\":\"/api/documents/getbymediaid/129235\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129235,\"Uploaded\":\"2018-02-26T19:28:16Z\",\"UploadedBy\":34,\"ObjectId\":137445,\"Created\":\"2018-02-26T19:28:31Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:38Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"2f4ae535-4c20-57b1-9060-c63a5298229b\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171126.zip\",\"Name\":\"Load Pocket 20171126\",\"Url\":\"/api/documents/getbymediaid/129296\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129296,\"Uploaded\":\"2018-02-26T19:43:02Z\",\"UploadedBy\":34,\"ObjectId\":137506,\"Created\":\"2018-02-26T19:43:18Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:21Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"7763eb39-3bd5-53da-a29a-91be0327d7e2\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171127.zip\",\"Name\":\"Load Pocket 20171127\",\"Url\":\"/api/documents/getbymediaid/129297\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129297,\"Uploaded\":\"2018-02-26T19:43:08Z\",\"UploadedBy\":34,\"ObjectId\":137507,\"Created\":\"2018-02-26T19:43:24Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:27Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"eb27d73c-aa3a-5820-98c8-23fd308d5d18\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171128.zip\",\"Name\":\"Load Pocket 20171128\",\"Url\":\"/api/documents/getbymediaid/129236\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129236,\"Uploaded\":\"2018-02-26T19:28:26Z\",\"UploadedBy\":34,\"ObjectId\":137446,\"Created\":\"2018-02-26T19:28:42Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:47Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"1e6b4040-2c1b-538f-8091-82f51514dcd4\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171129.zip\",\"Name\":\"Load Pocket 20171129\",\"Url\":\"/api/documents/getbymediaid/129237\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129237,\"Uploaded\":\"2018-02-26T19:28:36Z\",\"UploadedBy\":34,\"ObjectId\":137447,\"Created\":\"2018-02-26T19:28:51Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:57Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"c9e3df76-6555-5ba6-8f1a-a1476c7a5a1f\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171130.zip\",\"Name\":\"Load Pocket 20171130\",\"Url\":\"/api/documents/getbymediaid/129298\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129298,\"Uploaded\":\"2018-02-26T19:43:14Z\",\"UploadedBy\":34,\"ObjectId\":137508,\"Created\":\"2018-02-26T19:43:30Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:33Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"48c75229-1268-5621-8353-57cc4e89cad6\",\"accesstype\":\"Visitors-RA\"}}],\"TotalAvailableResults\":98},\"Filters\":[{\"PropertyName\":\"rctype\",\"Value\":\"\"}],\"EnableFollowDocuments\":null,\"Top\":null,\"Skip\":10}";

            //Stops from running if files for the current date already exist
            if (FileCheck.Check(finalLocation))
            {
                return;
            }

            var webClient = new CookieAwareWebClient();


            var collection = new NameValueCollection();
            collection.Add("Email", email);
            collection.Add("Password", password);



            Console.Write("Attempting to log in to MISO website... \n");
            webClient.Login("https://www.misoenergy.org/Account/Login", collection);

            //Post JSON using cookie authenticated client and JSON from standard request
            Console.Write("Acquiring document list from MISO... \n");
            var response = webClient.PostPage("https://www.misoenergy.org/api/documents/getnavigabledocuments", json);

            //Parse the response JSON
            JObject parsedResponse = JObject.Parse(response);
            var     list           = parsedResponse["documents"].OrderByDescending(t => t["FileName"]).ToList();
            var     single         = list.FirstOrDefault();
            var     url            = "https://www.misoenergy.org" + single["Url"];
            var     filename       = single["FileName"].ToString();

            //Make sure that the load pocket file that is the "latest" is from the current date.
            if (filename != "Load_Pocket_" + DateTime.Now.ToString("yyyyMMdd") + ".zip")
            {
                throw new Exception("The current load pocket file is not from the current date.");
            }

            //Download zip file, store temporarily in location and the extract to finalLocation before deleting zip from location
            webClient.GetFileAndMove(url, filename, location, finalLocation);


            //Used to send alert on working instance
            if (FileCheck.Check(finalLocation))
            {
                Console.Write("Attempting to send email notifications... \n");
                MailHelper.SendAlert(smtpUser, smtpPass, alertEmail, phone);
            }

            Console.Write(filename + " was extracted to " + finalLocation + "");
        }
        catch (Exception ex)
        {
            Console.Write(ex);
        }
    }