JLChen
2020-06-04 6d55af8792cf8fbef0055e677b900fc352dba9a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using Shared.Net;
using Shared.SimpleControl.R;
using SmartHome.UI.SimpleControl.Phone.Music;
 
namespace Shared.SimpleControl.Phone.Music
{
 
[System.Serializable]
    public class TidalConfig
    {
        public readonly static string FileName = "TidalConfig";
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName;
        /// <summary>
        /// 密码
        /// </summary>
        public string Passwrod;
    }
 
[System.Serializable]
    public class Tidal
    {
        public  static string fileName = "Tidal";
        #region
        public static readonly System.Collections.Generic.List<MusicInfo> TempMusicInfoList = new System.Collections.Generic.List<MusicInfo> ();
        #endregion
        //保存当前信息
        public void Save ()
        {
            Shared.IO.FileUtils.WriteFileByBytes (fileName, System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (CurrentTidal)));
        }
      
        public static string GetResult (string url)
        {
            var datetTime = DateTime.Now;
            var webclient = new MyWebClient ();
            webclient.Proxy = null;
            webclient.Headers.Add ("Authorization", "Basic " + Authorization);
            var resut = webclient.DownloadString (url);
            System.Console.WriteLine (url + "获取数据时长:" + (DateTime.Now - datetTime).TotalMilliseconds);
            return resut;
            //var datetTime = DateTime.Now;
            //var result = httpRequest.HTTPRequest.HTTPRequestA (url, "Authorization", "Basic " + Authorization, 10);
            //System.Console.WriteLine (url + "获取数据时长:" + (DateTime.Now - datetTime).TotalMilliseconds);
            //if (result == null) {
            //    return null;
            //} else {
            //    return System.Text.Encoding.UTF8.GetString (result.ToArray ());
            //}
        }
 
        public static void InitTokenTime ()
        {
            Shared.IO.FileUtils.DeleteFile (fileName);
            CurrentTidal = null;
            //尝试获取多次,有可能有的时候网络有问题获取不成功
            int count = 2;
            while (0 < count) {
                count--;
                if (initTokenTime ()) {
                    //如果获取到时间,就马上退出
                    break;
                }
            }
        }
 
        /// <summary>
        /// 获取真实播放地址
        /// </summary>
        /// <param name="musicInfo">Music info.</param>
        public static void ReadRealUrl (MusicInfo musicInfo)
        {
            try {
                if (musicInfo.URL.StartsWith ("https://meta.airable.io")) {
                    var result = GetResult (musicInfo.URL);
                    if (!string.IsNullOrEmpty (result)) {
                        var airable = Newtonsoft.Json.JsonConvert.DeserializeObject<Airable> (result);
                        if (airable != null && airable.url != null)
                            musicInfo.URL = airable.url;
                    }
                }
            } catch { }
        }
 
       static Tidal ()
        {
            new Tidal { IsLogin = false, id = new string [0], time = 0, token = "" };
            if (Shared.IO.FileUtils.Exists (fileName)) {
                CurrentTidal = Newtonsoft.Json.JsonConvert.DeserializeObject<Tidal> (System.Text.Encoding.UTF8.GetString (Shared.IO.FileUtils.ReadFile (fileName)));
            }
        }
        //是否已经登录了
        public bool IsLogin;
        /// <summary>
        /// 当前Token
        /// </summary>
        public string token;
        /// <summary>
        /// 服务器记录时间
        /// </summary>
        public long time;
        public string [] id;
        // "{\"id\":[\"airable\",\"accesstoken\",\"authentication\"],\"token\":\"6ALMArG5kLS6kciUvYuiBhaeXO1JQMGBk8qXEslY9tvSghVIpdwggVRZ1QDsLR3i\",\"time\":1512032632}"
        public static Tidal CurrentTidal {
            internal set;
            get;
        }
 
        //ECJUFDFLAIA
        static string secret = "PJFKwfIWH7LIoaYGqlEOe5x2QzLCzcVN";
        static string @name = "audiocast";
        static string version = "1.0";
        static string locale = "en-US";
 
        public static string Authorization {
            get {
                if (CurrentTidal == null) {
                    return null;
                }
                var ts = (DateTime.UtcNow - new DateTime (1970, 1, 1, 0, 0, 0, 0));
                var time = Convert.ToInt64 (ts.TotalSeconds).ToString ();
                var result = Encoding.ASCII.GetBytes (CurrentTidal.token + secret + time);
                var output = new MD5CryptoServiceProvider ().ComputeHash (result);
                var password = BitConverter.ToString (output).Replace ("-", "").ToLower ();
                return Convert.ToBase64String (System.Text.Encoding.ASCII.GetBytes (CurrentTidal.token + ":" + password));
            }
        }
 
