Пример #1
0
        public async Task <bool> LoginAsync(string account, string password)
        {
            var  queries = new Dictionary <string, object>();
            bool isPhone = Regex.Match(account, "^[0-9]+$").Success;

            queries[isPhone ? "phone" : "email"] = account;
            queries["password"] = password;
            var(result, _)      = await _api.RequestAsync(isPhone?CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries);

            return(result);
        }
Пример #2
0
        /// <summary>
        /// SearchMusic
        /// </summary>
        /// <returns></returns>
        private async Task SearchMusic(string keyWords)
        {
            try
            {
                SongLst             = new ObservableCollection <Song>();
                queries             = new Dictionary <string, string>();
                queries["keywords"] = keyWords;
                (isOk, json)        = await api.RequestAsync(CloudMusicApiProviders.Search, queries);

                if (!isOk)
                {
                    throw new ApplicationException($"获取歌曲详情失败: {json}");
                }
                var Lst = json["result"];
                foreach (JObject song in Lst["songs"])
                {
                    var item = song.ToObject <Song>();
                    SongLst.Add(item);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #3
0
        public async void getSongs(String path)
        {
            string        listIdPath   = path + "listid.ini";
            StreamReader  listIdReader = new StreamReader(listIdPath);
            String        listId       = listIdReader.ReadLine();
            CloudMusicApi api          = new CloudMusicApi();
            bool          isOk;
            JObject       json = new JObject();
            Dictionary <String, String> param = new Dictionary <string, string> {
                { "id", listId }
            };

            (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.PlaylistDetail, param);

            var songList = json.SelectTokens("playlist.tracks[*]").ToDictionary(t => t["id"], t => t["name"]);
            //foreach (var item in songList)
            //{
            //    Console.WriteLine(item.Key + ":" + item.Value);
            //}
            string       filePath = path + "songs.json";
            StreamWriter writer   = File.CreateText(filePath);

            writer.Write(JObject.FromObject(songList));
            writer.Flush();
            writer.Close();
        }
Пример #4
0
        /// <summary>
        /// 用api搜音乐
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        public async Task <List <MusicInfo> > SearchMusicAsync2(string keyword, int offset = 0)
        {
            List <MusicInfo> songs = new List <MusicInfo>();

            using (CloudMusicApi api = new CloudMusicApi())
            {
                try
                {
                    bool    isOk;
                    JObject json;
                    (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.Search, new Dictionary <string, string> {
                        { "keywords", keyword.ToString() }, { "offset", offset.ToString() }
                    });

                    if (!isOk)
                    {
                        throw new ApplicationException($"获取专辑信息失败: {json}");
                    }

                    //var a = json.ToString();

                    var songsTemp = json["result"]["songs"].ToArray();

                    songs = new List <MusicInfo>();
                    foreach (var t in songsTemp)
                    {
                        //var b = t.ToString();

                        var artistsTemp    = t["artists"].Select(p => (string)p["name"]).ToArray();
                        var artistsIdsTemp = t["artists"].Select(p => ((int)p["id"]).ToString()).ToArray();
                        var duration       = TimeSpan.FromMilliseconds((int)t["duration"]);

                        songs.Add(
                            new MusicInfo
                        {
                            Id        = (int)t["id"],
                            Name      = t["name"].ToString(),
                            Album     = t["album"]?["name"].ToString(),
                            AlbumId   = (int)t["album"]["id"],
                            Artist    = string.Join("/", artistsTemp),
                            ArtistIds = artistsIdsTemp[0],    /*先做成只能搜索单个歌手*/
                            Duration  = $"{duration.TotalMinutes:00}:{duration.Seconds:00}",
                            File      = @"http://music.163.com/song/media/outer/url?id=" + t["id"].ToString() + ".mp3",
                            MvId      = (int)t["mvid"],
                            Type      = 1/*网页音乐*/
                        });
                    }
                    Console.WriteLine();
                }
                catch { }
            }

            return(songs);
        }
Пример #5
0
        /// <summary>
        /// 查找音乐
        /// </summary>
        /// <returns></returns>
        private static async Task SearchMusic()
        {
            queries             = new Dictionary <string, string>();
            queries["keywords"] = "最美情侣";
            (isOk, json)        = await api.RequestAsync(CloudMusicApiProviders.Search, queries);

            if (!isOk)
            {
                throw new ApplicationException($"获取歌曲详情失败: {json}");
            }
            var Lst = json["result"];

            foreach (JObject song in Lst["songs"])
            {
                var item = song.ToObject <Song>();
            }
        }
Пример #6
0
        public async void getUserListAsync(string path)
        {
            string uIdPath = path + "uid.ini";

            while (!File.Exists(uIdPath))
            {
            }
            StreamReader  listIdReader = new StreamReader(uIdPath);
            String        uid          = listIdReader.ReadLine();
            CloudMusicApi api          = new CloudMusicApi();
            bool          isOk;
            JObject       json = new JObject();
            Dictionary <String, String> param = new Dictionary <string, string> {
                { "uid", uid }
            };

            (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.UserPlaylist, param);

            var playList = json.SelectTokens("playlist[*]").ToDictionary(t => t["id"], t => t["name"]);
            //foreach (var item in playList)
            //{
            //    Console.WriteLine(item.Key + ":" + item.Value);
            //}
            string       filePath = path + "playlist.json";
            StreamWriter writer   = File.CreateText(filePath);

            writer.Write(JObject.FromObject(playList));
            writer.Flush();
            String defalutPlayId = playList.FirstOrDefault().Key.ToString();
            String listIdPath    = path + "listid.ini";

            writer = File.CreateText(listIdPath);
            writer.Write(defalutPlayId);
            writer.Flush();
            writer.Close();
        }
Пример #7
0
        private static async Task Main()
        {
            try {
                var api = new CloudMusicApi();

                /******************** 登录 ********************/

                while (true)
                {
                    var queries = new Dictionary <string, object>();
                    Console.WriteLine("请输入账号(邮箱或手机)");
                    string account = Console.ReadLine();
                    bool   isPhone = Regex.Match(account, "^[0-9]+$").Success;
                    queries[isPhone ? "phone" : "email"] = account;
                    Console.WriteLine("请输入密码");
                    queries["password"] = Console.ReadLine();
                    if (!CloudMusicApi.IsSuccess(await api.RequestAsync(isPhone ? CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries, false)))
                    {
                        Console.WriteLine("登录失败,账号或密码错误");
                    }
                    else
                    {
                        break;
                    }
                }
                Console.WriteLine("登录成功");
                Console.WriteLine();

                /******************** 登录 ********************/

                /******************** 获取账号信息 ********************/

                var json = await api.RequestAsync(CloudMusicApiProviders.LoginStatus);

                long uid = (long)json["profile"]["userId"];
                Console.WriteLine($"账号ID: {uid}");
                Console.WriteLine($"账号昵称: {json["profile"]["nickname"]}");
                Console.WriteLine();

                /******************** 获取账号信息 ********************/

                /******************** 获取我喜欢的音乐 ********************/

                json = await api.RequestAsync(CloudMusicApiProviders.UserPlaylist, new Dictionary <string, object> {
                    ["uid"] = uid
                });

                json = await api.RequestAsync(CloudMusicApiProviders.PlaylistDetail, new Dictionary <string, object> {
                    ["id"] = json["playlist"][0]["id"]
                });

                int[] trackIds = json["playlist"]["trackIds"].Select(t => (int)t["id"]).ToArray();
                json = await api.RequestAsync(CloudMusicApiProviders.SongDetail, new Dictionary <string, object> {
                    ["ids"] = trackIds
                });

                Console.WriteLine($"我喜欢的音乐({trackIds.Length} 首):");
                foreach (var song in json["songs"])
                {
                    Console.WriteLine($"{string.Join(",", song["ar"].Select(t => t["name"]))} - {song["name"]}");
                }
                Console.WriteLine();

                /******************** 获取我喜欢的音乐 ********************/

                /******************** 获取我的关注 ********************/

                /******************** 获取我的关注 ********************/

                json = await api.RequestAsync(CloudMusicApiProviders.UserFollows, new Dictionary <string, object> {
                    ["uid"] = uid
                });

                Console.WriteLine($"我的关注:");
                foreach (var user in json["follow"])
                {
                    Console.WriteLine(user["nickname"]);
                }
                Console.WriteLine();

                /******************** 获取我的动态 ********************/

                json = await api.RequestAsync(CloudMusicApiProviders.UserEvent, new Dictionary <string, object> {
                    ["uid"] = uid
                });

                Console.WriteLine($"我的动态:");
                foreach (var @event in json["events"])
                {
                    Console.WriteLine(JObject.Parse((string)@event["json"])["msg"]);
                }
                Console.WriteLine();

                /******************** 获取我的动态 ********************/

                /******************** 退出登录 ********************/

                json = await api.RequestAsync(CloudMusicApiProviders.Logout);

                Console.WriteLine("退出登录成功");
                Console.WriteLine();

                /******************** 退出登录 ********************/
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
            }
            Console.ReadKey(true);
        }
Пример #8
0
        private static async Task Main()
        {
            using (CloudMusicApi api = new CloudMusicApi()) {
                try {
                    bool    isOk;
                    JObject json;
                    int     uid;
                    int[]   trackIds;

                    /******************** 登录 ********************/

                    do
                    {
                        Dictionary <string, string> queries;
                        string account;
                        bool   isPhone;

                        queries = new Dictionary <string, string>();
                        Console.WriteLine("请输入账号(邮箱或手机)");
                        account = Console.ReadLine();
                        isPhone = Regex.Match(account, "^[0-9]+$").Success;
                        queries[isPhone ? "phone" : "email"] = account;
                        Console.WriteLine("请输入密码");
                        queries["password"] = Console.ReadLine();
                        (isOk, json)        = await api.RequestAsync(isPhone?CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries);

                        if (!isOk)
                        {
                            Console.WriteLine("登录失败,账号或密码错误");
                        }
                    } while (!isOk);
                    Console.WriteLine("登录成功");
                    Console.WriteLine();

                    /******************** 登录 ********************/

                    /******************** 获取账号信息 ********************/

                    (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.LoginStatus, CloudMusicApi.EmptyQueries);

                    if (!isOk)
                    {
                        throw new ApplicationException($"获取账号信息失败: {json}");
                    }
                    uid = (int)json["profile"]["userId"];
                    Console.WriteLine($"账号ID: {uid}");
                    Console.WriteLine($"账号昵称: {json["profile"]["nickname"]}");
                    Console.WriteLine();

                    /******************** 获取账号信息 ********************/

                    /******************** 获取我喜欢的音乐 ********************/

                    (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.UserPlaylist, new Dictionary <string, string> {
                        { "uid", uid.ToString() }
                    });

                    if (!isOk)
                    {
                        throw new ApplicationException($"获取用户歌单失败: {json}");
                    }
                    (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.PlaylistDetail, new Dictionary <string, string> {
                        { "id", json["playlist"][0]["id"].ToString() }
                    });

                    if (!isOk)
                    {
                        throw new ApplicationException($"获取歌单详情失败: {json}");
                    }
                    trackIds     = json["playlist"]["trackIds"].Select(t => (int)t["id"]).ToArray();
                    (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.SongDetail, new Dictionary <string, string> {
                        { "ids", string.Join(",", trackIds) }
                    });

                    if (!isOk)
                    {
                        throw new ApplicationException($"获取歌曲详情失败: {json}");
                    }
                    Console.WriteLine($"我喜欢的音乐 ({trackIds.Length} 首):");
                    foreach (JObject song in json["songs"])
                    {
                        Console.WriteLine($"{string.Join(",", song["ar"].Select(t => t["name"]))} - {song["name"]}");
                    }
                    Console.WriteLine();

                    /******************** 获取我喜欢的音乐 ********************/

                    /******************** 退出登录 ********************/

                    (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.Logout, CloudMusicApi.EmptyQueries);

                    if (!isOk)
                    {
                        throw new ApplicationException($"退出登录失败: {json}");
                    }
                    Console.WriteLine("退出登录成功");
                    Console.WriteLine();

                    /******************** 退出登录 ********************/
                }
                catch (Exception ex) {
                    Console.WriteLine(ex);
                }
            }
            Console.ReadKey(true);
        }
Пример #9
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="reqParamInfo"></param>
        /// <returns></returns>
        public async Task <Tuple <LoginInfo, string> > Invoke <TResult>(LoginInfo LoginInfo)
        {
            LoginInfo loginInfo = new LoginInfo();
            bool      isOk;
            string    msg;
            JObject   json;

            int[] trackIds;

            try
            {
                do
                {
                    Dictionary <string, string> queries;
                    string account = LoginInfo.UserAccount;
                    bool   isPhone;

                    queries = new Dictionary <string, string>();
                    isPhone = Regex.Match(account, "^[0-9]+$").Success;
                    queries[isPhone ? "phone" : "email"] = account;
                    queries["password"] = LoginInfo.UserPassword;
                    var rlt = api.RequestAsync(isPhone ? CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries);
                    isOk = rlt.Result.Item1;
                    json = rlt.Result.Item2;
                    if (!isOk)
                    {
                        msg = "登录失败,账号或密码错误";
                    }
                } while (!isOk);
                msg = "登录成功";

                /******************** 获取账号信息 ********************/

                var rlt1 = api.RequestAsync(CloudMusicApiProviders.LoginStatus, CloudMusicApi.EmptyQueries);
                isOk = rlt1.Result.Item1;
                json = rlt1.Result.Item2;
                if (!isOk)
                {
                    msg = "获取账号信息失败:" + json;
                }
                uid                = (int)json["profile"]["userId"];
                nickName           = json["profile"]["nickname"].ToString();
                loginInfo.UserId   = uid;
                loginInfo.Nickname = nickName;
                /******************** 获取账号信息 ********************/

                /******************** 获取我喜欢的音乐 ********************/

                (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.UserPlaylist, new Dictionary <string, string> {
                    { "uid", uid.ToString() }
                });

                if (!isOk)
                {
                    throw new ApplicationException($"获取用户歌单失败: {json}");
                }
                (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.PlaylistDetail, new Dictionary <string, string> {
                    { "id", json["playlist"][0]["id"].ToString() }
                });

                if (!isOk)
                {
                    throw new ApplicationException($"获取歌单详情失败: {json}");
                }
                trackIds     = json["playlist"]["trackIds"].Select(t => (int)t["id"]).ToArray();
                (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.SongDetail, new Dictionary <string, string> {
                    { "ids", string.Join(",", trackIds) }
                });

                if (!isOk)
                {
                    throw new ApplicationException($"获取歌曲详情失败: {json}");
                }
                Console.WriteLine($"我喜欢的音乐 ({trackIds.Length} 首):");
                foreach (JObject song in json["songs"])
                {
                    Console.WriteLine($"{string.Join(",", song["ar"].Select(t => t["name"]))} - {song["name"]}");
                }
                Console.WriteLine();
                /******************** 获取我喜欢的音乐 ********************/

                return(Tuple.Create <LoginInfo, string>(LoginInfo, msg));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return(null);
        }
Пример #10
0
        private async Task FetchSongList()
        {
            Dictionary <string, string> queries;
            string  account;
            bool    isPhone;
            bool    isOk;
            JObject json;

            queries = new Dictionary <string, string>();
            account = txtUserName.Text;
            isPhone = Regex.Match(account, "^[0-9]+$").Success;
            queries[isPhone ? "phone" : "email"] = account;
            queries[Settings.PASSWORD]           = txtPassword.Text;

            showLog("登录中...");
            (isOk, json) = await api.RequestAsync(isPhone?CloudMusicApiProviders.LoginCellphone : CloudMusicApiProviders.Login, queries);

            if (!isOk)
            {
                showLog("登录失败,账号或密码错误");
                return;
            }

            showLog("获取用户信息...");
            (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.LoginStatus, CloudMusicApi.EmptyQueries);

            if (!isOk)
            {
                showLog($"获取账号信息失败: {json}");
                return;
            }
            int uid = (int)json["profile"]["userId"];


            showLog("获取用户歌单...");
            (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.UserPlaylist, new Dictionary <string, string> {
                { "uid", uid.ToString() }
            });

            if (!isOk)
            {
                showLog("获取用户歌单失败");
                return;
            }

            (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.PlaylistDetail, new Dictionary <string, string> {
                { "id", json["playlist"][0]["id"].ToString() }
            });

            if (!isOk)
            {
                showLog("获取歌单详情失败");
                return;
            }

            showLog("获取用歌单歌曲...");
            int[] trackIds = json["playlist"]["trackIds"].Select(t => (int)t["id"]).ToArray();
            (isOk, json) = await api.RequestAsync(CloudMusicApiProviders.SongDetail, new Dictionary <string, string> {
                { "ids", string.Join(",", trackIds) }
            });

            if (!isOk)
            {
                showLog("获取歌曲详情失败");
            }

            // 搜索候选歌曲
            showLog("获取无版权歌曲...");
            List <Song> noCopyrightsSongs = FetchNoCopyrightSongs(json);

            showLog("搜索候选歌曲...");
            List <MergedSong> mergedSongs = FetchCandidateSongs(noCopyrightsSongs);

            ShowSongList(mergedSongs);
        }