Advertisement
Guest User

SoundCloud Class (VB.Net) (Requires IDB's http class) Update

a guest
Dec 14th, 2012
1,400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 23.97 KB | None | 0 0
  1. Imports System.Collections.Specialized
  2. Imports System.Text
  3. Imports SoundcloudPlayer.Utility
  4. Imports SoundcloudPlayer.Utility.Http
  5. Imports System.Web
  6. Imports System.Net
  7. Imports System.Text.RegularExpressions
  8. Imports System.Runtime.Serialization
  9. Imports System.IO
  10. Imports System.Xml.Serialization
  11. Imports System.Runtime.Serialization.Json
  12.  
  13. '//////////////////////////////////////////////
  14. '// Note: THIS CLASS IS MADE BY MAVAMAARTEN~ //
  15. '//   YOU CAN USE THIS WHEREEVER YOU WANT    //
  16. '//    BUT IF YOU DO, GIVE CREDIT TO ME      //
  17. '//         (Mavamaarten~) and idb!          //
  18. '//////////////////////////////////////////////
  19.  
  20. Public Class User
  21.       <DataMember(Name:="id")>
  22.       Public Property id As Integer
  23.       <DataMember(Name:="kind")>
  24.       Public Property kind As String
  25.       <DataMember(Name:="permalink")>
  26.       Public Property permalink As String
  27.       <DataMember(Name:="username")>
  28.       Public Property username As String
  29.       <DataMember(Name:="uri")>
  30.       Public Property uri As String
  31.       <DataMember(Name:="permalink_url")>
  32.       Public Property permalink_url As String
  33.       <DataMember(Name:="avatar_url")>
  34.       Public Property avatar_url As String
  35.       <DataMember(Name:="country")>
  36.       Public Property country As String
  37.       <DataMember(Name:="full_name")>
  38.       Public Property full_name As String
  39.       <DataMember(Name:="description")>
  40.       Public Property description As String
  41.       <DataMember(Name:="city")>
  42.       Public Property city As String
  43.       <DataMember(Name:="discogs_name")>
  44.       Public Property discogs_name As String
  45.       <DataMember(Name:="myspace_name")>
  46.       Public Property myspace_name As String
  47.       <DataMember(Name:="website")>
  48.       Public Property website As String
  49.       <DataMember(Name:="website_title")>
  50.       Public Property website_title As String
  51.       <DataMember(Name:="online")>
  52.       Public Property online As String
  53.       <DataMember(Name:="track_count")>
  54.       Public Property track_count As String
  55.       <DataMember(Name:="playlist_count")>
  56.       Public Property playlist_count As Integer
  57.       <DataMember(Name:="plan")>
  58.       Public Property plan As String
  59.       <DataMember(Name:="_favorites_count")>
  60.       Public Property _favorites_count As Integer
  61.       <DataMember(Name:="followers_count")>
  62.       Public Property followers_count As Integer
  63.       <DataMember(Name:="followings_count")>
  64.       Public Property followings_count As Integer
  65.       <DataMember(Name:="private_tracks_count")>
  66.       Public Property private_tracks_count As Integer
  67.       <DataMember(Name:="private_playlists_count")>
  68.       Public Property private_playlists_count As Integer
  69.       <DataMember(Name:="primary_email_confirmed")>
  70.       Public Property primary_email_confirmed As Boolean
  71.  
  72. End Class
  73.  
  74. <XmlRoot("user")>
  75. Public Class ShortUser
  76.       <XmlElement("id")>
  77.       Public Property id As Integer
  78.       <XmlElement("kind")>
  79.       Public Property kind As String
  80.       <XmlElement("permalink")>
  81.       Public Property permalink As String
  82.       <XmlElement("username")>
  83.       Public Property username As String
  84.       <XmlElement("uri")>
  85.       Public Property uri As String
  86.       <XmlElement("permalink_url")>
  87.       Public Property permalink_url As String
  88.       <XmlElement("avatar_url")>
  89.       Public Property avatar_url As String
  90. End Class
  91.  
  92. <XmlRoot("track")>
  93. Public Class Track
  94.       <XmlElement("id")>
  95.       Public Property id As Integer
  96.       <XmlElement("created-at")>
  97.       Public Property created_at As String
  98.       <XmlElement("user-id")>
  99.       Public Property user_id As String
  100.       <XmlElement("duration")>
  101.       Public Property duration As Integer
  102.       <XmlElement("commentable")>
  103.       Public Property commentable As String
  104.       <XmlElement("state")>
  105.       Public Property state As String
  106.       <XmlElement("sharing")>
  107.       Public Property sharing As String
  108.       <XmlElement("tag-list")>
  109.       Public Property tag_list As String
  110.       <XmlElement("permalink")>
  111.       Public Property permalink As String
  112.       <XmlElement("description")>
  113.       Public Property description As String
  114.       <XmlElement("streamable")>
  115.       Public Property streamable As String
  116.       <XmlElement("downloadable")>
  117.       Public Property downloadable As String
  118.       <XmlElement("genre")>
  119.       Public Property genre As String
  120.       <XmlElement("release")>
  121.       Public Property release As String
  122.       <XmlElement("purchase-url")>
  123.       Public Property purchase_url As String
  124.       <XmlElement("label-id")>
  125.       Public Property label_id As String
  126.       <XmlElement("label-name")>
  127.       Public Property label_name As String
  128.       <XmlElement("isrc")>
  129.       Public Property isrc As String
  130.       <XmlElement("video-url")>
  131.       Public Property video_url As String
  132.       <XmlElement("track-type")>
  133.       Public Property track_type As String
  134.       <XmlElement("key-signature")>
  135.       Public Property key_signature As String
  136.       <XmlElement("bpm")>
  137.       Public Property bpm As String
  138.       <XmlElement("title")>
  139.       Public Property title As String
  140.       <XmlElement("release-year")>
  141.       Public Property release_year As String
  142.       <XmlElement("release-month")>
  143.       Public Property release_month As String
  144.       <XmlElement("release-day")>
  145.       Public Property release_day As String
  146.       <XmlElement("original-format")>
  147.       Public Property original_format As String
  148.       <XmlElement("original-content-size")>
  149.       Public Property original_content_size As String
  150.       <XmlElement("license")>
  151.       Public Property license As String
  152.       <XmlElement("uri")>
  153.       Public Property uri As String
  154.       <XmlElement("permalink-url")>
  155.       Public Property permalink_url As String
  156.       <XmlElement("artwork-url")>
  157.       Public Property artwork_url As String
  158.       <XmlElement("waveform-url")>
  159.       Public Property waveform_url As String
  160.       <XmlElement("stream-url")>
  161.       Public Property stream_url As String
  162.       <XmlElement("download-url")>
  163.       Public Property download_url As String
  164.       <XmlElement("playback-count")>
  165.       Public Property playback_count As String
  166.       <XmlElement("download_count")>
  167.       Public Property download_count As String
  168.       <XmlElement("favoritings-count")>
  169.       Public Property favoritings_count As String
  170.       <XmlElement("comment-count")>
  171.       Public Property comment_count As String
  172.       Public Property user As ShortUser
  173. End Class
  174.  
  175. Namespace Service
  176.       Public Class Soundcloud
  177.             Implements IDisposable
  178.             Private Http As Http = Nothing
  179.  
  180.             Public Const client_ID As String = 'Get one on http://developers.soundcloud.com
  181.             Const client_secret As String = 'Same story here.
  182.  
  183. #Region "Structures"
  184.             Public Structure Result
  185.                   Dim Success As Boolean
  186.                   Dim FailMessage As String
  187.                   Dim ProxyError As Boolean
  188.                   Dim Exception As Exception
  189.             End Structure
  190.  
  191.             Public Class Song
  192.                   Public URL As String
  193.                   Public Title As String
  194.                   Public Artist As String
  195.                   Public LengthInSeconds As Integer
  196.                   Public Size As Integer
  197.             End Class
  198. #End Region
  199.  
  200. #Region "Properties"
  201.             Private _Index As Integer = 0
  202.             Public ReadOnly Property Index As Integer
  203.                   Get
  204.                         Return _Index
  205.                   End Get
  206.             End Property
  207.  
  208.             Private _Proxy As String = String.Empty
  209.             Public Property Proxy As String
  210.                   Get
  211.                         Return _Proxy
  212.                   End Get
  213.                   Set(value As String)
  214.                         _Proxy = value
  215.                   End Set
  216.             End Property
  217.  
  218.             Private _Account As String = String.Empty
  219.             Public Property Account As String
  220.                   Get
  221.                         Return _Account
  222.                   End Get
  223.                   Set(value As String)
  224.                         _Account = value
  225.                   End Set
  226.             End Property
  227.  
  228.             Private _IsLoggedIn As Boolean = False
  229.             Public ReadOnly Property IsLoggedIn As Boolean
  230.                   Get
  231.                         Return _IsLoggedIn
  232.                   End Get
  233.             End Property
  234.  
  235.             Private _Token As String
  236.             Public ReadOnly Property AccessToken As String
  237.                   Get
  238.                         Return _Token
  239.                   End Get
  240.             End Property
  241. #End Region
  242.  
  243. #Region "Constructor"
  244.             Public Sub New(I As Integer)
  245.                   _Index = I
  246.             End Sub
  247. #End Region
  248.  
  249. #Region "Deconstructor"
  250.             Private disposedValue As Boolean
  251.             Protected Overridable Sub Dispose(disposing As Boolean)
  252.                   If Not Me.disposedValue Then
  253.                         If disposing Then
  254.                               If Not IsNothing(Http) Then Http.Dispose()
  255.                         End If
  256.                   End If
  257.                   Me.disposedValue = True
  258.             End Sub
  259.             Public Sub Dispose() Implements IDisposable.Dispose
  260.                   Dispose(True)
  261.                   GC.SuppressFinalize(Me)
  262.             End Sub
  263. #End Region
  264.  
  265. #Region "Methods"
  266.  
  267.             Private Sub NewSession()
  268.                   If Not IsNothing(Http) Then
  269.                         Http.Dispose()
  270.                         Http = Nothing
  271.                   End If
  272.                   Http = New Http
  273.                   With Http
  274.                         .AcceptCharset = String.Empty
  275.                         .KeepAlive = True
  276.                         .Useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1"
  277.  
  278.                         .AutoRedirect = True
  279.                         .SendCookies = True
  280.                         .StoreCookies = True
  281.  
  282.                         If Not String.IsNullOrEmpty(Proxy) Then
  283.                               If Not CountOccurance(Proxy, ":") > 1 Then
  284.                                     .Proxy = New HttpProxy(Proxy.Split(Convert.ToChar(":"))(0), Convert.ToInt32(Proxy.Split(Convert.ToChar(":"))(1)))
  285.                               Else
  286.                                     .Proxy = New HttpProxy(Proxy.Split(Convert.ToChar(":"))(0), Convert.ToInt32(Proxy.Split(Convert.ToChar(":"))(1)), Proxy.Split(Convert.ToChar(":"))(2), Proxy.Split(Convert.ToChar(":"))(3))
  287.                               End If
  288.                         End If
  289.                   End With
  290.             End Sub
  291. #End Region
  292.  
  293. #Region "XML deserialization"
  294.  
  295.             Private Function ParseTrack(ByVal XML As String) As Track
  296.                   Dim track As Track = Nothing
  297.                   Try
  298.                         Dim encoding As New System.Text.UTF8Encoding
  299.                         Dim usr As String = "<user>" & Split(Split(XML, "<user>")(1), "</user>")(0) & "</user>"
  300.                         Dim user As ShortUser
  301.                         Dim bytes() As Byte = encoding.GetBytes(usr)
  302.                         Using os As New MemoryStream
  303.                               os.Write(bytes, 0, bytes.Length)
  304.                               os.Position = 0
  305.                               user = CType(New XmlSerializer(GetType(ShortUser)).Deserialize(os), ShortUser)
  306.                         End Using
  307.                         XML.Replace(usr, "")
  308.                         bytes = encoding.GetBytes(XML)
  309.                         Using os As New MemoryStream
  310.                               os.Write(bytes, 0, bytes.Length)
  311.                               os.Position = 0
  312.                               track = CType(New XmlSerializer(GetType(Track)).Deserialize(os), Track)
  313.                               track.user = user
  314.                         End Using
  315.                   Catch ex As Exception
  316.                         Return Nothing
  317.                   End Try
  318.                   Return track
  319.             End Function
  320.  
  321.             Private Function ParseUser(ByVal Json As String) As User
  322.                   Dim encoding As New System.Text.UTF8Encoding
  323.                   Dim bytes() As Byte = encoding.GetBytes(Json)
  324.  
  325.                   Using os As New MemoryStream
  326.                         os.Write(bytes, 0, bytes.Length)
  327.                         os.Position = 0
  328.  
  329.                         Using reader As New StreamReader(os)
  330.                               Dim converter As New Converter(Of User)
  331.                               Return converter.ReturnJSON(reader)
  332.                         End Using
  333.                   End Using
  334.             End Function
  335.  
  336.             Private Class Converter(Of t)
  337.                   Public Function ReturnJSON(ByRef sreader As StreamReader) As t
  338.                         If GetType(t).Equals(GetType(String)) Then
  339.                               Dim result As Object = sreader.ReadToEnd.Replace("""", "")
  340.                               Return result
  341.                         Else
  342.                               Dim ds As New DataContractJsonSerializer(GetType(t))
  343.                               Dim result As t = DirectCast(ds.ReadObject(sreader.BaseStream), t)
  344.                               ds = Nothing
  345.                               Return result
  346.                         End If
  347.                   End Function
  348.             End Class
  349.  
  350. #End Region
  351.  
  352. #Region "API"
  353.  
  354.             Public Function AuthorizeURL(ByVal Input As String) As String
  355.                   Return Input & "?client_id=" & Soundcloud.client_ID & "&oauth_token=" & _Token
  356.             End Function
  357.  
  358.             Public Function Unlike_Track(ByVal T As Track) As Boolean
  359.                   Dim responseFromServer As String
  360.                   Try
  361.                         Dim request As WebRequest = WebRequest.Create("https://api.soundcloud.com/me/favorites/" & T.id & "?client_id=" & Soundcloud.client_ID & "&oauth_token=" & _Token)
  362.                         request.Method = "DELETE"
  363.                         Dim postData As String = ""
  364.                         Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
  365.                         request.ContentType = "application/x-www-form-urlencoded"
  366.                         request.ContentLength = byteArray.Length
  367.                         Dim dataStream As Stream = request.GetRequestStream()
  368.                         dataStream.Write(byteArray, 0, byteArray.Length)
  369.                         dataStream.Close()
  370.                         Dim response As WebResponse = request.GetResponse()
  371.                         dataStream = response.GetResponseStream()
  372.                         Dim reader As New StreamReader(dataStream)
  373.                         responseFromServer = reader.ReadToEnd()
  374.  
  375.                         reader.Close()
  376.                         dataStream.Close()
  377.                         response.Close()
  378.                   Catch ex As Exception
  379.                         If ex.ToString.Contains("404") Then
  380.                               Return True
  381.                         Else
  382.                               Return False
  383.                         End If
  384.                   End Try
  385.  
  386.                   If responseFromServer.Contains("200 - OK") Then
  387.                         Return True
  388.                   Else
  389.                         Return False
  390.                   End If
  391.             End Function
  392.  
  393.             Public Function Like_Track(ByVal T As Track) As Boolean
  394.                   Dim responseFromServer As String
  395.                   Try
  396.                         Dim request As WebRequest = WebRequest.Create("https://api.soundcloud.com/me/favorites/" & T.id & "?client_id=" & Soundcloud.client_ID & "&oauth_token=" & _Token)
  397.                         request.Method = "PUT"
  398.                         Dim postData As String = ""
  399.                         Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
  400.                         request.ContentType = "application/x-www-form-urlencoded"
  401.                         request.ContentLength = byteArray.Length
  402.                         Dim dataStream As Stream = request.GetRequestStream()
  403.                         dataStream.Write(byteArray, 0, byteArray.Length)
  404.                         dataStream.Close()
  405.                         Dim response As WebResponse = request.GetResponse()
  406.                         dataStream = response.GetResponseStream()
  407.                         Dim reader As New StreamReader(dataStream)
  408.                         responseFromServer = reader.ReadToEnd()
  409.                         reader.Close()
  410.                         dataStream.Close()
  411.                         response.Close()
  412.                   Catch ex As Exception
  413.                         Return False
  414.                   End Try
  415.  
  416.                   If responseFromServer.Contains("201 - Created") Then
  417.                         Return True
  418.                   Else
  419.                         Return False
  420.                   End If
  421.             End Function
  422.  
  423.             Public Function Search(ByVal Query As String) As List(Of Track)
  424.                   Dim result As New List(Of Track)
  425.                   Try
  426.                         Dim Response As String = New WebClient() With {.Proxy = Nothing}.DownloadString("https://api.soundcloud.com/tracks.xml" & "?limit=500&q=" & UrlEncode(Query) & "&client_id=" & client_ID)
  427.  
  428.                         For Each trck As String In Split(Response, "<track>")
  429.                               If Not trck.Contains("kind") Then Continue For
  430.                               trck = "<track>" & trck
  431.                               If trck.Contains("</tracks>") Then trck = Split(trck, "</tracks>")(0)
  432.                               result.Add(ParseTrack(trck))
  433.                         Next
  434.                         Return result
  435.                   Catch ex As Exception
  436.                         Return result
  437.                   End Try
  438.             End Function
  439.  
  440.             Public Function Get_Activity() As List(Of Track)
  441.                   Dim result As New List(Of Track)
  442.                   Try
  443.                         Dim Response As String = New WebClient() With {.Proxy = Nothing}.DownloadString("https://api.soundcloud.com/me/activities/tracks/affiliated" & "?limit=50&oauth_token=" & _Token)
  444.                         For Each trck As String In Split(Response, "<activity>")
  445.                               If Not trck.Contains("kind") Then Continue For
  446.                               If trck.Contains("<type>track-sharing</type>") Then Continue For
  447.  
  448.                               trck = Split(trck, "<origin>")(1)
  449.                               trck = Split(trck, "</origin>")(0)
  450.                               trck = "<track>" & trck & "</track>"
  451.  
  452.                               result.Add(ParseTrack(trck))
  453.                         Next
  454.                         Return result
  455.                   Catch ex As Exception
  456.                         Return result
  457.                   End Try
  458.  
  459.             End Function
  460.  
  461.             Public Function Get_Favorites() As List(Of Track)
  462.                   Dim result As New List(Of Track)
  463.                   Try
  464.                         Dim Response As String = New WebClient() With {.Proxy = Nothing}.DownloadString("https://api.soundcloud.com/me/favorites.xml" & "?limit=500&oauth_token=" & _Token)
  465.  
  466.                         For Each trck As String In Split(Response, "<track>")
  467.                               If Not trck.Contains("kind") Then Continue For
  468.                               trck = "<track>" & trck
  469.                               If trck.Contains("</tracks>") Then trck = Split(trck, "</tracks>")(0)
  470.  
  471.                               Dim resultTrack As Track = ParseTrack(trck)
  472.                               If Not resultTrack.id = 0 Then result.Add(resultTrack)
  473.                         Next
  474.                         Return result
  475.                   Catch ex As Exception
  476.                         Return result
  477.                   End Try
  478.             End Function
  479.  
  480.             Public Function Get_CurrentUserTracks() As List(Of Track)
  481.                   Dim result As New List(Of Track)
  482.                   Try
  483.                         Dim Response As String = New WebClient() With {.Proxy = Nothing}.DownloadString("https://api.soundcloud.com/me/tracks.xml" & "?limit=500&oauth_token=" & _Token)
  484.                         For Each trck As String In Split(Response, "<track>")
  485.                               If Not trck.Contains("kind") Then Continue For
  486.                               trck = "<track>" & trck
  487.                               If trck.Contains("</tracks>") Then trck = Split(trck, "</tracks>")(0)
  488.  
  489.                               Dim resultTrack As Track = ParseTrack(trck)
  490.                               If Not resultTrack.id = 0 Then result.Add(resultTrack)
  491.                         Next
  492.                         Return result
  493.                   Catch ex As Exception
  494.                         Return result
  495.                   End Try
  496.             End Function
  497.  
  498.             Public Function Get_Current_User() As User
  499.                   If Not _IsLoggedIn Then
  500.                         Throw New Exception("Not logged in")
  501.                         Exit Function
  502.                   End If
  503.  
  504.                   Return ParseUser(New WebClient() With {.Proxy = Nothing}.DownloadString("https://api.soundcloud.com/me.json" & "?oauth_token=" & _Token))
  505.             End Function
  506.  
  507.             Public Function Login() As Result
  508.                   Dim Result As New Result
  509.                   Try
  510.                         NewSession()
  511.                         With Http
  512.                               .TimeOut = 10000
  513.                               .RedirectBlacklist.Add("badbrowser.php")
  514.  
  515.  
  516.                               Dim PostData As New StringBuilder
  517.                               PostData.Append("client_id=" & client_ID)
  518.                               PostData.Append("&client_secret=" & client_secret)
  519.                               PostData.Append("&grant_type=password&username=" & UrlEncode(_Account.Split(":")(0)))
  520.                               PostData.Append("&password=" & UrlEncode(_Account.Split(":")(1)))
  521.  
  522.                               .Referer = "http://www.soundcloud.com"
  523.                               Dim hr As SoundcloudPlayer.Utility.Http.HttpResponse = .GetResponse(Verb._POST, "https://api.soundcloud.com/oauth2/token", PostData.ToString)
  524.                               If Not IsNothing(hr.RequestError) Then
  525.                                     Result.Exception = DirectCast(hr.RequestError.Exception, Exception)
  526.                                     Result.ProxyError = hr.RequestError.IsProxyError
  527.                                     Result.FailMessage = "Could not submit log in credentials; " & hr.RequestError.Message
  528.                                     Exit Try
  529.                               ElseIf Not hr.Html.Contains("access_token") Then
  530.                                     Result.Exception = Nothing
  531.                                     Result.ProxyError = False
  532.                                     Result.FailMessage = "Could not get access token. Wrong credentials?"
  533.                                     Exit Try
  534.                               End If
  535.  
  536.  
  537.                               Dim m As Match = New Regex(".*?" & """.*?""" & ".*?" & "("".*?"")", RegexOptions.IgnoreCase Or RegexOptions.Singleline).Match(hr.Html)
  538.                               If (m.Success) Then
  539.                                     _Token = m.Groups(1).Value.Replace(Chr(34), "")
  540.                               Else
  541.                                     Result.Exception = Nothing
  542.                                     Result.ProxyError = False
  543.                                     Result.FailMessage = "Could not get access token. Wrong credentials?"
  544.                                     Exit Try
  545.                               End If
  546.  
  547.                         End With
  548.                   Catch ex As Exception
  549.                         Result.Exception = ex
  550.                         Result.FailMessage = "Function exception; " & ex.Message
  551.                   Finally
  552.                         Result.Success = String.IsNullOrEmpty(Result.FailMessage)
  553.                         _IsLoggedIn = True
  554.                   End Try
  555.                   Return Result
  556.             End Function
  557. #End Region
  558.       End Class
  559. End Namespace
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement