public static void Run(string[] args) { List <string> cmd = new OptionSet().Parse(args); CliUtils.Validate(cmd.Count != 0, AppError.ErrorCode.ArgumentParseError, "no subcommand given"); string subcommand = cmd[0]; MethodInfo[] methods = ( from i in typeof(Methods).GetMethods() let attr = i.GetCustomAttribute <CliMethodAttribute>() where attr != null where attr.Names.Any(_ => _ == subcommand) select i ).ToArray(); CliUtils.Validate(methods.Length == 1, AppError.ErrorCode.ArgumentParseError, $"unknown subcomand ({subcommand})"); MethodInfo method = methods[0]; AppData appData = AppConfig.LoadAppData(); if (method.GetCustomAttribute <CliMethodRequiresAuthorizationAttribute>() != null) { CliUtils.Validate(appData.Authorized, AppError.ErrorCode.AuthorizationError, "should authorize first (type `vk login`)"); } Action <string[], AppData> action = (Action <string[], AppData>)Delegate.CreateDelegate( typeof(Action <string[], AppData>), method); action(args, appData); }
public static void Important(string[] args, AppData appData) { uint n = 0; new OptionSet() { { "n=", _ => n = Convert.ToUInt32(_) } }.Parse(args); CliUtils.Validate(n > 0, AppError.ErrorCode.ArgumentParseError, $"should pass the number of messages to retrieve (-n=..)"); var vk = new VkApi(); vk.Authorize(appData.AccessToken); var messages = vk.Messages.Get(new MessagesGetParams() { Count = n, Filters = MessagesFilter.Important, }).Messages; CliUtils.PresentField("Messages", messages.Count); foreach (var m in messages) { Console.WriteLine(); CliUtils.PresentMessage(m, appData); } }
public static void Logout(string[] args, AppData appData) { CliUtils.Validate(appData.Authorized, AppError.ErrorCode.ApplicationConfigError, "already not authorized"); AppConfig.SaveAppData(new AppData()); Console.WriteLine($"Goodbye, {appData.FullName}!"); }
public static T LoadFromFile <T>(string filePath) { using (var stream = File.OpenRead(filePath)) { var obj = BinaryFormatter_.Deserialize(stream); CliUtils.Validate(obj is T, AppError.ErrorCode.DeserializationError, $"type mismatch (expected {typeof(T).Name}, got {obj.GetType().Name})"); return((T)obj); } }
public static void Login(string[] args, AppData appData) { CliUtils.Validate(!appData.Authorized, AppError.ErrorCode.ApplicationConfigError, "already authorized"); Console.WriteLine("Authorizing in the VK api.."); Console.WriteLine(); Console.WriteLine("Step 1. OAuth authorization."); Console.WriteLine("Visit the following page in your web browser."); Console.WriteLine("Authorize if necessary and copy the code (should appear after #code= in your address bar)."); Console.WriteLine($"https://oauth.vk.com/authorize?client_id={AppId}&redirect_uri=https:%2F%2Foauth.vk.com%2Fblank.html&scope={AccessMagicNumber}"); string code = CliUtils.ReadString("Code: "); Console.WriteLine(); Console.WriteLine("Step 2. Receiving access token."); Console.WriteLine("Sending authorization request.."); AccessTokenResponse resp = JsonModelUtils.ReceiveJson <AccessTokenResponse>( $"https://oauth.vk.com/access_token?client_id={AppId}&client_secret={AppSecret}&code={code}&redirect_uri=https:%2F%2Foauth.vk.com%2Fblank.html"); CliUtils.Validate(String.IsNullOrEmpty(resp.error), AppError.ErrorCode.AuthorizationError, $"{resp.error}, {resp.error_description}"); string accessToken = resp.access_token; Console.WriteLine(); Console.WriteLine("Step 3. VK authorization."); var vk = new VkApi(); vk.Authorize(accessToken); var profileInfo = vk.Account.GetProfileInfo(); string userName = $"{profileInfo.FirstName} {profileInfo.LastName}"; appData = new AppData() { Authorized = true, AccessToken = accessToken, FullName = userName, UserId = Convert.ToInt64(resp.user_id), }; appData.AddAbbr("self", appData.UserId); AppConfig.SaveAppData(appData); Console.WriteLine(); Console.WriteLine($"Welcome, {userName}!"); }
public void DeleteAbbr(string abbr) { CliUtils.Validate(AbbrToId_.ContainsKey(abbr), AppError.ErrorCode.ApplicationConfigError, $"abbreviation '{abbr}' not found"); long id = AbbrToId_[abbr]; CliUtils.Validate(IdToAbbr_.ContainsKey(id) && IdToAbbr_[id] == abbr, AppError.ErrorCode.AssertionFailed); AbbrToId_.Remove(abbr); IdToAbbr_.Remove(id); if (AbbrRooms_.Contains(abbr)) { AbbrRooms_.Remove(abbr); } }
public static void Send(string[] args, AppData appData) { bool edit = false; bool room = false; string[] opts = new OptionSet() { { "e|edit", _ => edit = true }, { "R|room", _ => room = true }, }.Parse(args).ToArray(); long id = appData.GetId(opts.GetArg(1)); bool?roomAbbr = appData.IsRoom(opts.GetArg(1)); if (roomAbbr.HasValue && roomAbbr.Value != room) { Console.WriteLine($"Warning: setting -R|--room flag to {roomAbbr.Value} according to abbreviations data."); room = roomAbbr.Value; } string text = String.Join(" ", from i in Enumerable.Range(2, opts.Length - 2) select opts[i]); if (edit) { CliUtils.Validate(String.IsNullOrWhiteSpace(text), AppError.ErrorCode.ArgumentParseError, "both -e|--edit mode and message body arguments are present"); text = CliUtils.ReadText(ConsoleColor.DarkGreen); CliUtils.Validate(!String.IsNullOrWhiteSpace(text), AppError.ErrorCode.ArgumentParseError, $"empty message"); } else { CliUtils.Validate(!String.IsNullOrWhiteSpace(text), AppError.ErrorCode.ArgumentParseError, "no message body is passed and -e|--edit mode is not enabled"); } var vk = new VkApi(); vk.Authorize(appData.AccessToken); MiscUtils.Send(vk, id, text, room); }
public long GetId(string str) { CliUtils.Validate(!String.IsNullOrWhiteSpace(str), AppError.ErrorCode.ArgumentParseError, "empty id given"); if (AbbrToId_.ContainsKey(str)) { return(AbbrToId_[str]); } else { try { return(Convert.ToInt64(str)); } catch { throw new AppError(AppError.ErrorCode.ArgumentParseError, $"unknown abbr or id: '{str}'"); } } }
public static void Abbr(string[] args, AppData appData) { bool delete = false; bool room = false; string[] opts = new OptionSet() { { "d|delete", _ => delete = true }, { "R|room", _ => room = true }, }.Parse(args).ToArray(); string abbr = opts.GetArg(1); string ids = opts.GetArg(2); if (!delete) { CliUtils.Validate(!String.IsNullOrWhiteSpace(abbr), AppError.ErrorCode.ArgumentParseError, "passed abbreviation is empty"); CliUtils.Validate(!String.IsNullOrWhiteSpace(ids), AppError.ErrorCode.ArgumentParseError, "passed id is empty"); long id; try { id = Convert.ToInt64(ids); } catch { throw new AppError(AppError.ErrorCode.ArgumentParseError, $"unable to convert id '{ids}' to integer"); } appData.AddAbbr(abbr, id, room); appData.SaveChanges(); } else { CliUtils.Validate(ids == null, AppError.ErrorCode.ArgumentParseError, "passed id, but requested abbreviation deletion"); appData.DeleteAbbr(abbr); appData.SaveChanges(); } }