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 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 static void Friend(string[] args, AppData appData) { string[] opts = new OptionSet().Parse(args).ToArray(); long id = appData.GetId(opts.GetArg(1)); var vk = new VkApi(); vk.Authorize(appData.AccessToken); User user; ProfileFields fields = ProfileFields.Nickname | ProfileFields.FirstName | ProfileFields.LastName | ProfileFields.Sex | ProfileFields.Status | ProfileFields.BirthDate | ProfileFields.Relation | ProfileFields.RelationPartner; try { user = vk.Users.Get(id, fields | ProfileFields.Online); } catch (Exception e) { if (e.Message == "Can not convert String to Int64.") { Thread.Sleep(400); user = vk.Users.Get(id, fields); } else { throw; } } CliUtils.PresentField("User name", $"{user.FirstName} {user.LastName}"); CliUtils.PresentField("Online", user.Online.HasValue ? (user.Online.Value ? "online" : "offline") : "unknown", user.Online.HasValue ? (user.Online.Value ? ConsoleColor.DarkGreen : ConsoleColor.DarkBlue) : ConsoleColor.Gray); CliUtils.PresentField("VK ID", user.ScreenName); CliUtils.PresentField("Status", user.Status); CliUtils.PresentField("Sex", user.Sex); CliUtils.PresentField("Birth date", MiscUtils.FormatDate(user.BirthDate)); CliUtils.PresentField("Home town", user.HomeTown); CliUtils.PresentField("Relation", user.Relation); CliUtils.PresentField("Relation partner", user.RelationPartner != null ? $"{user.RelationPartner.FirstName} {user.RelationPartner.LastName}" : null); }
public static void Chat(string[] args, AppData appData) { int p = -1; bool room = false; string[] opts = new OptionSet() { { "p=|prev=", _ => p = Convert.ToInt32(_) }, { "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; } var vk = new VkApi(); vk.Authorize(appData.AccessToken); var msgs = MiscUtils.RecvMessages(vk, id, p >= 0 ? (int?)p : null, false, false); Console.WriteLine("Entering chat mode. Press enter at any time to begin typing."); if (!room) { CliUtils.PresentField("Buddy", appData.GetAbbr(id)); } else { CliUtils.PresentField("Room", appData.GetAbbr(id)); } if (p != 0) { foreach (var m in msgs) { Console.WriteLine(); CliUtils.PresentMessage(m, appData); } } CliUtils.LaunchChatMode(vk, appData, id, room); }
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); } }
static AppConfig() { string userDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var userDataDir = new DirectoryInfo(userDataPath); if (!userDataDir.Exists) { CliUtils.Fail(AppError.ErrorCode.ApplicationConfigError, $"local application data dir ({userDataPath}) does not exist"); } AppDataFile_ = new FileInfo(Path.Combine(userDataDir.FullName, "VkCli.dat")); if (!AppDataFile_.Exists) { SaveAppData(new AppData()); } }
public void Display() { if (Incoming_.Count == 0) { return; } foreach (var msg in Incoming_) { Console.WriteLine(); CliUtils.PresentMessage(msg, AppData); } Incoming_.Clear(); HorizontalLine(); }
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 static void Room(string[] args, AppData appData) { string[] opts = new OptionSet() { }.Parse(args).ToArray(); long id = appData.GetId(opts.GetArg(1)); var vk = new VkApi(); vk.Authorize(appData.AccessToken); var res = vk.Messages.GetChat(id); CliUtils.PresentField("Title", res.Title); CliUtils.PresentField("Admin", appData.GetAbbr(res.AdminId ?? 0)); CliUtils.PresentField("Users", String.Join(" ", from i in res.Users select appData.GetAbbr(i))); }
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 Profile(string[] args, AppData appData) { var vk = new VkApi(); vk.Authorize(appData.AccessToken); var profile = vk.Account.GetProfileInfo(); CliUtils.PresentField("User name", $"{profile.FirstName} {profile.LastName}"); CliUtils.PresentField("VK ID", profile.ScreenName); CliUtils.PresentField("Status", profile.Status); CliUtils.PresentField("Sex", profile.Sex.HasValue ? profile.Sex.Value.ToString() : null); CliUtils.PresentField("Birth date", MiscUtils.FormatDate(profile.BirthDate)); CliUtils.PresentField("Home town", profile.HomeTown); CliUtils.PresentField("Relation", profile.Relation.HasValue ? profile.Relation.Value.ToString() : null); CliUtils.PresentField("Relation partner", profile.RelationPartner != null ? $"{profile.RelationPartner.FirstName} {profile.RelationPartner.LastName}" : null); }
public static void Recv(string[] args, AppData appData) { bool quiet = false; bool all = false; uint n = 200; bool reverse = false; bool room = false; string[] opts = new OptionSet() { { "q|quiet", _ => quiet = true }, { "a=|all=", _ => { all = true; n = Convert.ToUInt32(_); } }, { "r|reverse", _ => reverse = 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; } var vk = new VkApi(); vk.Authorize(appData.AccessToken); var msgs = MiscUtils.RecvMessages(vk, id, all ? (int?)n : null, reverse, quiet); if (msgs.Count > 0) { CliUtils.PresentField("Messages", msgs.Count, ConsoleColor.Magenta); CliUtils.PresentField("Quiet", quiet); foreach (var m in msgs) { Console.WriteLine(); CliUtils.PresentMessage(m, appData); } } }
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(); } }
public static void State(string[] args, AppData appData) { bool accessToken = false; new OptionSet() { { "access-token", _ => accessToken = true }, }.Parse(args); CliUtils.PresentField("State", appData.Authorized ? "authorized" : "not authorized", appData.Authorized ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed); if (accessToken) { CliUtils.PresentField("Access token", appData.AccessToken); } CliUtils.PresentField("User name", appData.FullName); }
public static void Check(string[] args, AppData appData) { bool all = false; new OptionSet() { { "a|all", _ => all = true } }.Parse(args); var vk = new VkApi(); vk.Authorize(appData.AccessToken); var dialogs = vk.Messages.GetDialogs(new MessagesDialogsGetParams() { Count = 200, Unread = !all, }); var msgs = ( from m in dialogs.Messages where !all || m.ChatId == null select m ).ToList(); if (msgs.Count == 0) { return; } CliUtils.PresentField("Dialogs", msgs.Count, ConsoleColor.Magenta); Console.WriteLine(); foreach (var m in msgs) { Console.WriteLine(); CliUtils.PresentDialog(m, appData); } }
public static void HorizontalLine() { Console.WriteLine(); CliUtils.WriteLineColor("***", ConsoleColor.White); }