From 3ac45668d4229c79f0028cf536fa13950308619c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= <ondra@ondrovo.com>
Date: Sun, 24 Feb 2019 13:20:57 +0100
Subject: [PATCH] less dumb title -> filename conversion

---
 background.js | 24 +++++++++++++++++++-----
 manifest.json |  2 +-
 2 files changed, 20 insertions(+), 6 deletions(-)

diff --git a/background.js b/background.js
index 2b58f0b..ebf3eb1 100644
--- a/background.js
+++ b/background.js
@@ -14,13 +14,27 @@ function sanitizeUrl(unsafe) {
     .replace(/;/g, "%3B");  
 }
 
-/** Remove the most risky characters from a filename string */
+/** 
+ * Remove the most risky characters from a filename string 
+ * 
+ * Firefox doesn't allow these: |"*?:<>
+ */
 function cleanFilename(unsafe) {
   return unsafe
-    .replace(/::/g, " - ")
-    .replace(/[/\\?*|"'<>:]+/g, " ")
-    .replace(/\s+/g, " ")
-    .replace(/[\._-]$/g, "")
+    .replace(/::/g, " - ") // common delimiter (e.g. My Cool Article :: Website.com)
+    .replace(/[?*]+/g, " ") // this is just noise, drop it
+    .replace(/[\<\[]/g, "(")
+    .replace(/[\>\]]/g, ")")
+    .replace(/ :/g, " -")
+    .replace(/: /g, " ")
+    .replace(/:/g, "_")
+    .replace(/"/g, "'") // firefox hates double quote
+    .replace(/[/\\|]/g, "-") // porobable delimiters that should be kept in some form
+    .replace(/-+/g, "-") // collapse multiple hyphen (may result from substitutions)
+    .replace(/[\+=]/g, "_") // other suspicious stuff
+    .replace(/\s+/g, " ") // collapse multiple whitespace
+    .replace(/[\._,-]+$/g, "") // the filename should not end on special chars
+    .replace(/^[\._,-]+/g, "") // nor start
     .trim();
 }
 
diff --git a/manifest.json b/manifest.json
index b82ce90..d4eac72 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
   "manifest_version":2,
   "author": "Ondřej Hruška",
   "name":"Save Link to File",
-  "version":"0.4",
+  "version":"0.5",
   "description":"Saves the current page as a HTML file with auto-redirect. It's like a bookmark you can store anywhere on your disk.",
   "icons":{
     "48":"icon-dark.svg",