public uint GetCount(VK.UID page) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); if (!page.IsValid) throw new ArgumentException("Invalid page UID specified."); // Request var args = new NameValueCollection(); args.Add("owner_id", page.Value.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.getCount", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.getCount", args); #endif // Check uint iReturn = 0; if (response == null || string.IsNullOrEmpty(response.InnerText) || response.NodeType != XmlNodeType.Element || !uint.TryParse(response.InnerText, out iReturn)) throw new VK.APIImplException(HostSession, "status.get", "Unexpected server reply."); // Done return iReturn; }
public VK.PageStatus Get(VK.UID page) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Statuses); if (!page.IsValid) throw new ArgumentException("Invalid UID specified: " + page.Value); // Request var args = new NameValueCollection(); args.Add("user_id", page.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("status.get", args); #else XmlElement response = HostSession.Network.XmlMethodCall("status.get", args); #endif // Check if (response == null || response["text"] == null) throw new VK.APIImplException(HostSession, "status.get", "Unexpected server reply."); // Parse var status = new VK.PageStatus(); status.Parse(response); // Done return status; }
/// <summary> /// Builds "scope" parameter for VK API login from VK.SecurityFlagflags /// </summary> /// <param name="scopeFlags">Flags</param> public static string GetAuthScopeString(VK.SecurityFlag scopeFlags) { var flags = Enum.GetValues(typeof(VK.SecurityFlag)) as VK.SecurityFlag[]; var scope_s = string.Empty; foreach (var flag in flags) { if (flag != VK.SecurityFlag.None && (scopeFlags & flag) == flag) scope_s += VK.InternalName.GetValue(flag) + ','; } return scope_s.TrimEnd(','); }
/// <summary> /// Initializes new VKSession instance. /// </summary> /// <param name="appID">Registered VK application ID, required to work with API.</param> /// <param name="networkBaseImplType">What network driver class type to use (must implement NetworkBase class). If not set, NetworkDefault is used.</param> public VKSession(VK.AppID appID, Type networkBaseImplType = null) { this.AppID = appID; // Initialize network if (networkBaseImplType == null) Network = new NetworkDefault(this); else Network = (NetworkBase) Activator.CreateInstance(networkBaseImplType, this); // Empty security options SecuritySettings = VK.SecurityFlag.None; // Initialize API components this.Status = new VKAPIStatusMethods(this); this.Audio = new VKAPIAudioMethods(this); }
public void Reorder(VK.Audio audio, VK.Audio after, VK.Audio before) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); // Check if (before == null && after == null) throw new ArgumentNullException("before", "You have to specify 'after' or 'before', or both."); if ((before != null && audio.ID.Page != before.ID.Page) || (after != null && audio.ID.Page != after.ID.Page)) throw new ArgumentException("One of arguments specified is invalid. All Audios must belong to same owner(page)."); else if (!audio.ID.Page.IsCommunity && audio.ID.Page != HostSession.UserPage) throw new ArgumentException("Cannot modify other's page audios."); // Request var args = new NameValueCollection(); if (audio.ID.Page != HostSession.UserPage) args.Add("oid", audio.ID.Page.ToString()); args.Add("aid", audio.ID.Ordinal.ToString()); if (after != null) args.Add("after", after.ID.Ordinal.ToString()); else args.Add("after", "0"); if (before != null) args.Add("before", before.ID.Ordinal.ToString()); else args.Add("before", "0"); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.reorder", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.reorder", args); #endif // Check int opResult = -1; if (response == null || !int.TryParse(response.InnerText, out opResult)) throw new VK.APIImplException(HostSession, "audio.reorder", "Unexpected server reply."); // Check opResult if (opResult != 1) throw new VK.APIImplException(HostSession, "audio.reorder", "Audio reorder failed, result code: " + opResult + '.'); }
public void Update(VK.Audio audio) #endif { // Call Update(ref VK.Audio[]) var audios = new VK.Audio[1] { audio }; #if NEWSTYLE int updatedCount = await Update(audios); #else int updatedCount = Update(audios); #endif if (updatedCount != 1) throw new VK.APIImplException(HostSession, "audio.getById","updatedCount is " + updatedCount + ", expected: 1."); // Done audio = audios[0]; }
public async Task Reorder(VK.Audio audio, VK.Audio after, VK.Audio before)
public async Task Set(VK.PageStatus status)
public async Task<VK.PageStatus> Get(VK.UID page)
/// <summary> /// Allows you to set captcha solution for next API request (used for delayed captcha validation). /// </summary> /// <param name="captchaKey">Captcha key</param> public void SetCaptchaKey(VK.CaptchaEventArgs captchaKey) { if (captchaKey != null && (!captchaKey.IsSolved || !captchaKey.IsValidCaptcha)) throw new ArgumentException("Specified captchaKey is not valid or not solved'."); pendingCaptchaKey = captchaKey; }
public async Task<int> Update(VK.Audio[] audios)
GetAlbums(VK.UID page, int offset, uint count) { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); if (!page.IsValid) throw new ArgumentException("Invalid page UID specified."); else if (count < 1 || count > 100) throw new ArgumentOutOfRangeException("count", "Count of albums to fetch per one request must be in range [1-100]."); else if (offset < -1) throw new ArgumentOutOfRangeException("offset", "Invalid 'offset' value."); // Request var args = new NameValueCollection(); args.Add("owner_id", page.ToString()); if (offset != -1) args.Add("offset", offset.ToString()); args.Add("count", count.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.getAlbums", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.getAlbums", args); #endif // Check if (response == null) throw new VK.APIImplException(HostSession, "audio.getAlbums", "Unexpected server reply."); uint totalCount = 0; // Parse VK.AudioAlbum[] albums = null; if (response.GetAttribute("list") == "true") // Notice: maybe this is incorrect, but currently okay { int iCount = 0; foreach (XmlElement node in response.ChildNodes) { // Ensure it is what we expect if (iCount == 0 && node.Name == "count") { // We have totalCount totalCount = uint.Parse(node.InnerText); if (count <= 0 || count > totalCount) count = totalCount; albums = new VK.AudioAlbum[count]; continue; } else if (node.Name != "album") throw new NotSupportedException("Unknown node in xml server reply; expected 'album', got '" + node.Name + "'."); albums[iCount++].Parse(node); } } // Done return new ArraySegment<VK.AudioAlbum,uint>(albums, totalCount); }
public async Task<uint> GetCount(VK.UID page)
public VK.Audio[] Get(VK.UID page, bool needUserDigest, VK.AudioOwnerDigest userDigest, VK.AudioAlbum album = null, int offset = 0, int count = -1) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); if (!page.IsValid) throw new ArgumentException("Invalid page UID specified."); else if (album != null && album.ID.Page != page) throw new ArgumentException("Invalid 'album' specified, this album does not belong to the specified page."); else if (album != null && !album.IsValid) throw new ArgumentException("Album does not exists."); else if (offset < -1) throw new ArgumentOutOfRangeException("offset", "Invalid 'offset' value."); // Request var args = new NameValueCollection(); if(page != HostSession.UserPage) args.Add("owner_id", page.Value.ToString()); if (album != null) args.Add("album_id", album.ID.Ordinal.ToString()); if (needUserDigest) args.Add("need_user", "1"); if (offset != -1) args.Add("offset", offset.ToString()); if (count != -1) args.Add("count", count.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.get", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.get", args); #endif // Check if (response == null) throw new VK.APIImplException(HostSession, "audio.get", "Unexpected server reply."); // Parse user digest if (needUserDigest && response["user"] != null) userDigest.Parse(response["user"]); // Parse audios VK.Audio[] audios = null; if (response.GetAttribute("list") == "true") // Notice: maybe this is incorrect, but currently okay { audios = new VK.Audio[response.ChildNodes.Count]; int iCount = 0; foreach (XmlElement node in response.ChildNodes) { // Ensure it is audio if (node.Name != "audio") throw new VK.APIImplException(HostSession, "audio.get", "Unexpected server reply. " + "Unexpected XML node; expected 'audio', got '" + node.Name + "'."); audios[iCount] = new VK.Audio(); audios[iCount++].Parse(node); } } // Done return audios; }
Search(string query, bool queryAutoCorrect, bool searchOwnOnly, bool searchByPerformersOnly, VK.AudioSearchResultSort sortMode, bool onlyWithLyrics, uint offset, uint count) { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); if (query == null) throw new ArgumentNullException("query"); // Request var args = new NameValueCollection(); args.Add("q", query); args.Add("auto_complete", queryAutoCorrect ? "1" : "0"); args.Add("lyrics", onlyWithLyrics ? "1" : "0"); args.Add("performer_only", searchByPerformersOnly ? "1" : "0"); args.Add("sort", ((byte)sortMode).ToString()); args.Add("search_own", searchOwnOnly ? "1" : "0"); args.Add("offset", offset.ToString()); args.Add("count", count.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.search", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.search", args); #endif // Check if (response == null) throw new VK.APIImplException(HostSession, "audio.search", "Unexpected server reply."); uint totalCount = 0; // Parse totalCount if (response["count"] != null) { // We have totalCount totalCount = uint.Parse(response["count"].InnerText); if (count <= 0 || count > totalCount) count = totalCount; response.RemoveChild(response["count"]); } // Parse List<VK.Audio> audios = new List<VK.Audio>(); if (response.GetAttribute("list") == "true") { foreach (XmlElement node in response.ChildNodes) { // Ensure it is what we expect // Ensure it is what we expect if (node.Name != "audio") throw new VK.APIImplException(HostSession, "audio.get", "Unexpected server reply. " + "Unexpected XML node; expected 'audio', got '" + node.Name + "'."); var audio = new VK.Audio(); if (audio.Parse(node)) audios.Add(audio); } } // Done return new ArraySegment<VK.Audio, uint>(audios.ToArray(), totalCount); }
public async Task<VK.Audio[]> Get(VK.UID page, bool needUserDigest, VK.AudioOwnerDigest userDigest, VK.AudioAlbum album = null, int offset = 0, int count = -1)
public VK.Audio[] Get(VK.UID page, VK.AudioAlbum album = null, int offset = 0, int count = -1) #endif { var tmp = new VK.AudioOwnerDigest(); #if NEWSTYLE VK.Audio[] audios = await this.Get(page, false, tmp, album, offset, count); return audios; #else return this.Get(page, false, tmp, album, offset, count); #endif }
public async Task<VK.Audio[]> Get(VK.UID page, VK.AudioAlbum album = null, int offset = 0, int count = -1)
/// <summary> /// You can initialize Audio instance from its identifier. /// Remember that this object will only contain ID untill you, for example, call Audio.Update() method with this Audio as argument. /// </summary> /// <param name="owner">'ownerid_localid' is well-known VK audio identifier format</param> /// <param name="local_id">'ownerid_localid' is well-known VK audio identifier format</param> public Audio FromID(VK.UID owner, uint local_id) { if (owner.Value == 0) throw new ArgumentException("Audio.FromID: Invalid owner id speicfied (0)."); return new Audio { ID = new DualID(owner, local_id) }; }
public int Update(VK.Audio[] audios) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); if (audios == null) throw new ArgumentNullException("audios"); else if (audios.Length == 0) return 0; // Build <audios> string var audios_s = string.Empty; for (int i = 0; i < audios.Length; i++) { // Check if (!audios[i].ID.IsValid) throw new ArgumentException("Invalid Audio identfier specified. " + audios[i]); audios_s += (i > 0 ? "," : "") + audios[i].ID; } // Request var args = new NameValueCollection(); args.Add("audios", audios_s); #if NEWSTYLE var response = await HostSession.Network.AsyncXmlMethodCall("audio.getById", args); #else var response = HostSession.Network.XmlMethodCall("audio.getById", args); #endif // Check if (response == null || response.GetAttribute("list") != "true" || !response.HasChildNodes) throw new VK.APIImplException(HostSession, "audio.getById", "Unexpected server reply."); // Parse int iCount = 0; foreach (XmlElement node in response.ChildNodes) { // Ensure it is audio if (node.Name != "audio") continue; // ParseUpdate int owner_id = int.Parse(node["owner_id"].InnerText); uint local_id = uint.Parse(node["aid"].InnerText); int i = SubFindByID(audios, owner_id, local_id); if (i != -1) { audios[i].Parse(node); iCount++; } } // Done return iCount; }
/// <summary> /// You can specify album by ID. Title value will not be set, of course. /// </summary> /// <param name="owner">Owner page unique identifier</param> /// <param name="localID">Local album id</param> public static AudioAlbum FromID(VK.UID owner, uint localID) { var album = new AudioAlbum(); album.ID = new DualID(owner, localID); return album; }
CreateAlbum(VK.UID page, string albumTitle) { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); if (!page.IsValid) throw new ArgumentException("Invalid page UID specified."); else if (!page.IsCommunity && page != HostSession.UserPage) throw new ArgumentException("Cannot modify other's private page audios."); else if (albumTitle == null) throw new ArgumentNullException("albumTitle", "You have to specify audio album title."); // Request var args = new NameValueCollection(); if (page != HostSession.UserPage) args.Add("group_id", page.AbsoluteValue.ToString()); args.Add("title", albumTitle); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.addAlbum", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.addAlbum", args); #endif // Check if (response == null || response["album_id"] == null) throw new VK.APIImplException(HostSession, "audio.addAlbum", "Unexpected server reply."); // Parse var album = new VK.AudioAlbum(); album.Title = albumTitle; album.ID = new VK.DualID(page, uint.Parse(response["album_id"].InnerText)); // Done return album; }
/// <summary> /// Attempts to authorize the session with direct login method. Uses HTTPS for request. /// </summary> /// <param name="login">Username for login</param> /// <param name="password">Password for login</param> /// <param name="clientSecret">Application secret key</param> /// <param name="securityScope">Security settings and options for session</param> public void Authorize(string login, string password, string clientSecret, VK.SecurityFlag securityScope = VK.SecurityFlag.None) { // Check if (AuthSession.AppID.Value == 0) throw new ArgumentException("Invalid AppID specified for session: 0"); else if (string.IsNullOrEmpty(login)) throw new ArgumentNullException("login"); else if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password"); else if (string.IsNullOrEmpty(clientSecret)) throw new ArgumentNullException("clientSecret"); // Request arguments var args = new NameValueCollection { { "grant_type", "password" }, { "username", login }, { "password", password }, { "client_id", this.AuthSession.AppID.ToString() }, { "client_secret", clientSecret}, { "v", VK.Version.ToString(2) }, { "test_redirect_uri", "1" }, }; if (securityScope != VK.SecurityFlag.None) args.Add("scope", VK.GetAuthScopeString(securityScope)); _retry: // Send the request string url_queryString = NetworkBase.ToQueryString(args, true); string responseJson = AuthSession.Network.HttpGetString("https://oauth.vk.com/token?" + url_queryString); // Process JSON response var json = new JavaScriptSerializer(); var responseDic = json.Deserialize<Dictionary<string, string>>(responseJson); // Check for errors if (responseDic.ContainsKey("error")) { // Gather error profile string error = responseDic["error"]; string errorDescription = (responseDic.ContainsKey("error_description") ? responseDic["error_description"] : "(not specified)"); // Check for errors we can handle switch (error) { case "need_captcha": { // Remove captcha key from previous validation attempt args.Remove("captcha_sid"); args.Remove("captcha_key"); var eventData = VKSession.TriggerCaptchaNeeded(this.AuthSession, new Uri(responseDic["captcha_img"]), responseDic["captcha_sid"]); if (eventData.IsSolved || eventData.Retry) { if (eventData.IsSolved) { // Append arguments with captcha solve key args.Add("captcha_sid", eventData.ID); args.Add("captcha_key", eventData.SolveKey); } // Retry auth goto _retry; } } break; case "need_validation": VKSession.TriggerValidationNeeded(this.AuthSession, new Uri(responseDic["redirect_uri"]), securityScope); break; } // Throw exception var message = string.Format("Type: '{0}', Description: '{1}'", error, errorDescription); throw new VK.APIException(this.AuthSession, "auth_direct", message, VK.APIError.UnspecifiedUnsupported, null, null); } else { string token_s = responseDic["token"]; string userPage_s = responseDic["user_id"]; string expires_in_s = responseDic["expires_in"]; var token = new VK.AuthToken(token_s, long.Parse(expires_in_s)); // NoHTTPS secret string nohttpsSecret = null; if ((securityScope & VK.SecurityFlag.NoHTTPS) == VK.SecurityFlag.NoHTTPS) { // Ensure NoHTTPS authorized if (responseDic.ContainsKey("https_required")) // || !responseDic.ContainsKey("secret")) securityScope ^= VK.SecurityFlag.NoHTTPS; else nohttpsSecret = responseDic["secret"]; } // AssignToken this.AuthSession.AssignToken(token, securityScope, int.Parse(userPage_s), nohttpsSecret); } }
/// <summary> /// Service method to find audio in array by audio id. /// </summary> private int SubFindByID(VK.Audio[] array, int page, uint ordinal) { int i = 0; foreach (var audio in array) { if (audio.ID.Page == page && audio.ID.Ordinal == ordinal) return i; else i++; } return -1; }
/// <summary> /// Initializes new instance with optional parameters. /// </summary> /// <param name="text">Status text</param> /// <param name="audio">Status broadcasting audio</param> public PageStatus(string text = null, VK.Audio audio = null) { this.Text = text; this.Audio = audio; }
public async Task MoveToAlbum(VK.Audio[] audios, VK.AudioAlbum album)
public void Set(VK.PageStatus status) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Statuses); // Request var args = new NameValueCollection(); //args.Add("id", page.ToString()); status.APIDigest(args); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("status.set", args); #else XmlElement response = HostSession.Network.XmlMethodCall("status.set", args); #endif // Check int opResult = -1; if (response == null || string.IsNullOrEmpty(response.InnerText) || response.NodeType != XmlNodeType.Element || !int.TryParse(response.InnerText, out opResult)) throw new VK.APIImplException(HostSession, "status.set", "Unexpected server reply."); // Check opResult if (opResult != 1) throw new VK.APIImplException(HostSession, "status.set", "Status set failed, return code: " + opResult + '.'); }
public void MoveToAlbum(VK.Audio[] audios, VK.AudioAlbum album) #endif { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); // Check if (audios == null) throw new ArgumentNullException("audios"); else if (!album.IsValid) throw new ArgumentException("Invalid AudioAlbum identifier."); else if (!album.ID.Page.IsCommunity && album.ID.Page != HostSession.UserPage) throw new ArgumentException("Cannot modify other's private page audios."); // Construct audios_s var audios_s = string.Empty; for (int i = 0; i < audios.Length; i++) { VK.Audio audio = audios[i]; // Check if (!audios[i].ID.IsValid) throw new ArgumentException("Invalid Audio identifier specified."); if (audio.ID.Page != album.ID.Page) throw new ArgumentException("One of 'audios' array element is invalid. 'audios' may only contain audios from the same page as album."); audios_s += (i > 0 ? "," : "") + audio.ID.Ordinal.ToString(); } // Request var args = new NameValueCollection(); args.Add("album_id", album.ID.Ordinal.ToString()); args.Add("audio_ids", audios_s); if (album.ID.Page.IsCommunity) args.Add("group_id", album.ID.Page.AbsoluteValue.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.moveToAlbum", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.moveToAlbum", args); #endif // Check int opResult = -1; if (response == null || !int.TryParse(response.InnerText, out opResult)) throw new VK.APIImplException(HostSession, "audio.moveToAlbum", "Unexpected server reply."); // Check opResult if (opResult != 1) throw new VK.APIImplException(HostSession, "audio.moveToAlbum", "Move audio to album failed, return code: " + opResult + '.'); // Assign new AlbumID and Album to array elements for (int i = 0; i < audios.Length; i++) { audios[i].KnownAlbumID = album.ID.Ordinal; audios[i].KnownAlbum = album; } // Done }
RemoveAlbum(VK.AudioAlbum album) { // Check HostSession.EnsureHasPermission(VK.SecurityFlag.Audios); // Check if (!album.ID.Page.IsValid) throw new ArgumentException("Invalid owner page UID specified in album."); else if (!album.ID.Page.IsCommunity && album.ID.Page != HostSession.UserPage) throw new ArgumentException("Cannot modify other's private page audios."); else if (!album.IsValid) throw new ArgumentException("Invalid AudioAlbum identifier."); // Request var args = new NameValueCollection(); if (album.ID.Page != HostSession.UserPage) args.Add("gid", album.ID.Page.AbsoluteValue.ToString()); args.Add("album_id", album.ID.Ordinal.ToString()); #if NEWSTYLE XmlElement response = await HostSession.Network.AsyncXmlMethodCall("audio.deleteAlbum", args); #else XmlElement response = HostSession.Network.XmlMethodCall("audio.deleteAlbum", args); #endif // Check int opResult = -1; if (response == null || !int.TryParse(response.InnerText, out opResult)) throw new VK.APIImplException(HostSession, "audio.deleteAlbum", "Unexpected server reply."); // Check opResult if (opResult != 1) throw new VK.APIImplException(HostSession, "audio.deleteAlbum", "AudioAlbum remove failed, result code: " + opResult + '.'); // Done album.ID = new VK.DualID(album.ID.Page, 0); }
public async Task Update(VK.Audio audio)