private void GetNewTicket() { Log("Getting new ticket"); if (lastAccount?.Password == null) { throw new InvalidOperationException("Set login credentials before logging in!"); } var buffer = browser.GetResponse(Constants.UrlConstants.GetTicket, ticketCredentials); if (buffer.Equals(SiteIsDisabled, StringComparison.OrdinalIgnoreCase)) { throw new Exception("Site API disabled for maintenance."); } // assign the data to our account model var result = buffer.DeserializeTo <ApiAuthResponse>(); var hasError = !string.IsNullOrWhiteSpace(result.Error); lastTicket = result.Ticket; if (hasError) { throw new Exception(result.Error); } foreach (var item in result.Characters.OrderBy(x => x)) { lastAccount.Characters.Add(item); } foreach (var friend in result.Friends) { if (lastAccount.AllFriends.ContainsKey(friend.From)) { lastAccount.AllFriends[friend.From].Add(friend.To); } else { var list = new List <string> { friend.To }; lastAccount.AllFriends.Add(friend.From, list); } } foreach ( var bookmark in result.Bookmarks.Where(bookmark => !lastAccount.Bookmarks.Contains(bookmark.Name))) { lastAccount.Bookmarks.Add(bookmark.Name); } lastInfoRetrieval = DateTime.Now; ShouldGetNewTicket = false; Log("Successfully got a new ticket: " + result.Ticket.Substring(result.Ticket.Length - 6)); }
public int UploadLog(ReportModel report, IEnumerable <IMessage> log) { try { var logId = -1; // log upload format doesn't allow much HTML or anything other than line breaks. var sb = new StringBuilder(); sb.Append("==================================\n"); sb.Append($"{Constants.FriendlyName} log upload " + $"\n{DateTime.UtcNow.ToShortDateString()} in {report.Tab}" + $"\nreported user: {report.Reported}" + "\ntime stamps in 24hr UTC\n"); sb.Append("==================================\n"); log.Where(x => !x.IsHistoryMessage) .Select(m => $"{m.PostedTime.ToUniversalTime().ToTimeStamp()} {m.Poster.Name}: {m.Message} \n") .Each(m => sb.Append(m)); var toUpload = new Dictionary <string, object> { { "account", model.AccountName.ToLower() }, { "ticket", ticketService.Ticket }, { "character", report.Reporter.Name }, { "log", sb.ToString() }, { "reportText", report.Complaint }, { "reportUser", report.Reported }, { "channel", report.Tab } }; var buffer = browser.GetResponse(Constants.UrlConstants.UploadLog, toUpload, true); var result = buffer.DeserializeTo <ApiUploadLogResponse>(); var hasError = !string.IsNullOrWhiteSpace(result.Error); if (hasError) { ticketService.ShouldGetNewTicket = true; UploadLog(report, log); } if (result.LogId != null) { int.TryParse(result.LogId, out logId); } Log($"Uploaded report log in tab {report.Tab} with id of {logId}"); return(logId); } catch (Exception) { // when dealing with the web it's always possible something could mess up Log($"Failed to get id for report log in tab {report.Tab}"); return(-1); } }
private IList <ApiFriendRequest> DoApiAction(string endpoint) { var command = new Dictionary <string, object> { { "account", account.AccountName.ToLower() }, { "ticket", ticketService.Ticket } }; var buffer = browser.GetResponse(endpoint, command); var result = (ApiFriendRequestsResponse)SimpleJson.DeserializeObject(buffer, typeof(ApiFriendRequestsResponse)); var hasError = !string.IsNullOrWhiteSpace(result.Error); if (string.Equals("Ticked expired", result.Error, StringComparison.OrdinalIgnoreCase)) { ticketService.ShouldGetNewTicket = true; DoApiAction(endpoint); } if (hasError) { events.NewError(result.Error); } return(result.Requests); }
private void GetSearchTerms(string character) { var cache = SettingsService.RetrieveTerms(character); if (cache == null) { var worker = new BackgroundWorker(); worker.DoWork += (sender, args) => PopulateSearchTerms(browser.GetResponse(Constants.UrlConstants.SearchFields, true)); worker.RunWorkerAsync(); } else { availableSearchTerms = new ObservableCollection <SearchTermModel>(cache.AvailableTerms); selectedSearchTerms = new ObservableCollection <SearchTermModel>(cache.SelectedTerms); } AvailableSearchTerms = new ListCollectionView(availableSearchTerms); AvailableSearchTerms.GroupDescriptions.Add(new PropertyGroupDescription("Category", new CategoryConverter())); AvailableSearchTerms.SortDescriptions.Add(new SortDescription("DisplayName", ListSortDirection.Ascending)); AvailableSearchTerms.Filter = o => ((SearchTermModel)o).DisplayName.ContainsOrdinal(searchString); SelectedSearchTerms = new ListCollectionView(selectedSearchTerms); SelectedSearchTerms.SortDescriptions.Add(new SortDescription("Category", ListSortDirection.Ascending)); SelectedSearchTerms.SortDescriptions.Add(new SortDescription("DisplayName", ListSortDirection.Ascending)); updateActiveViews = DeferredAction.Create(AvailableSearchTerms.Refresh); OnPropertyChanged("AvailableSearchTerms"); OnPropertyChanged("SelectedSearchTerms"); }
private void SendNoteAsyncHandler(object sender, DoWorkEventArgs e) { var args = (IDictionary <string, object>)e.Argument; var characterName = (string)args["dest"]; var message = (string)args["message"]; var subject = (string)args["title"]; var resp = browser.GetResponse(Constants.UrlConstants.SendNote, args, true); var json = (JObject)JsonConvert.DeserializeObject(resp); JToken errorMessage; var error = string.Empty; if (json.TryGetValue("error", out errorMessage)) { error = errorMessage.ToString(); events.NewError(error); } if (!string.IsNullOrEmpty(error)) { return; } var model = cm.CurrentPms.FirstByIdOrNull(characterName); if (model == null) { return; } Application.Current.Dispatcher.BeginInvoke((Action)(() => { model.Notes.Add( new MessageModel(cm.CurrentCharacter, message)); model.NoteSubject = subject; })); }
private void CheckForThemes() { try { var currentThemeParser = new TextFieldParser(new FileStream("Theme\\theme.csv", FileMode.Open, FileAccess.Read, FileShare.Read)); currentThemeParser.SetDelimiters(","); // go through header currentThemeParser.ReadLine(); CurrentTheme = GetThemeModel(currentThemeParser.ReadFields()); OnPropertyChanged("CurrentTheme"); currentThemeParser.Close(); HasCurrentTheme = true; OnPropertyChanged("HasCurrentTheme"); } catch { HasCurrentTheme = false; OnPropertyChanged("HasCurrentTheme"); } try { var resp = browser.GetResponse(Constants.ThemeIndexUrl); if (resp == null) { return; } var parser = new TextFieldParser(new StringReader(resp)) { TextFieldType = FieldType.Delimited }; parser.SetDelimiters(","); // go through header parser.ReadLine(); Dispatcher.BeginInvoke((Action)(() => Themes.Clear())); while (!parser.EndOfData) { var row = parser.ReadFields(); var model = GetThemeModel(row); if (HasCurrentTheme && model.Name == CurrentTheme.Name && model.Version == CurrentTheme.Version) { continue; } Dispatcher.BeginInvoke((Action)(() => Themes.Add(model))); } parser.Close(); } catch (WebException) { } }
private void GetProfileDataAsyncHandler(object s, DoWorkEventArgs e) { var characterName = (string)e.Argument; PmChannelModel model = null; try { model = state.Resolve <PmChannelModel>(characterName); } catch (ResolutionFailedException) { } if (!invalidCacheList.Contains(characterName)) { ProfileData cache; profileCache.TryGetValue(characterName, out cache); cache = cache ?? SettingsService.RetrieveProfile(characterName); if (cache != null) { if (!profileCache.ContainsKey(characterName)) { cache.Kinks = cache.Kinks.Select(GetFullKink).ToList(); } if (cm.CurrentCharacter.NameEquals(characterName)) { cm.CurrentCharacterData = cache; } if (model != null) { model.ProfileData = cache; } profileCache[characterName] = cache; return; } } else { invalidCacheList.Remove(characterName); } var resp = browser.GetResponse(Constants.UrlConstants.CharacterPage + characterName, true); var htmlDoc = new HtmlDocument { OptionCheckSyntax = false }; HtmlNode.ElementsFlags.Remove("option"); htmlDoc.LoadHtml(resp); if (htmlDoc.DocumentNode == null) { return; } try { var profileBody = string.Empty; var profileText = htmlDoc.DocumentNode.SelectNodes(ProfileBodySelector); if (profileText != null) { profileBody = WebUtility.HtmlDecode(profileText[0].InnerHtml); profileBody = profileBody.Replace("<br>", "\n"); } IEnumerable <ProfileTag> profileTags = new List <ProfileTag>(); var statboxTags = htmlDoc.DocumentNode.SelectNodes(ProfileStatBoxSelector); if (statboxTags != null && statboxTags.Count != 0) { profileTags = statboxTags[0].ChildNodes .Where(x => x.Name == "span" || x.Name == "#text") .Select(x => x.InnerText.Trim().DoubleDecode()) .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList() .Chunk(2) .Select(x => x.ToList()) .Select(x => new ProfileTag { Label = x[0], Value = x[1].Substring(1).Trim() }); } var otherTags = htmlDoc.DocumentNode.SelectNodes(ProfileTagsSelector); if (otherTags != null) { profileTags = profileTags.Union(otherTags.SelectMany(selection => selection.ChildNodes .Where(x => x.Name == "span" || x.Name == "#text") .Select(x => x.InnerText.Trim().DoubleDecode()) .ToList() .Chunk(2) .Select(x => x.ToList()) .Select(x => new ProfileTag { Label = x[0].Replace(":", "").Trim(), Value = x[1] }))); } IEnumerable <string> allAlts = new List <string>(); var profileAlts = htmlDoc.DocumentNode.SelectNodes(ProfileAltsSelector); if (profileAlts != null) { allAlts = profileAlts[0].ChildNodes .Where(x => x.Name == "a") .Select(x => x.InnerText.Trim().DoubleDecode()) .Where(x => !string.IsNullOrWhiteSpace(x)) .ToList(); } var allKinks = new List <ProfileKink>(); var profileKinks = htmlDoc.DocumentNode.SelectNodes(ProfileKinksSelector); if (profileKinks != null) { allKinks = profileKinks.SelectMany(selection => { var kind = (KinkListKind) Enum.Parse(typeof(KinkListKind), selection.Id.Substring("Character_Fetishlist".Length)); return(selection.Descendants() .Where(x => x.Name == "a") .Select(x => { var tagId = int.Parse(x.Id.Substring("Character_Listedfetish".Length)); var isCustomKink = x.Attributes.First(y => y.Name.Equals("class")).Value.Contains("FetishGroupCustom"); var tooltip = x.Attributes.FirstOrDefault(y => y.Name.Equals("rel")); var name = x.InnerText.Trim(); return new ProfileKink { Id = tagId, IsCustomKink = isCustomKink, Name = isCustomKink ? name.DoubleDecode() : string.Empty, KinkListKind = kind, Tooltip = tooltip != null && isCustomKink ? tooltip.Value.DoubleDecode() : string.Empty }; })); }).ToList(); } var id = htmlDoc.DocumentNode.SelectSingleNode(ProfileIdSelector).Attributes["value"].Value; ApiProfileImagesResponse images; try { var imageResp = browser.GetResponse(Constants.UrlConstants.ProfileImages, new Dictionary <string, object> { { "character_id", id } }, true); images = JsonConvert.DeserializeObject <ApiProfileImagesResponse>(imageResp); images.Images = images.Images.OrderBy(x => x.SortOrder).ToList(); } catch { images = new ApiProfileImagesResponse { Images = new List <ApiProfileImage>() }; } var profileData = CreateModel(profileBody, profileTags, images, allKinks, allAlts); SettingsService.SaveProfile(characterName, profileData); profileCache[characterName] = profileData; if (model != null) { model.ProfileData = profileData; } if (cm.CurrentCharacter.NameEquals(characterName)) { cm.CurrentCharacterData = profileData; } } catch { } }