public async Task <SearchResult> Search(string key, EnumSearchType t) { key = key.Trim(); var res = new SearchResult { Items = new List <IMusic>(), Keyword = key, SearchType = t, Page = 1, }; var url = string.Format(search_url, Uri.EscapeDataString(key)); var response = await NetAccess.DownloadStringAsync(url); var json = response.ToDynamicObject(); if (json.song.Count > 0) { foreach (var obj in json.song) { var s = new Song { Id = "b" + MusicHelper.Get(obj, "songid"), ArtistName = MusicHelper.Get(obj, "artistname"), AlbumName = "", Name = MusicHelper.Get(obj, "songname"), WriteId3 = false, }; res.Items.Add(s); s.UrlMp3 = await getDownloadUrl(s.Id.Substring(1)); } } return(res); }
public override async Task Download() { try { var item = Info.Entity as SongViewModel; if (item == null) { throw new Exception("song item is null"); } if (string.IsNullOrEmpty(item.UrlLrc)) { item.UrlLrc = await NetAccess.GetUrlLrc(item.Id); } Info.Url = item.UrlLrc; if (string.IsNullOrEmpty(Info.Url)) { State = EnumDownloadState.Error; NotifyState(); return; } } catch (Exception e) { NotifyError(e); return; } await base.Download(); }
public static void EndColliding(/*ulong[] ___m_collidingSegments1*/) { StackTrace stackTrace = new StackTrace(); ToolController targetInstance = Singleton <ToolManager> .instance.m_properties; if (stackTrace.GetFrame(1).GetMethod().Name == "SimulationStep") { ulong[] ___m_collidingSegments1 = typeof(ToolController).GetField("m_collidingSegments1", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(targetInstance) as ulong[]; //UnityEngine.Debug.Log("EndColliding caller: " + stackTrace.GetFrame(2).GetMethod().GetUnderlyingType() + " " + stackTrace.GetFrame(2).GetMethod().Name + " " + ", count: " + CollidingSegments.Count); CollidingSegments.Clear(); foreach (int segment in NetAccess.SegmentsFromMask(___m_collidingSegments1)) { CollidingSegments.Add((ushort)segment); } CollidingSegmentsCache2 = CollidingSegments.ToArray(); } Redirector <ToolControllerDetour> .Revert(); targetInstance.EndColliding(); Redirector <ToolControllerDetour> .Deploy(); //UnityEngine.Debug.Log("EndColliding: " + CollidingSegmentsCache2.Length); }
/* This draws the UI circles on the map */ protected override void RenderOverlayExtended(RenderManager.CameraInfo cameraInfo) { try { if (m_hoverNode != 0) { NetNode hoveredNode = NetAccess.Node(m_hoverNode); // kinda stole this color from Move It! // thanks to SamsamTS because they're a UI god // ..and then Strad stole it from all of you!! RenderManager.instance.OverlayEffect.DrawCircle(cameraInfo, Color.black, hoveredNode.m_position, 15f, hoveredNode.m_position.y - 1f, hoveredNode.m_position.y + 1f, true, true); float?radius = UIWindow2.instance.P_RoundAboutPanel.RadiusField.Value; if (radius != null) { float roadWidth = UIWindow2.instance.dropDown.Value.m_halfWidth; // There is a slight chance that this will throw an exception float innerCirleRadius = radius - roadWidth > 0 ? 2 * ((float)radius - roadWidth) : 2 * (float)radius; RenderManager.instance.OverlayEffect.DrawCircle(cameraInfo, Color.red, hoveredNode.m_position, innerCirleRadius, hoveredNode.m_position.y - 2f, hoveredNode.m_position.y + 2f, true, true); RenderManager.instance.OverlayEffect.DrawCircle(cameraInfo, Color.red, hoveredNode.m_position, 2 * ((float)radius + roadWidth /*DISTANCE_PADDING - 5*/), hoveredNode.m_position.y - 1f, hoveredNode.m_position.y + 1f, true, true); } //RenderDirectionVectors(cameraInfo); RenderHoveringLabel("Click to build\nPress +/- to adjust radius"); } else { RenderMousePositionCircle(cameraInfo); RenderHoveringLabel("Hover mouse over intersection"); } } catch (Exception e) { Debug.LogError(e); } }
/* Debug */ /*public List<Bezier2> debugDraw = new List<Bezier2>(); * public List<Vector3> debugDrawPositions = new List<Vector3>(); * bool yes = true; // :)*/ public void BuildEllipse() { if (ellipse == null) { UIWindow2.instance.ThrowErrorMsg("Invalid radii!"); } Ellipse toBeBuiltEllipse = ellipse; Ellipse ellipseWithPadding = ellipse; /* When the old snapping algorithm is enabled, we create secondary (bigger) ellipse, so the newly connected roads obtained by the * graph traveller are not too short. They will be at least as long as the padding. */ if (RoundAboutBuilder.UseOldSnappingAlgorithm.value) { ellipseWithPadding = new Ellipse(NetAccess.Node(centralNode).m_position, NetAccess.Node(axisNode).m_position - NetAccess.Node(centralNode).m_position, prevRadius1 + DISTANCE_PADDING, prevRadius2 + DISTANCE_PADDING); } UIWindow2.instance.LostFocus(); UIWindow2.instance.GoBack(); try { GraphTraveller2 traveller = new GraphTraveller2(centralNode, ellipseWithPadding); EdgeIntersections2 intersections = new EdgeIntersections2(traveller, centralNode, toBeBuiltEllipse); FinalConnector finalConnector = new FinalConnector(NetAccess.Node(centralNode).Info, intersections, toBeBuiltEllipse, ControlVertices); // Easter egg RoundAboutBuilder.EasterEggToggle(); } catch (Exception e) { Debug.LogError(e); UIWindow2.instance.ThrowErrorMsg(e.ToString(), true); } }
/*public static void Apply(HarmonyInstance harmony) * { * var fix = typeof(BuildingDecorationDetour).GetMethod("LoadPaths"); * harmony.Patch(OriginalMethod, new HarmonyMethod(fix), null, null); * * }*/ /*public static void Revert(HarmonyInstance harmony) * { * harmony.Unpatch(OriginalMethod, HarmonyPatchType.Prefix); * }*/ /*private static MethodInfo OriginalMethod => typeof(BuildingDecoration).GetMethod("LoadPaths");*/ #endregion DETOUR private static HashSet <ConnectionPoint> ReleaseCollidingSegments() { // We obtain a list of nodes adjacent to the deleted segment to know where to reconnect HashSet <ConnectionPoint> borderNodes = new HashSet <ConnectionPoint>(); if (ToolControllerDetour.CollidingSegmentsCache2 == null) { return(null); } foreach (ushort segment in ToolControllerDetour.CollidingSegmentsCache2) { //Debug.Log("Releasing segment " + segment); NetSegment netSegment = NetAccess.GetSegment(segment); // We keep untouchable segments if ((netSegment.m_flags & NetSegment.Flags.Untouchable) != NetSegment.Flags.None) { continue; } bool inverted = ((netSegment.m_flags & NetSegment.Flags.Invert) != NetSegment.Flags.None); borderNodes.Add(new ConnectionPoint(netSegment.m_startNode, netSegment.m_startDirection, netSegment.Info, inverted)); borderNodes.Add(new ConnectionPoint(netSegment.m_endNode, netSegment.m_endDirection, netSegment.Info, !inverted)); NetAccess.ReleaseSegment(segment, true); } borderNodes.RemoveWhere(n => !NetAccess.ExistsNode(n.Node)); ToolControllerDetour.CollidingSegmentsCache2 = null; //Debug.Log("Border nodes (1): " + borderNodes.Count); return(borderNodes); }
/* If node distance is too short, we travel one segment up from the border node and set the new node as the one to connect to */ private static void RepairShortSegment(ref Vector3 direction, ref ushort node) { //Debug.Log("Repairing short segment..."); NetNode netNode = NetAccess.GetNode(node); // If there is more than one segment we cannot safely delete it (we don't even know from which segment we should pick) if (netNode.CountSegments() != 1) { return; } ushort segmentId = NetAccess.GetFirstSegment(netNode); NetSegment netSegment = NetAccess.GetSegment(segmentId); if (node == netSegment.m_startNode) { direction = netSegment.m_endDirection; node = netSegment.m_endNode; } else { direction = netSegment.m_startDirection; node = netSegment.m_startNode; } NetAccess.ReleaseSegment(segmentId, true); }
static async Task <SearchResult> SearchAll(string key) { var items = new List <IMusic>(); var sr = new SearchResult { Items = items, Keyword = key, Page = -1, SearchType = EnumSearchType.all, }; dynamic obj = await NetAccess.Json(XiamiUrl.url_search_all, "key", key); if (obj == null) { return(sr); } foreach (var type in new string[] { "song", "album", "artist", "collect" }) { dynamic data = obj[type + "s"]; if (data == null) { continue; } foreach (dynamic x in data) { items.Add(MusicFactory.CreateFromJson(x, (EnumMusicType)Enum.Parse(typeof(EnumMusicType), type))); } } return(sr); }
//string m_radiusField.text = RADIUS_DEF.ToString(); /* Main method , called when user cliks on a node to create a roundabout */ public void CreateRoundabout(ushort nodeID) { //Debug.Log(string.Format("Clicked on node ID {0}!", nodeID)); float?radiusQ = UIWindow2.instance.P_RoundAboutPanel.RadiusField.Value; if (radiusQ == null) { UIWindow2.instance.ThrowErrorMsg("Radius out of bounds!"); return; } float radius = (float)radiusQ; if (!UIWindow2.instance.keepOpen) { UIWindow2.instance.LostFocus(); } /* These lines of code do all the work. See documentation in respective classes. */ /* When the old snapping algorithm is enabled, we create secondary (bigger) ellipse, so the newly connected roads obtained by the * graph traveller are not too short. They will be at least as long as the padding. */ Ellipse ellipse = new Ellipse(NetAccess.Node(nodeID).m_position, new Vector3(0f, 0f, 0f), radius, radius); Ellipse ellipseWithPadding = ellipse; if (RoundAboutBuilder.UseOldSnappingAlgorithm.value) { ellipseWithPadding = new Ellipse(NetAccess.Node(nodeID).m_position, new Vector3(0f, 0f, 0f), radius + DISTANCE_PADDING, radius + DISTANCE_PADDING); } try { GraphTraveller2 traveller; EdgeIntersections2 intersections = null; if (!RoundAboutBuilder.DoNotRemoveAnyRoads) { traveller = new GraphTraveller2(nodeID, ellipse); intersections = new EdgeIntersections2(traveller, nodeID, ellipse); } FinalConnector finalConnector = new FinalConnector(NetAccess.Node(nodeID).Info, intersections, ellipse, true); // Easter egg RoundAboutBuilder.EasterEggToggle(); // Debug, don't forget to remove /*foreach(VectorNodeStruct intersection in intersections.Intersections) * { * Debug.Log($"May have/Has restrictions: {TrafficManager.Manager.Impl.JunctionRestrictionsManager.Instance.MayHaveJunctionRestrictions(intersection.nodeId)}, {TrafficManager.Manager.Impl.JunctionRestrictionsManager.Instance.HasJunctionRestrictions(intersection.nodeId)}"); * }*/ } catch (Exception e) { Debug.LogError(e); UIWindow2.instance.ThrowErrorMsg(e.ToString(), true); } }
void OnMp3PlayerSongChanged(object sender, SongChangedEventArgs e) { source.Clear(); SongViewModel svm = SongViewModel.GetId(e.Id); if (svm == null) { return; } var lrcPath = Path.Combine(Global.AppSettings["DownloadFolder"], svm.FileNameBase + ".lrc"); if (!File.Exists(lrcPath)) { lrcPath = Path.Combine(Global.BasePath, "cache", e.Id + ".lrc"); } if (!File.Exists(lrcPath)) { Task.Run(async() => { var url = svm.Song.UrlLrc; if (string.IsNullOrEmpty(url)) { var json = await NetAccess.Json(XiamiUrl.url_song, "id", svm.Id); if (json.song != null) { json = json.song; } url = MusicHelper.Get(json, "lyric", "song_lrc"); if (string.IsNullOrEmpty(url)) { return; } } string lrcText = await Http.Get(url, null); File.WriteAllText(lrcPath, lrcText); var f = LyricViewModel.LoadLrcFile(lrcPath); UIHelper.RunOnUI(() => { foreach (var item in f) { source.Add(item); } timelist = source.Select(x => x.Time.TotalMilliseconds).ToArray(); }); }); return; } var s = LyricViewModel.LoadLrcFile(lrcPath); foreach (var item in s) { source.Add(item); } timelist = source.Select(x => x.Time.TotalMilliseconds).ToArray(); }
public async Task <SearchResult> Search(string key, EnumSearchType t) { var res = new SearchResult { Items = new List <IMusic>(), Keyword = key, SearchType = t, Page = 1, }; if (string.IsNullOrEmpty(key) || !re_url.IsMatch(key)) { return(res); } var html = await NetAccess.DownloadStringAsync(key); var ms = re_json.Matches(html); if (ms.Count == 0) { return(null); } var artistName = ""; var x = re_artist.Match(html); if (x.Success) { artistName = x.Groups[1].Value; } foreach (Match m in ms) { var listId = m.Groups[1].Value; var json = m.Groups[2].Value.ToDynamicObject(); foreach (var obj in json) { var s = new Song { Id = "d" + MusicHelper.Get(obj, "id"), AlbumName = artistName, ArtistName = artistName, Name = MusicHelper.Get(obj, "name"), UrlMp3 = (MusicHelper.Get(obj, "rawUrl") as string).Replace("\\/", "/"), Logo = MusicHelper.Get(obj, "cover"), WriteId3 = false, }; s.UrlLrc = DoubanUrl.LyricUrl(listId, s.Id.Substring(1)); res.Items.Add(s); } } return(res); }
/* We keep only nodes with exactly one segment connected (dead ends). */ private static HashSet <ushort> FilterCreatedNodes(FastList <ushort> createdNodes) { HashSet <ushort> filteredNodes = new HashSet <ushort>(); foreach (ushort node in createdNodes) { if (NetAccess.GetNode(node).CountSegments() == 1) { filteredNodes.Add(node); } } return(filteredNodes); }
async Task <string> getDownloadUrl(string id) { var url = string.Format("http://music.baidu.com/song/{0}/download", id); var html = await NetAccess.DownloadStringAsync(url); var m = re_download.Match(html); if (!m.Success) { return(null); } return(m.Groups[1].Value); }
//public override bool CanDownload //{ // get // { // var song = Info.Entity as SongViewModel; // return song != null && song.HasXml; // } //} public override async Task Download() { var item = Info.Entity as SongViewModel; if (item == null) { return; } if (string.IsNullOrEmpty(item.UrlLrc)) { var url = await NetAccess.DownloadStringAsync(XiamiUrl.UrlSongInfo(item.SongId)); } Info.Url = (Info.Entity as SongViewModel).UrlLrc; await base.Download(); }
void OnMp3PlayerSongChanged(object sender, SongChangedEventArgs e) { if (SongViewModel.NowPlaying != null) { SongViewModel.NowPlaying.IsNowPlaying = false; } SongViewModel.NowPlaying = SongViewModel.GetId(e.Id); if (SongViewModel.NowPlaying != null) { Task.Run(() => { if (!Mp3Player.IsPlaying) { return; } var id = SongViewModel.NowPlaying.Id; System.Threading.Thread.Sleep(10000); if (SongViewModel.NowPlaying.Id != id) { return; } NetAccess.Json(XiamiUrl.url_playlog, "uid", Global.AppSettings["xiami_uid"], "id", id); // XiamiClient.GetDefault().Call_xiami_api("Playlog.add", // "id=" + SongViewModel.NowPlaying.Id, // "time=" + XiamiClient.DateTimeToUnixTimestamp(DateTime.Now).ToString(), // "type=20" //); }); SongViewModel.NowPlaying.IsNowPlaying = true; var now = SongViewModel.NowPlaying; info_now.Visibility = Visibility.Visible; part_nowPlaying.DataContext = now; Title = string.Format("{0} - {1} ", now.Name, now.ArtistName); counter = 0; if (trayIcon != null && Global.AppSettings["ShowNowPlaying"] != "0" && Mp3Player.IsPlaying) { balloonTip = new MyBalloonTip(); balloonTip.ViewModel = now; trayIcon.ShowCustomBalloon(balloonTip, PopupAnimation.Fade, 3000); } } ActionBarService.Refresh(); refreshPlause(); currentList.PerformAction("选中正在播放"); }
private async Task InitNetAccess() { Pass = new MyPassword(); while (!Pass.GetLoginInfoFromRegistry()) { var result = await Task.Run(() => MessageBox.Show("ユーザー情報を入力してください。", "Password not found", MessageBoxButton.OKCancel)); if (result == MessageBoxResult.Cancel) { // Quit the program Application.Current.Shutdown(); return; } await RunProcessNoWindow("powershell.exe", @"-ExecutionPolicy Bypass -File .\SavePassword.ps1"); } Net = new NetAccess(); while (!IsLoggedIn) { Net.SupplyLoginInfo(Pass.CompanyCode, Pass.UserId, Pass.Password); if ((IsLoggedIn = await Net.Login()) == true) { break; } var result = await Task.Run(() => MessageBox.Show("ユーザー情報が間違っているようです。入れ直しますか?", "Unable to login", MessageBoxButton.OKCancel)); if (result == MessageBoxResult.Cancel) { // Quit the program Application.Current.Shutdown(); return; } await RunProcessNoWindow("powershell.exe", @"-ExecutionPolicy Bypass -File .\ClearPassword.ps1"); await RunProcessNoWindow("powershell.exe", @"-ExecutionPolicy Bypass -File .\SavePassword.ps1"); Pass.GetLoginInfoFromRegistry(); } }
// Solved by ReleaseQuestionableSegments /*private static void CheckSplitSegmentAngle(ref NetTool.ControlPoint point, FastList<ushort> createdSegments, HashSet<ConnectionPoint> borderNodes) * { * if(point.m_segment != 0) * { * if (createdSegments.Contains(point.m_segment)) * return; * * if (point.m_node != 0) * return; * * Debug.Log("CheckSplitSegmentAngle: Snapping detected"); * NetSegment netSegment = NetAccess.GetSegment(point.m_segment); * netSegment.GetClosestPositionAndDirection(point.m_position, out Vector3 pos, out Vector3 dir); * float angle = Vector3.Angle(point.m_direction, dir); * if(angle < 5 || 180 - angle < 5) * { * Debug.Log("CheckSplitSegmentAngle: Releasing (" + angle + " deg)"); * bool inverted = ((netSegment.m_flags & NetSegment.Flags.Invert) != NetSegment.Flags.None); * ConnectionPoint p1 = new ConnectionPoint(netSegment.m_startNode, netSegment.m_startDirection, netSegment.Info, inverted); * ConnectionPoint p2 = new ConnectionPoint(netSegment.m_endNode, netSegment.m_endDirection, netSegment.Info, !inverted); * NetAccess.ReleaseSegment(point.m_segment, true); * if(NetAccess.ExistsNode(p1.Node) && NetAccess.ExistsNode(p2.Node)) * { * borderNodes.Add(p1); * borderNodes.Add(p2); * } * } * } * }*/ /* Sometimes the intersection end snaps to an existing road. But it can happen that the intersection road and the road it snaps to are (more or * less) parallel. Then we are left with a piece of old road overlapping the new road because the old segment for some reason doesn't show up as * colliding. We have to find it and release it. I think that it shouldn't happen more than once per intersection tho. */ private static void ReleaseQuestionableSegments(FastList <ushort> newNodes, FastList <ushort> newSegments) { foreach (ushort node in newNodes) { NetNode netNode = NetAccess.GetNode(node); ushort foundSegment = 0; for (int i = 0; i < 8; i++) { ushort segment = netNode.GetSegment(i); if (segment != 0 && newSegments.Contains(segment)) { if (foundSegment != 0) { goto continueOuterLoop; } else { foundSegment = segment; } } } Vector3 direction = NetAccess.GetSegment(foundSegment).GetDirection(node); for (int i = 0; i < 8; i++) { ushort segment = netNode.GetSegment(i); if (segment != 0 && segment != foundSegment) { float angle = Vector3.Angle(direction, NetAccess.GetSegment(segment).GetDirection(node)); if (angle < 10) { //Debug.Log("Releasing questionable segment " + segment); NetAccess.ReleaseSegment(segment); goto breakOuterLoop; } } } continueOuterLoop :; } breakOuterLoop :; }
async static Task <SearchResult> _searchByKey(string keyword, int page, EnumMusicType type = EnumMusicType.song) { dynamic obj = await NetAccess.Json(XiamiUrl.url_search_all, "key", keyword, "page", page.ToString()); ///////////// if (obj == null) { return(null); } //string typestr = type.ToString(); //dynamic obj = await XiamiClient.GetDefault().Call_xiami_api(string.Format("Search.{0}s", typestr), // string.Format("\"key={0}\"", keyword), // string.Format("page={0}", page)); //if (obj == null) return null; dynamic data = obj[type.ToString() + "s"]; if (data == null) { return(null); } var items = new List <IMusic>(); foreach (dynamic x in data) { items.Add(MusicFactory.CreateFromJson(x, type)); } var searchType = EnumSearchType.song; Enum.TryParse <EnumSearchType>(type.ToString(), out searchType); bool hasNext = page.ToString() != obj["next"]; var res = new SearchResult { Items = items, Keyword = keyword, Page = page, HasNext = hasNext, SearchType = searchType, }; return(res); }
private static void Connect(ushort node1, ushort node2, Vector3 startDir, Vector3 endDir, NetInfo Info, bool invert = false) { //Debug.Log("Connectiong nodes " + node1 + " and " + node2); NetNode netNode1 = NetAccess.GetNode(node1); NetNode netNode2 = NetAccess.GetNode(node2); if ((netNode1.m_position - netNode2.m_position).magnitude < MIN_SEGMENT_LENGTH) { RepairShortSegment(ref endDir, ref node2); } //NetAccess.CreateSegment(node1,node2,(netNode2.m_position-netNode1.m_position).normalized, (netNode1.m_position - netNode2.m_position).normalized, info, invert); try { NetAccess.CreateSegment(node1, node2, startDir, endDir, Info, invert); } catch (Exception e) { Debug.LogWarning(e); } }
static async Task getUserMusic(string key) { bool isKeyValidMusicType = new Regex("^(song|album|artist|collect)$").IsMatch(key.Trim()); var searchType = EnumSearchType.song; var musicType = EnumMusicType.song; if (isKeyValidMusicType) { Enum.TryParse(key, out searchType); Enum.TryParse(key, out musicType); } int page = 1; while (true) { dynamic obj = null; if (key == "daily") { obj = await XiamiClient.GetDefault().Call_xiami_api("Recommend.DailySongs"); } else if (key == "guess") { if (!isGuessUsed) { await Http.Get("http://www.xiami.com/index/feeds", null); isGuessUsed = true; } musicType = EnumMusicType.all; searchType = EnumSearchType.all; var html = await Http.Get(string.Format(XiamiUrl.url_recommend_guess, page), null); var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html); obj = new JObject(); obj.alls = new JArray(); HtmlNodeCollection nodes = null; nodes = doc.DocumentNode.SelectNodes("*[contains(concat(' ', @class, ' '), ' album ')]"); if (nodes != null) { foreach (var x in nodes) { string id, name, artist_id, artist_name; string logo = x.SelectSingleNode(".//img").Attributes["src"].Value; getIdName(x, "/album/", out id, out name); getIdName(x, "/artist/", out artist_id, out artist_name); try { obj.alls.Add(JObject.Parse(string.Format(@" {{ Type: 'album', album_id : '{0}', album_name : '{1}', artist_id : '{2}', artist_name : '{3}', logo:'{4}', }}", id, name, artist_id, artist_name, logo))); } catch { } } } nodes = doc.DocumentNode.SelectNodes("*[contains(concat(' ', @class, ' '), ' collect ')]"); if (nodes != null) { foreach (var x in nodes) { string id, name, artist_id, artist_name; string logo = x.SelectSingleNode(".//img").Attributes["src"].Value; getIdName(x, "/song/showcollect/id/", out id, out name); getIdName(x, "/u/", out artist_id, out artist_name); try { obj.alls.Add(JObject.Parse(string.Format(@" {{ Type: 'collect', list_id : '{0}', collect_name : '{1}', user_id : '{2}', user_name : '{3}', logo:'{4}', }}", id, name, artist_id, artist_name, logo))); } catch { } } } } else if (key == "collect_recommend") { musicType = EnumMusicType.collect; searchType = EnumSearchType.collect; obj = await XiamiClient.GetDefault().Call_xiami_api("Collects.recommend"); } else if (isKeyValidMusicType) { obj = await NetAccess.Json(XiamiUrl.url_lib_music, "music", key, "uid", Global.AppSettings["xiami_uid"], "page", page.ToString()); } else { Logger.Error(new Exception("user:"******" is not supported")); break; } if (obj == null) { break; } var items = new List <IMusic>(); if (obj[musicType.ToString() + "s"] != null) { obj = obj[musicType.ToString() + "s"] as dynamic; } foreach (dynamic item in obj) { try { EnumMusicType t = musicType; if (item["Type"] != null) { Enum.TryParse(item["Type"].ToString(), out t); } items.Add(MusicFactory.CreateFromJson(item, t)); } catch (Exception e) { } } var sr = new SearchResult { Keyword = "user:"******"song") { foreach (Song item in sr.Items) { item.InFav = true; } } SearchManager.notifyState(sr); //if (obj.more != null && obj.more != "true") // break; page++; } }
private static bool TryConnect(ushort node1, ConnectionPoint cpoint) { NetNode netNode1 = NetAccess.GetNode(node1); NetNode netNode2 = NetAccess.GetNode(cpoint.Node); Vector3 differenceVector = netNode2.m_position - netNode1.m_position; //Debug.Log("TryConnect: " + node1 + ", " + cpoint.Node + ", dist: " + differenceVector.magnitude); // 1) Check max distance if (differenceVector.magnitude > MAX_NODE_DISTANCE) { return(false); } ushort segment1 = NetAccess.GetFirstSegment(netNode1); //ushort segment2 = NetAccess.GetFirstSegment(netNode2); NetSegment netSegment1 = NetAccess.GetSegment(segment1); //NetSegment netSegment2 = NetAccess.GetSegment(segment2); // 2) Check if both segments are roads if (!((netSegment1.Info.m_hasForwardVehicleLanes || netSegment1.Info.m_hasBackwardVehicleLanes) && (cpoint.NetInfo.m_hasForwardVehicleLanes || cpoint.NetInfo.m_hasBackwardVehicleLanes))) { //Debug.Log("Not roads!"); return(false); } // 3) Check max angle (if segments are too close we skip this as it won't give good data) Vector3 direction1 = netSegment1.GetDirection(node1); Vector3 direction2 = cpoint.Direction; float angle1 = Vector3.Angle(direction1, -differenceVector); float angle2 = Vector3.Angle(direction2, -differenceVector); if (differenceVector.magnitude > MIN_SEGMENT_LENGTH) { if (angle1 > MAX_ANGLE || angle2 > MAX_ANGLE) { //Debug.Log("Angle too big: " + angle1 + " " + angle2); return(false); } } // 4) Check if directions of one-way roads match (if so connect) if (NetAccess.IsOneWay(netSegment1.Info) && cpoint.NetInfo) { if (SegmentDirectionBool(netSegment1, node1) ^ cpoint.DirectionBool) { Connect(node1, cpoint.Node, -netSegment1.GetDirection(node1), cpoint.Direction, cpoint.NetInfo, !cpoint.DirectionBool); return(true); } else { return(false); // We won't connect one-way roads whose directions don't match } } // 5) We will favor roads with same NetIfno (if so connect) if (netSegment1.Info == cpoint.NetInfo) { Connect(node1, cpoint.Node, -netSegment1.GetDirection(node1), cpoint.Direction, cpoint.NetInfo, !cpoint.DirectionBool); return(true); } // 6) Lastly we set smaller max distance and angle and try again if (differenceVector.magnitude < (MAX_NODE_DISTANCE * 3 / 4) && angle1 < MAX_ANGLE / 2 && angle2 < MAX_ANGLE / 2) { Connect(node1, cpoint.Node, -netSegment1.GetDirection(node1), cpoint.Direction, cpoint.NetInfo, !cpoint.DirectionBool); return(true); } return(false); }
static async Task <SearchResult> getByType(EnumSearchType type, string id) { List <IMusic> items = new List <IMusic>(); dynamic json = null; switch (type) { case EnumSearchType.song: json = await NetAccess.Json(XiamiUrl.url_song, "id", id); items = GetSong(json); break; case EnumSearchType.album: json = await NetAccess.Json(XiamiUrl.url_album, "id", id); items = GetAlbum(json); break; case EnumSearchType.album_song: json = await NetAccess.Json(XiamiUrl.url_album, "id", id); items = GetSongsOfAlbum(json); break; case EnumSearchType.artist_song: json = await NetAccess.Json(XiamiUrl.url_artist_top_song, "id", id); items = GetSongsOfArtist(json); break; case EnumSearchType.artist: json = await NetAccess.Json(XiamiUrl.url_artist, "id", id); items = GetArtist(json); break; case EnumSearchType.collect: case EnumSearchType.collect_song: json = await NetAccess.Json(XiamiUrl.url_collect, "id", id); getCollectDetails(json["collect"]["id"].ToString()); items = GetSongsOfCollect(json); break; case EnumSearchType.artist_artist: json = await NetAccess.Json(XiamiUrl.url_artsit_similars, "id", id); items = GetSimilarsOfArtist(json); break; case EnumSearchType.artist_album: json = await NetAccess.Json(XiamiUrl.url_artist_albums, "id", id); items = GetAlbumsOfArtist(json); break; default: break; } if (json == null) { return(null); } if (type.ToString().Contains("_")) { var duo = type.ToString().Split("_".ToCharArray()); id = duo[0] + ":" + id; Enum.TryParse(duo[1], out type); } else { id = type.ToString() + ":" + id; type = EnumSearchType.all; } var res = new SearchResult { Items = items, Keyword = id, SearchType = type, Page = 1, }; return(res); }
/* This draws UI shapes on the map. */ protected override void RenderOverlayExtended(RenderManager.CameraInfo cameraInfo) { //debugDrawMethod(cameraInfo); try { if (m_hoverNode != 0 && (stage == Stage.CentralPoint || stage == Stage.MainAxis)) { NetNode hoveredNode = NetAccess.Node(m_hoverNode); RenderManager.instance.OverlayEffect.DrawCircle(cameraInfo, Color.black, hoveredNode.m_position, 15f, hoveredNode.m_position.y - 1f, hoveredNode.m_position.y + 1f, true, true); UIWindow2.instance.m_hoveringLabel.isVisible = false; } else if (stage == Stage.CentralPoint) { RenderMousePositionCircle(cameraInfo); RenderHoveringLabel("Select center of elliptic roundabout"); } else if (stage == Stage.MainAxis) { RenderMousePositionCircle(cameraInfo); RenderHoveringLabel("Select any intersection in direction of main axis"); } else { UIWindow2.instance.m_hoveringLabel.isVisible = false; } if (stage == Stage.MainAxis || stage == Stage.Final) { NetNode centralNodeDraw = NetAccess.Node(centralNode); RenderManager.instance.OverlayEffect.DrawCircle(cameraInfo, Color.red, centralNodeDraw.m_position, 15f, centralNodeDraw.m_position.y - 1f, centralNodeDraw.m_position.y + 1f, true, true); } if (stage == Stage.Final) { NetNode axisNodeDraw = NetAccess.Node(axisNode); RenderManager.instance.OverlayEffect.DrawCircle(cameraInfo, Color.green, axisNodeDraw.m_position, 15f, axisNodeDraw.m_position.y - 1f, axisNodeDraw.m_position.y + 1f, true, true); if (Radius(out float radius1, out float radius2)) { /* If the radiuses didn't change, we don't have to generate new ellipse. */ if (radius1 == prevRadius1 && radius2 == prevRadius2 && ellipse != null) { DrawEllipse(cameraInfo); } else { prevRadius1 = radius1; prevRadius2 = radius2; ellipse = new Ellipse(NetAccess.Node(centralNode).m_position, NetAccess.Node(axisNode).m_position - NetAccess.Node(centralNode).m_position, radius1, radius2); DrawEllipse(cameraInfo); } } else { ellipse = null; } } } catch (Exception e) { Debug.Log("Catched exception while rendering ellipse UI."); Debug.Log(e); stage = Stage.CentralPoint; enabled = false; // ??? } }
void btn_import_click(object sender, RoutedEventArgs e) { var dir = Global.AppSettings["DownloadFolder"]; Task.Run(async() => { var buffer = new List <IMusic>(); int bufferLength = 10; var mp3s = Directory.EnumerateFiles(dir, "*.mp3").ToArray(); foreach (var item in mp3s) { try { var mp3 = TagLib.File.Create(item); var tags = mp3.Tag; if (tags.Comment == null) { continue; } var id = ""; var artistid = ""; var albumid = ""; var logo = ""; var m = reg_ids.Match(tags.Comment); if (!m.Success) { m = reg.Match(tags.Comment); if (!m.Success) { continue; } id = m.Groups[1].Value; var obj = await NetAccess.Json(XiamiUrl.url_song, "id", id); artistid = MusicHelper.Get(obj["song"], "artist_id"); albumid = MusicHelper.Get(obj["song"], "album_id"); logo = StringHelper.EscapeUrl(MusicHelper.Get(obj["song"], "logo")); tags.Comment = string.Join(" ", new[] { id, artistid, albumid }); mp3.Save(); } else { id = m.Groups[1].Value; artistid = m.Groups[2].Value; albumid = m.Groups[3].Value; } var art = System.IO.Path.Combine(Global.BasePath, "cache", albumid + ".art"); if (!File.Exists(art)) { if (string.IsNullOrEmpty(logo)) { var obj = await NetAccess.Json(XiamiUrl.url_song, "id", id); logo = StringHelper.EscapeUrl(MusicHelper.Get(obj["song"], "logo")); } await new System.Net.WebClient().DownloadFileTaskAsync(logo, art); } var song = new Song { Id = id, ArtistId = artistid, AlbumId = albumid, Name = tags.Title, ArtistName = tags.FirstPerformer, AlbumName = tags.Album, FilePath = item, Logo = logo, }; buffer.Add(song); } catch { } if (buffer.Count == bufferLength) { var songs = new List <IMusic>(); foreach (var s in buffer.OfType <Song>()) { SongViewModel.Get(s).HasMp3 = true; } songs.AddRange(buffer); Items.AddItems(songs); buffer.Clear(); } } if (buffer.Count > 0) { foreach (var s in buffer.OfType <Song>()) { SongViewModel.Get(s).HasMp3 = true; } Items.AddItems(buffer); } }); }