Repository: searxng/searxng

Issue:
Wikimedia Commons
**Working URL to the engine**
https://commons.wikimedia.org

**Why do you want to add this engine?**
Out of all of the Wikimedia projects, Wikimedia Commons is one of only two to not appear in any engine category in SearXNG, with the other being Wikispecies.

**Features of this engine**
It has a collection of [82,886,704](https://commons.wikimedia.org/wiki/Special:Statistics) [freely usable](https://commons.wikimedia.org/wiki/Commons:Reusing_content_outside_Wikimedia) media files.

**How can SearXNG fetch the information from this engine?**
`https://commons.wikimedia.org/w/index.php?search=%s` with `%s` being what you want to search.

**Applicable category of this engine**
General, files, images, music, videos.


Discussion:
There are various categories: Images, Audio, Video, Other media, Categories and pages.

So I guess we need an engine per category (and most probably one Python module).

---

* commons.wikimedia.org has a SPARQL endpoint but it requires a login
* the result page `https://commons.wikimedia.org/w/index.php?search=time&title=Special:MediaSearch&go=Go&type=image` make a XHR request to display the second page `https://commons.wikimedia.org/w/api.php?action=query&format=json&uselang=en&generator=search&gsrsearch=filetype:bitmap|drawing -fileres:0 time&gsrlimit=40&gsroffset=40&gsrinfo=totalhits|suggestion&gsrprop=size|wordcount|timestamp|snippet&prop=info|imageinfo|entityterms&inprop=url&gsrnamespace=6&iiprop=url|size|mime&iiurlheight=180&wbetterms=label`.

Resolving patch:
diff --git a/searx/engines/wikicommons.py b/searx/engines/wikicommons.py
--- a/searx/engines/wikicommons.py
+++ b/searx/engines/wikicommons.py
@@ -3,6 +3,8 @@
 
 """
 
+import datetime
+
 from urllib.parse import urlencode
 
 # about
@@ -14,6 +16,8 @@
     "require_api_key": False,
     "results": 'JSON',
 }
+categories = ['images']
+search_type = 'images'
 
 base_url = "https://commons.wikimedia.org"
 search_prefix = (
@@ -29,17 +33,29 @@
 paging = True
 number_of_results = 10
 
+search_types = {
+    'images': 'bitmap|drawing',
+    'videos': 'video',
+    'audio': 'audio',
+    'files': 'multimedia|office|archive|3d',
+}
+
 
 def request(query, params):
     language = 'en'
     if params['language'] != 'all':
         language = params['language'].split('-')[0]
 
+    if search_type not in search_types:
+        raise ValueError(f"Unsupported search type: {search_type}")
+
+    filetype = search_types[search_type]
+
     args = {
         'uselang': language,
         'gsrlimit': number_of_results,
         'gsroffset': number_of_results * (params["pageno"] - 1),
-        'gsrsearch': "filetype:bitmap|drawing " + query,
+        'gsrsearch': f"filetype:{filetype} {query}",
     }
 
     params["url"] = f"{base_url}/w/api.php{search_prefix}&{urlencode(args, safe=':|')}"
@@ -52,7 +68,6 @@ def response(resp):
 
     if not json.get("query", {}).get("pages"):
         return results
-
     for item in json["query"]["pages"].values():
         imageinfo = item["imageinfo"][0]
         title = item["title"].replace("File:", "").rsplit('.', 1)[0]
@@ -60,11 +75,28 @@ def response(resp):
             'url': imageinfo["descriptionurl"],
             'title': title,
             'content': item["snippet"],
-            'img_src': imageinfo["url"],
-            'resolution': f'{imageinfo["width"]} x {imageinfo["height"]}',
-            'thumbnail_src': imageinfo["thumburl"],
-            'template': 'images.html',
         }
+
+        if search_type == "images":
+            result['template'] = 'images.html'
+            result['img_src'] = imageinfo["url"]
+            result['thumbnail_src'] = imageinfo["thumburl"]
+            result['resolution'] = f'{imageinfo["width"]} x {imageinfo["height"]}'
+        else:
+            result['thumbnail'] = imageinfo["thumburl"]
+
+        if search_type == "videos":
+            result['template'] = 'videos.html'
+            if imageinfo.get('duration'):
+                result['length'] = datetime.timedelta(seconds=int(imageinfo['duration']))
+            result['iframe_src'] = imageinfo['url']
+        elif search_type == "files":
+            result['template'] = 'files.html'
+            result['metadata'] = imageinfo['mime']
+            result['size'] = imageinfo['size']
+        elif search_type == "audio":
+            result['iframe_src'] = imageinfo['url']
+
         results.append(result)
 
     return results


Test patch: