From dd7f669c797d8bf844140001a094f87f28188351 Mon Sep 17 00:00:00 2001 From: dec05eba Date: Sat, 27 Jun 2020 22:52:20 +0200 Subject: Fix search result broken if contains curly braces --- src/plugins/Youtube.cpp | 65 ++++++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 30 deletions(-) (limited to 'src/plugins/Youtube.cpp') diff --git a/src/plugins/Youtube.cpp b/src/plugins/Youtube.cpp index 3d7e4fb..c82fdbe 100644 --- a/src/plugins/Youtube.cpp +++ b/src/plugins/Youtube.cpp @@ -25,6 +25,37 @@ namespace QuickMedia { } } + static size_t find_end_of_json(const std::string &website_data, size_t data_start) { + int brace_count = 0; + char string_char = '\0'; + bool escape = false; + for(size_t i = data_start; i < website_data.size(); ++i) { + char c = website_data[i]; + if(c == '{' && string_char == '\0') { + escape = false; + ++brace_count; + } else if(c == '}' && string_char == '\0') { + escape = false; + --brace_count; + if(brace_count == 0) { + return i + 1; + } + } else if(c == '"' || c == '\'') { + if(string_char == '\0') { + string_char = c; + } else if(c == string_char && !escape) { + string_char = '\0'; + } + escape = false; + } else if(c == '\\' && string_char) { + escape = !escape; + } else if(string_char) { + escape = false; + } + } + return std::string::npos; + } + // TODO: Speed this up by using string.find instead of parsing html SuggestionResult Youtube::update_search_suggestions(const std::string &text, BodyItems &result_items) { // Keep this for backup. This is using search suggestion the same way youtube does it, but the results @@ -138,22 +169,9 @@ namespace QuickMedia { return SuggestionResult::ERR; data_start = data_start + 26; - size_t data_end = 0; - int brace_count = 0; - for(size_t i = data_start; i < website_data.size(); ++i) { - char c = website_data[i]; - if(c == '{') - ++brace_count; - else if(c == '}') { - --brace_count; - if(brace_count == 0) { - data_end = i + 1; - break; - } - } - } + size_t data_end = find_end_of_json(website_data, data_start); - if(data_end == 0) + if(data_end == std::string::npos) return SuggestionResult::ERR; Json::Value json_root; @@ -389,22 +407,9 @@ namespace QuickMedia { return result_items; data_start = data_start + 26; - size_t data_end = 0; - int brace_count = 0; - for(size_t i = data_start; i < website_data.size(); ++i) { - char c = website_data[i]; - if(c == '{') - ++brace_count; - else if(c == '}') { - --brace_count; - if(brace_count == 0) { - data_end = i + 1; - break; - } - } - } + size_t data_end = find_end_of_json(website_data, data_start); - if(data_end == 0) + if(data_end == std::string::npos) return result_items; Json::Value json_root; -- cgit v1.2.3