/* * Copyright 2019 tom5079 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.quaver.pupil.hitomi import kotlinx.coroutines.* import java.util.* suspend fun doSearch(query: String, sortByPopularity: Boolean = false) : Set = coroutineScope { val terms = query .trim() .replace(Regex("""^\?"""), "") .lowercase() .split(Regex("\\s+")) .map { it.replace('_', ' ') } val positiveTerms = LinkedList() val negativeTerms = LinkedList() for (term in terms) { if (term.matches(Regex("^-.+"))) negativeTerms.push(term.replace(Regex("^-"), "")) else if (term.isNotBlank()) positiveTerms.push(term) } val positiveResults = positiveTerms.map { async { runCatching { getGalleryIDsForQuery(it) }.getOrElse { emptySet() } } } val negativeResults = negativeTerms.map { async { runCatching { getGalleryIDsForQuery(it) }.getOrElse { emptySet() } } } var results = when { sortByPopularity -> getGalleryIDsFromNozomi(null, "popular", "all") positiveTerms.isEmpty() -> getGalleryIDsFromNozomi(null, "index", "all") else -> emptySet() } fun filterPositive(newResults: Set) { results = when { results.isEmpty() -> newResults else -> results intersect newResults } } fun filterNegative(newResults: Set) { results = results subtract newResults } //positive results positiveResults.forEach { filterPositive(it.await()) } //negative results negativeResults.forEach { filterNegative(it.await()) } results }