        static bool initTokenTime ()
        {
            try {
                string salt = "345548ab";
                var deviceUniqueId = DateTime.Now.Ticks.ToString();
                string ss = string.Format ("{0}{1}{2}{3}",deviceUniqueId , locale, salt, secret);
 
                var result = Encoding.ASCII.GetBytes (ss);
                var output = new MD5CryptoServiceProvider ().ComputeHash (result);
                var password = BitConverter.ToString (output).Replace ("-", "").ToLower ();
 
                string url = string.Format ("https://meta.airable.io/authentication?device={0}&name={1}&version={2}&locale={3}&salt={4}&signature={5}",
                    deviceUniqueId,
                    name,
                    version,
                    locale,
                    salt,
                    password
                    );
                var dateTime = DateTime.Now;
 
                CurrentTidal = Newtonsoft.Json.JsonConvert.DeserializeObject<Tidal> (GetResult (url));
                System.Console.WriteLine ("获取Token时间时长:" + (DateTime.Now - dateTime).TotalMilliseconds);
                //如果获取到时候及Token,马上保存
                CurrentTidal.Save ();
 
                return true;
            } catch {
                return false;
            }
        }
 
 
        public static bool Login ()
        {
            InitTokenTime ();
 
            try {
                //可能网络或者其它原因,时间获取不到,下面代码不能执行
                if (CurrentTidal == null) {
                    return false;
                }
 
                var tidal = Newtonsoft.Json.JsonConvert.DeserializeObject<TidalConfig> (Encoding.UTF8.GetString (Shared.IO.FileUtils.ReadFile (TidalConfig.FileName)));
                if (tidal != null) {
                    var result = GetResult ("https://meta.airable.io/tidal/login?username=" + tidal.UserName + "&password=" + tidal.Passwrod);
                    var musics = Newtonsoft.Json.JsonConvert.DeserializeObject<Airable> (result);
                    if (musics.title != "TIDAL") {
                        return false;
                    }
                    CurrentTidal.IsLogin = true;
                    CurrentTidal.Save ();
                    return true;
                }
 
            } catch { }
 
            return false;
        }
       
        public static void ReadPlayList (string path, Action gotoLoginActon, Action<string> gotoPageAction)
        {
            MainPage.Loading.Start (Language.StringByID (MyInternationalizationString.load));
            System.Threading.Tasks.Task.Run (() => {
                try {
                    var list = TempMusicInfoList.FindAll ((obj) => obj.Tag.ToString() == path);
                    if (list.Count != 0) {
                        return;
                    }
                    var result = GetResult ("https://meta.airable.io/"+path);
                    if (result == null) {
                        result = GetResult ("https://meta.airable.io/"+path);
                        if (result == null) {
                            return;
                        }
                    }
                    var tracks = Newtonsoft.Json.JsonConvert.DeserializeObject<Airable> (result);
                    //token过期,需要重新登录.
 
                    if (tracks.id != null) {
                        if (tracks.id [2].ToString () == "authorization") {
                            if (!Login ()) {
                                return;
                            }
                        }
                    }
 
                    foreach (var v in tracks.content.entries) {
                        var tidalMusicInfo = new MusicInfo () { Tag = path };
 
                        if (v.title != null) {
                            tidalMusicInfo.Title = v.title.Replace ("&", "");
                        }
 
                        if (v.url != null) {
                            tidalMusicInfo.ID = v.url.Replace ("https://meta.airable.io/", "");
                        }
                        if (v.id != null) {
                            tidalMusicInfo.IsDirectory = v.id [1].ToString () != "track";
                        }
 
                        if (v.album != null) {
                            tidalMusicInfo.Album = v.album.title.Replace ("&", "");
                        }
 
                        if (v.artist != null) {
                            tidalMusicInfo.Artist = v.artist.title.Replace ("&", "");
                        }
                        if (v.streams != null && 0 < v.streams.Length) {
                            tidalMusicInfo.URL = v.streams [0].url;
                        }
 
                        if (v.images != null) {
                            #region 初始化网络图片路径
                            string pathIm = "";
                            if (Shared.Application.IsPad) {
                                pathIm = "";
                            } else {
                                pathIm = "Phone/" + "MusicImage/";
                            }
                            pathIm = System.IO.Path.Combine (Shared.IO.FileUtils.RootPath, pathIm + v.images [0].url.Replace ('/', '_').Replace ('\\', '_').Replace (':', '_').Replace ('*', '_').Replace ('?', '_').Replace ('"', '_').Replace ('<', '_').Replace ('>', '_').Replace ('|', '_'));
                            tidalMusicInfo.Image = pathIm;
                            #endregion
                            Shared.IO.FileUtils.DownLoadImage (tidalMusicInfo.Image, v.images [0].url);
                        }
                        if (!tidalMusicInfo.IsDirectory && tidalMusicInfo.URL == null) {
                        } else {
                            TempMusicInfoList.Add (tidalMusicInfo);
                        }
                    }
 
                } catch { } finally {
                    if (gotoPageAction != null) {
                        gotoPageAction (path);
                    }
                }
            });
        }
 
    }
}