| 1 | Article Filtering |
| 2 | ================= |
| 3 | Sometimes you need to automatically tweak the incoming article - mark it starred, remove ads from its contents, or simply ignore it. That's where article filtering feature comes in. |
| 4 | |
| 5 | ## `Article filters` dialog |
| 6 | The dialog seen below offers you a way of managing your article filters. You can assign single filter to multiple feeds. |
| 7 | |
| 8 | `Test` button tests selected filter against existing messages. `Process checked feeds` runs the filter against existing messages from checked feeds - in this mode all modifications made by the filter are saved to existing messages. |
| 9 | |
| 10 | <img alt="alt-img" src="images/filters-dialog.png" width="600px"> |
| 11 | |
| 12 | ## Writing article filter |
| 13 | Article filters are small scripts which are executed automatically when articles/feeds are downloaded. Article filters are `JavaScript` snippets which must provide function with prototype: |
| 14 | |
| 15 | ```js |
| 16 | function filterMessage() { } |
| 17 | ``` |
| 18 | |
| 19 | The function should be fast and must return values which belong to enumeration [`FilteringAction`](#filteringaction-enum). |
| 20 | |
| 21 | Supported set of built-in "standard library" adheres to [ECMA-262](https://ecma-international.org/publications-and-standards/standards/ecma-262). |
| 22 | |
| 23 | Each article is accessible in your script via global variable named `msg` of type `MessageObject`, see [this file](https://github.com/martinrotter/rssguard/blob/master/src/librssguard/core/messageobject.h) for the declaration. Some properties are writeable, allowing you to change contents of the article before it is written to RSS Guard DB. You can mark article important, change its description, perhaps change author name or even assign some [label](labels) to it!!! |
| 24 | |
| 25 | ```{note} |
| 26 | Some attributes (`read/unread/starred` states) are synchronized back to your account's server - so you can for example mark some articles as starred and the change will be propagated back to TT-RSS server if you use TT-RSS. |
| 27 | ``` |
| 28 | |
| 29 | ```{attention} |
| 30 | A special [placeholders](userdata.md#data-placeholder) can be used in article filters. |
| 31 | ``` |
| 32 | |
| 33 | There is also a special variable named `utils`. This variable is of `FilterUtils` type. It offers some useful utility functions for you to use in your filters. |
| 34 | |
| 35 | [Labels](labels) assigned to articles are visible to your filters. You can, therefore, execute actions in your filtering script, based on which labels are assigned to the article. The property is called `assignedLabels` and is an array of the `Label` objects. |
| 36 | |
| 37 | Passed article also offers a special function: |
| 38 | |
| 39 | ```js |
| 40 | Boolean MessageObject.isAlreadyInDatabase(DuplicateCheck) |
| 41 | ``` |
| 42 | |
| 43 | which allows you to perform runtime check for existence of the article in RSS Guard database. Parameter is the value from enumeration `DuplicateCheck`. It specifies how exactly the article should match. |
| 44 | |
| 45 | For example, if you want to check if there is already another article by the same author in a database, you should call `msg.isAlreadyInDatabase(MessageObject.SameAuthor)`. |
| 46 | The values of enumeration can be combined in a single call with the [bitwise OR](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) (`|`) operator, like this: |
| 47 | |
| 48 | ```js |
| 49 | msg.isAlreadyInDatabase(MessageObject.SameAuthor | MessageObject.SameUrl) |
| 50 | ``` |
| 51 | |
| 52 | ## Class Reference Documentation |
| 53 | |
| 54 | Here is the reference documentation of types available for your filtering scripts. |
| 55 | |
| 56 | ### `MessageObject` class |
| 57 | | Type | Name(Parameters) | Return value | Read-only | Synchronized | Description |
| 58 | | :--- | :--- | :--- | :---: | :---: | --- |
| 59 | | Property | `assignedLabels` | `Array<Label>`| ✅ | ✅ | List of labels assigned to the message/article. |
| 60 | | Property | `availableLabels` | `Array<Label>`| ✅ | ❌ | List of labels which are currently available and can be assigned to the message. Available in RSS Guard 3.8.1+. |
| 61 | | Property | `feedCustomId` | `String` | ✅ | ❌ | Service-specific ID of the feed which this message belongs to. |
| 62 | | Property | `accountId` | `Number` | ✅ | ❌ | RSS Guard's ID of the account activated in the program. This property is highly advanced, and you probably do not need to use it at all. |
| 63 | | Property | `id` | `Number` | ✅ | ❌ | ID assigned to the message in RSS Guard local database. |
| 64 | | Property | `customId` | `String` | ❌ | ❌ | ID of the message as provided by the remote service or feed file. |
| 65 | | Property | `title` | `String` | ❌ | ❌ | The message title. |
| 66 | | Property | `url` | `String` | ❌ | ❌ | The message URL. |
| 67 | | Property | `author` | `String` | ❌ | ❌ | Author of the message. |
| 68 | | Property | `contents` | `String` | ❌ | ❌ | Contents of the message. |
| 69 | | Property | `rawContents` | `String` | ❌ | ❌ | This is the RAW contents of the message obtained from remote service/feed. A raw XML or JSON element data. This attribute has the value only if `runningFilterWhenFetching` returns `true`. In other words, this attribute is not persistently stored in the RSS Guard's DB. Also, this attribute is artificially filled in with ATOM-like data when testing the filter. |
| 70 | | Property | `score` | `Number` | ❌ | ❌ | Arbitrary number in range \<0.0, 100.0\>. You can use this number to sort messages in a custom fashion as this attribute also has its own column in articles list. |
| 71 | | Property | `hasEnclosures` | `Boolean` | ✅ | ❌ | Returns `true` if the article has at least one enclosure/attachment. Otherwise returns `false`. |
| 72 | | Property | `created` | `Date` | ❌ | ❌ | Date/time of the message. |
| 73 | | Property | `isRead` | `Boolean` | ❌ | ✅ | Is message read? |
| 74 | | Property | `isImportant` | `Boolean` | ❌ | ✅ | Is message important? |
| 75 | | Property | `isDeleted` | `Boolean` | ❌ | ❌ | Is message placed in recycle bin? |
| 76 | | Method | `addEnclosure(String url, String mime_type)` | `void` | ❌ | ❌ | Adds multimedia attachment to the article. |
| 77 | | Method | `isAlreadyInDatabase(DuplicateCheck criteria)` | `Boolean` | ❌ | ❌ | Allows you to check if message is already stored in the RSS Guard's DB. See possible parameters. |
| 78 | | Method | `findLabelId(String label_name)` | `String` | ❌ | ❌ | If you enter the label name, method returns label's `customId` which then can be used in `assignLabel()` and `deassignLabel` methods. |
| 79 | | Method | `assignLabel(String label_id)` | `Boolean` | ❌ | ❌ | Assigns label to the message. The `String` value is the `customId` property of `Label` type. See its API reference for relevant info. |
| 80 | | Method | `deassignLabel(String label_id)` | `Boolean` | ❌ | ❌ | Removes label from the message. The `String` value is the `customId` property of `Label` type. See its API reference for relevant info. |
| 81 | | Method | `createLabelId(String title, String color_hex_code)` | `String` | ❌ | ❌ | Creates the label with given name and given color hex code in form `#AABBCC`. Color can be omitted in which case auto-generated color is used. |
| 82 | | Method | `addEnclosure(String url, String mime_type)` | `void` | ❌ | ❌ | Appends new enclosure/attachment with given URL and MIME type to the article. |
| 83 | | Property | `runningFilterWhenFetching` | `Boolean` | ✅ | ❌ | Returns `true` if message filter is applied when message is fetched. Returns `false` if filter is applied manually, for example from `Article filters` window. |
| 84 | |
| 85 | ### `Label` class |
| 86 | | Type | Name | Return value | Read-only | Description |
| 87 | | :--- | :--- | :--- | :---: | --- |
| 88 | | Property | `title` | `String` | ✅ | Label name. |
| 89 | | Property | `customId` | `String` | ✅ | Service-specific ID of the label. The ID is used as a unique identifier for label. It is useful if you want to assign/unassign the message label. |
| 90 | | Property | `color` | `Color` | ✅ | Label color. See the type `color` documentation in [Qt docs](https://doc.qt.io/qt-5/qml-color.html). |
| 91 | |
| 92 | ### `FilteringAction` enum |
| 93 | | Enumerant name | Integer value | Description |
| 94 | | :--- | :--- | --- |
| 95 | | `Accept` | 1 | Message is accepted and will be added or updated in DB. |
| 96 | | `Ignore` | 2 | Message is ignored and will **NOT** be added or updated in DB. Already existing message will not be purged from DB. |
| 97 | | `Purge` | 4 | Existing message is purged from the DB completely. Behaves like `Ignore` when there is a new incoming message. |
| 98 | |
| 99 | ```{attention} |
| 100 | The `MessageObject` attributes are synchronized with service even if you return `Purge` or `Ignore`. In other words, even if the filter ignores the article, you can still tweak its properties, and they will be synchronized back to your server. |
| 101 | ``` |
| 102 | |
| 103 | ### `DuplicateCheck` enum |
| 104 | | Enumerant name | Integer value | Description |
| 105 | | :--- | :--- | --- |
| 106 | | `SameTitle` | 1 | Check if message has same title as some another messages. |
| 107 | | `SameUrl` | 2 | Check if message has same URL as some another messages. |
| 108 | | `SameAuthor` | 4 | Check if message has same author as some another messages. |
| 109 | | `SameDateCreated` | 8 | Check if message has same date of creation as some another messages. |
| 110 | | `AllFeedsSameAccount` | 16 | Perform the check across all feeds from your account, not just "current" feed. |
| 111 | | `SameCustomId` | 32 | Check if message with same custom ID exists in RSS Guard DB. |
| 112 | |
| 113 | ### `utils` object |
| 114 | | Type | Name(Parameter) | Return value | How to call | Description |
| 115 | | :--- | :--- | :--- | :--- | --- |
| 116 | | Method | `hostname()` | `String` | `utils.hostname()` | Returns name of your PC. |
| 117 | | Method | `fromXmlToJson(String xml_string)` | `String` | `utils.fromXmlToJson('<h1>hello</h1>')` | Converts XML string into JSON. |
| 118 | | Method | `parseDateTime(String date_time)` | `Date` | `utils.parseDateTime('2020-02-24T08:00:00')` | Converts textual date/time representation into proper `Date` object. |
| 119 | | Method | `runExecutableGetOutput(String exec, String[] params)` | `String` | `utils.runExecutableGetOutput('cmd.exe', ['/c', 'dir'])` | Launches external executable with optional parameters, reads its standard output, and returns the output when executable finishes. |
| 120 | |
| 121 | ## Examples |
| 122 | Accept only messages/articles with title containing "Series Name" or "Another series" in it (whitelist): |
| 123 | ```js |
| 124 | var whitelist = [ |
| 125 | 'Series Name', 'Another series' |
| 126 | ]; |
| 127 | function filterMessage() { |
| 128 | if (whitelist.some(i => msg.title.indexOf(i) != -1)) { |
| 129 | return MessageObject.Accept; |
| 130 | } else { |
| 131 | return MessageObject.Ignore; |
| 132 | } |
| 133 | } |
| 134 | ``` |
| 135 | |
| 136 | Accept only messages/articles with title NOT containing "Other Series Name" or "Some other title" in it (blacklist): |
| 137 | ```js |
| 138 | var blacklist = [ |
| 139 | 'Other Series Name', 'Some other title' |
| 140 | ]; |
| 141 | function filterMessage() { |
| 142 | if (blacklist.some(i => msg.title.indexOf(i) != -1)) { |
| 143 | return MessageObject.Ignore; |
| 144 | } else { |
| 145 | return MessageObject.Accept; |
| 146 | } |
| 147 | } |
| 148 | ``` |
| 149 | |
| 150 | Accept only messages/articles from "Bob", while also mark them important: |
| 151 | ```js |
| 152 | function filterMessage() { |
| 153 | if (msg.author == "Bob") { |
| 154 | msg.isImportant = true; |
| 155 | return MessageObject.Accept; |
| 156 | } |
| 157 | else { |
| 158 | return MessageObject.Ignore; |
| 159 | } |
| 160 | } |
| 161 | ``` |
| 162 | |
| 163 | Replace all "dogs" with "cats"! |
| 164 | ```js |
| 165 | function filterMessage() { |
| 166 | msg.title = msg.title.replace("dogs", "cats"); |
| 167 | return MessageObject.Accept; |
| 168 | } |
| 169 | ``` |
| 170 | |
| 171 | Use published element instead of updated element (for `ATOM` entries only): |
| 172 | ```js |
| 173 | function filterMessage() { |
| 174 | // Read raw contents of message and |
| 175 | // convert to JSON. |
| 176 | json = utils.fromXmlToJson(msg.rawContents); |
| 177 | jsonObj = JSON.parse(json) |
| 178 | |
| 179 | // Read published date and parse it. |
| 180 | publishedDate = jsonObj.entry.published.__text; |
| 181 | parsedDate = utils.parseDateTime(publishedDate); |
| 182 | |
| 183 | // Set new date/time for message and |
| 184 | // proceed. |
| 185 | msg.created = parsedDate; |
| 186 | return MessageObject.Accept; |
| 187 | } |
| 188 | ``` |
| 189 | |
| 190 | Dump RAW data of each message to RSS Guard debug output: |
| 191 | ```js |
| 192 | function filterMessage() { |
| 193 | console.log(msg.rawContents); |
| 194 | return MessageObject.Accept; |
| 195 | } |
| 196 | ``` |
| 197 | |
| 198 | When running the above script for Tiny Tiny RSS, it produces the following debug output: |
| 199 | ``` |
| 200 | ... |
| 201 | time=" 34.360" type="debug" -> feed-downloader: Hooking message took 4 microseconds. |
| 202 | time=" 34.361" type="debug" -> {"always_display_attachments":false,"attachments":[],"author":"Aleš Kapica","comments_count":0,"comments_link":"","content":"<p>\nNaposledy jsem psal o čuňačení v MediaWiki asi před půl rokem, kdy jsem chtěl upozornit na to, že jsem přepracoval svoji původní šablonu Images tak, aby bylo možné používat výřezy z obrázků a stránek generovaných z DjVu a PDF dokumentů. Blogpost nebyl nijak extra hodnocen, takže mě vcelku nepřekvapuje, jak se do hlavní vývojové větve MediaWiki dostávají čím dál větší prasečiny.\n</p>","feed_id":"5903","feed_title":"abclinuxu - blogy","flavor_image":"","flavor_stream":"","guid":"{\"ver\":2,\"uid\":\"52\",\"hash\":\"SHA1:5b49e4d8f612984889ba25e7834e80604c795ff8\"}","id":6958843,"is_updated":false,"labels":[],"lang":"","link":"http://www.abclinuxu.cz/blog/kenyho_stesky/2021/1/cunacime-v-mediawiki-responzivni-obsah-ii","marked":false,"note":null,"published":false,"score":0,"tags":[""],"title":"Čuňačíme v MediaWiki - responzivní obsah II.","unread":true,"updated":1610044674} |
| 203 | time=" 34.361" type="debug" -> feed-downloader: Running filter script, it took 348 microseconds. |
| 204 | time=" 34.361" type="debug" -> feed-downloader: Hooking message took 4 microseconds. |
| 205 | time=" 34.361" type="debug" -> {"always_display_attachments":false,"attachments":[],"author":"kol-ouch","comments_count":0,"comments_link":"","content":"Ahoj, 1. 6. se blíží, tak začínám řešit co s bambilionem fotek na google photos. \n<p class=\"separator\"></p>\nZa sebe můžu říct, že gp mi vyhovují - ne snad úplně tím, že jsou zadarmo, ale hlavně způsobem práce s fotkami, možnostmi vyhledávání v nich podle obsahu, vykopírování textu z nich, provázaností s mapami, recenzemi, možnostmi sdílení, automatickým seskupováním a podobně.","feed_id":"5903","feed_title":"abclinuxu - blogy","flavor_image":"","flavor_stream":"","guid":"{\"ver\":2,\"uid\":\"52\",\"hash\":\"SHA1:1277107408b159882b95ca7151a0ec0160a3971a\"}","id":6939327,"is_updated":false,"labels":[],"lang":"","link":"http://www.abclinuxu.cz/blog/Co_to_je/2021/1/kam-s-fotkama","marked":false,"note":null,"published":false,"score":0,"tags":[""],"title":"Kam s fotkama?","unread":true,"updated":1609750800} |
| 206 | ... |
| 207 | ``` |
| 208 | |
| 209 | For `RSS 2.0` message, the result might look as follows: |
| 210 | ``` |
| 211 | ... |
| 212 | time=" 3.568" type="debug" -> feed-downloader: Hooking message took 6 microseconds. |
| 213 | time=" 3.568" type="debug" -> <item> |
| 214 | <title><![CDATA[Man Utd's Cavani 'not comfortable' in England, says father]]></title> |
| 215 | <description><![CDATA[Manchester United striker Edinson Cavani "does not feel comfortable" and could move back to his native South America, his father said.]]></description> |
| 216 | <link>https://www.bbc.co.uk/sport/football/56341983</link> |
| 217 | <guid isPermaLink="true">https://www.bbc.co.uk/sport/football/56341983</guid> |
| 218 | <pubDate>Tue, 09 Mar 2021 23:46:03 GMT</pubDate> |
| 219 | </item> |
| 220 | |
| 221 | time=" 3.568" type="debug" -> feed-downloader: Running filter script, it took 416 microseconds. |
| 222 | ... |
| 223 | ``` |
| 224 | |
| 225 | Write details of available labels and assign the first label to the message: |
| 226 | ```js |
| 227 | function filterMessage() { |
| 228 | console.log('Number of assigned labels: ' + msg.assignedLabels.length); |
| 229 | console.log('Number of available labels: ' + msg.availableLabels.length); |
| 230 | |
| 231 | var i; |
| 232 | for (i = 0; i < msg.availableLabels.length; i++) { |
| 233 | var lbl = msg.availableLabels[i]; |
| 234 | |
| 235 | console.log('Available label:'); |
| 236 | console.log(' Title: \'' + lbl.title + '\' ID: \'' + lbl.customId + '\''); |
| 237 | } |
| 238 | |
| 239 | if (msg.availableLabels.length > 0) { |
| 240 | console.log('Assigning first label to message...'); |
| 241 | msg.assignLabel(msg.availableLabels[0].customId); |
| 242 | |
| 243 | console.log('Number of assigned labels ' + msg.assignedLabels.length); |
| 244 | } |
| 245 | |
| 246 | console.log(); |
| 247 | return MessageObject.Accept; |
| 248 | } |
| 249 | ``` |
| 250 | |
| 251 | Make sure that you receive only one message with particular URL across all your feeds, plugin/account-wide. All other messages with the same URL are subsequently ignored: |
| 252 | ```js |
| 253 | function filterMessage() { |
| 254 | if (msg.isAlreadyInDatabase(MessageObject.SameUrl | MessageObject.AllFeedsSameAccount)) { |
| 255 | return MessageObject.Ignore; |
| 256 | } |
| 257 | else { |
| 258 | return MessageObject.Accept; |
| 259 | } |
| 260 | } |
| 261 | ``` |
| 262 | |
| 263 | Have multiple separate conditions and assign article to proper label according to condition: |
| 264 | ```js |
| 265 | // Conditions go here, condition is matched if title contains the condition phrase. |
| 266 | var conditions = [ |
| 267 | 'notification', |
| 268 | 'tired', |
| 269 | 'upgrade' |
| 270 | ]; |
| 271 | |
| 272 | // Names of your labels go here. |
| 273 | // Count of names must be same as count of conditions above. |
| 274 | var labels = [ |
| 275 | 'Notifications', |
| 276 | 'Tired stuff', |
| 277 | 'Upgrades' |
| 278 | ]; |
| 279 | |
| 280 | function filterMessage() { |
| 281 | var target_idx = conditions.findIndex(i => msg.title.indexOf(i) >= 0); |
| 282 | |
| 283 | if (target_idx >= 0) { |
| 284 | var target_lbl = msg.findLabelId(labels[target_idx]); |
| 285 | |
| 286 | msg.assignLabel(target_lbl); |
| 287 | } |
| 288 | |
| 289 | return MessageObject.Accept; |
| 290 | } |
| 291 | ``` |
| 292 | |
| 293 | Remove "ads" from messages received from Inoreader. Method simply removes `div` which contains the advertisement: |
| 294 | ```js |
| 295 | function filterMessage() { |
| 296 | msg.contents = msg.contents.replace(/<div>\s*Ads[\S\s]+Remove<\/a>[\S\s]+adv\/www\/delivery[\S\s]+?<\/div>/im, ''); |
| 297 | |
| 298 | return MessageObject.Accept; |
| 299 | } |
| 300 | ``` |