├── .gitignore ├── .rubocop.yml ├── .tx └── config ├── COPYRIGHT.txt ├── LICENSE.txt ├── README.md ├── app └── controllers │ └── topic_previews │ └── thumbnail_selection_controller.rb ├── config ├── locales │ ├── server.en.yml │ ├── server.es.yml │ ├── server.fr.yml │ └── server.it.yml ├── routes.rb └── settings.yml ├── lib └── topic_previews │ ├── cooked_post_processor_extension.rb │ ├── engine.rb │ ├── list_helper_extension.rb │ ├── optimized_image_extension.rb │ ├── post_guardian_extension.rb │ ├── search_topic_list_item_serializer_extension.rb │ ├── suggested_topic_serializer_extension.rb │ ├── thumbnail_selection_helper.rb │ ├── topic_extension.rb │ ├── topic_list_extension.rb │ ├── topic_list_item_edits_mixin.rb │ ├── topic_list_item_serializer_extension.rb │ ├── topic_list_serializer_lib.rb │ ├── topic_view_serializer_extension.rb │ └── upload_extension.rb └── plugin.rb /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | /gems 3 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | inherit_gem: 2 | rubocop-discourse: default.yml 3 | 4 | RSpec/ContextWording: 5 | Enabled: false 6 | 7 | RSpec/DescribeClass: 8 | Enabled: false 9 | 10 | AllCops: 11 | Exclude: 12 | - "**/gems/**/*" 13 | - "**/vendor/**/*" 14 | -------------------------------------------------------------------------------- /.tx/config: -------------------------------------------------------------------------------- 1 | [main] 2 | host = https://www.transifex.com 3 | 4 | [discourse-topic-previews.client-en-yml] 5 | file_filter = config/locales/client..yml 6 | minimum_perc = 0 7 | source_file = config/locales/client.en.yml 8 | source_lang = en 9 | type = YML 10 | 11 | [discourse-topic-previews.server-en-yml] 12 | file_filter = config/locales/server..yml 13 | source_file = config/locales/server.en.yml 14 | source_lang = en 15 | type = YML 16 | 17 | -------------------------------------------------------------------------------- /COPYRIGHT.txt: -------------------------------------------------------------------------------- 1 | All code in this repository is Copyright 2025 by Robert Barrow. 2 | 3 | This program is free software; you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation; either version 2 of the License, or (at 6 | your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, but 9 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 10 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 11 | for more details. 12 | 13 | You should have received a copy of the GNU General Public License 14 | along with this program as the file LICENSE.txt; if not, please see 15 | http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. 16 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # discourse-topic-previews (sidecar plugin) 2 | 3 | This is a sidecar plugin to add features to the otherwise [standalone TC Topic List Previews](https://github.com/paviliondev/discourse-tc-topic-list-previews): 4 | 5 | - 'actions’ (bookmarking and liking from Topic List) 6 | - Thumbnail Picker in the Topic Meta Editor. 7 | - Optionally suppresses links in excerpts to make them look a lot better 8 | 9 | This sidecar also includes some experimental features: 10 | 11 | - Colourisation of background based on dominant colour of the thumbnail 12 | - Processing of the thumbnails to remove any black borders (critical to determining the best dominant colour). 13 | - Option to recreate thumbnails on rebuild of Post to allow you to quickly manage border elimination. 14 | 15 | You must have the Theme Component installed for it to work/be useful 16 | 17 | [See further here](https://meta.discourse.org/t/topic-list-previews-theme-component/209973?u=merefield). 18 | -------------------------------------------------------------------------------- /app/controllers/topic_previews/thumbnail_selection_controller.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module ::TopicPreviews 3 | class ThumbnailSelectionController < ::ApplicationController 4 | requires_plugin PLUGIN_NAME 5 | 6 | def index 7 | params.require(:topic) 8 | 9 | raise Discourse::InvalidAccess.new unless current_user 10 | 11 | topic_id = params[:topic].to_i 12 | topic = Topic.find(topic_id) 13 | user_id = topic.user_id 14 | 15 | thumbnails = [] 16 | 17 | if current_user.id == user_id || current_user.staff? 18 | thumbnails = TopicPreviews::ThumbnailSelectionHelper.get_thumbnails_from_topic(topic) 19 | end 20 | 21 | respond_to do |format| 22 | format.json { render json: { thumbnailselection: thumbnails } } 23 | end 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /config/locales/server.en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | site_settings: 3 | topic_list_previews_enabled: "Enable Topic List Previews side-car plugin" 4 | topic_list_show_like_on_current_users_posts: "Show an inactive like button in topic list items previewing a post created by the current user (non-default Discourse behavior)." 5 | topic_list_excerpt_length: "Character length of topic excerpts." 6 | topic_list_excerpt_remove_links: "Remove links from excerpts." 7 | topic_list_enable_thumbnail_colour_determination: "Enable dominant thumbnail colour determination for additional styling" 8 | topic_list_enable_thumbnail_recreation_on_post_rebuild: "Recreate thumbnails when you rebuild Topic's first post HTML" 9 | topic_list_enable_thumbnail_black_border_elimination: "Enable black border elimination for YouTube thumbnails" 10 | topic_list_search_previews_enabled: "Display search results as thumbnail grid (experimental)" 11 | topic_list_keep_link_text_content: "Keep text content inside link tags from excerpts" 12 | -------------------------------------------------------------------------------- /config/locales/server.es.yml: -------------------------------------------------------------------------------- 1 | es: 2 | site_settings: 3 | topic_list_show_like_on_current_users_posts: "Mostrar un botón de 'Me gusta' inactivo en los elementos de la lista de temas en la vista previa de una publicación creada por el usuario actual (comportamiento de Discourse no predeterminado)." 4 | topic_list_excerpt_length: "Longitud del carácter de los extractos del tema." 5 | -------------------------------------------------------------------------------- /config/locales/server.fr.yml: -------------------------------------------------------------------------------- 1 | fr: 2 | site_settings: 3 | topic_list_show_like_on_current_users_posts: "Afficher un bouton semblable à inactif dans les éléments de la liste de sujets, prévisualisant un article créé par l'utilisateur actuel (comportement Discourse autre que par défaut)." 4 | topic_list_excerpt_length: "Longueur de caractère des extraits de sujet." 5 | topic_list_excerpt_remove_links: "Supprimer les liens des extraits de sujet" 6 | topic_list_keep_link_text_content: "Conserver le texte à l'intérieur des balises de lien des extraits de sujet" 7 | -------------------------------------------------------------------------------- /config/locales/server.it.yml: -------------------------------------------------------------------------------- 1 | it: 2 | site_settings: 3 | topic_list_show_like_on_current_users_posts: "Mostra un pulsante inattivo Mi piace in tutti gli elenchi degli argomenti mostrando l'anteprima del messaggio creato dall'utente corrente (comportamento di Discourse non predefinito)." 4 | topic_list_excerpt_length: "Lunghezza in caratteri degli estratti degli argomenti." 5 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | Discourse::Application.routes.draw do 3 | mount ::TopicPreviews::Engine, at: '/topic-previews' 4 | end 5 | 6 | TopicPreviews::Engine.routes.draw do 7 | get 'thumbnail-selection' => 'thumbnail_selection#index' 8 | end 9 | -------------------------------------------------------------------------------- /config/settings.yml: -------------------------------------------------------------------------------- 1 | plugins: 2 | topic_list_previews_enabled: 3 | default: true 4 | client: true 5 | topic_list_show_like_on_current_users_posts: 6 | default: false 7 | client: true 8 | topic_list_excerpt_length: 9 | default: 200 10 | client: true 11 | topic_list_excerpt_remove_links: 12 | default: true 13 | client: false 14 | topic_list_keep_link_text_content: 15 | default: false 16 | client: false 17 | topic_list_enable_thumbnail_colour_determination: 18 | default: false 19 | client: true 20 | topic_list_enable_thumbnail_recreation_on_post_rebuild: 21 | default: false 22 | client: false 23 | topic_list_enable_thumbnail_black_border_elimination: 24 | default: false 25 | client: false 26 | topic_list_search_previews_enabled: 27 | default: false 28 | client: true 29 | topic_list_dominant_color_quantisation: 30 | default: 5 31 | max: 10 32 | min: 3 33 | client: false 34 | -------------------------------------------------------------------------------- /lib/topic_previews/cooked_post_processor_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require_dependency 'cooked_post_processor' 3 | 4 | module TopicPreviews 5 | module CookedPostProcessorExtension 6 | def extract_images_for_post 7 | # all images with a src attribute 8 | @doc.css("img[src]") - 9 | # minus emojis 10 | @doc.css("img.emoji") - 11 | # minus images inside quotes 12 | @doc.css(".quote img") - 13 | # minus onebox site icons 14 | @doc.css("img.site-icon") - 15 | # minus onebox avatars 16 | @doc.css("img.onebox-avatar") #- 17 | # minus small onebox images (large images are .aspect-image-full-size) 18 | # @doc.css(".onebox .aspect-image img") 19 | end 20 | 21 | def update_post_image 22 | 23 | if @post.is_first_post? && @post.topic.custom_fields["user_chosen_thumbnail_url"] 24 | @post.topic.generate_thumbnails!(extra_sizes: get_extra_sizes) 25 | else 26 | 27 | upload = nil 28 | eligible_image_fragments = extract_images_for_post 29 | 30 | # Loop through those fragments until we find one with an upload record 31 | @post.each_upload_url(fragments: eligible_image_fragments) do |src, path, sha1| 32 | upload = Upload.find_by(sha1: sha1) 33 | break if upload 34 | end 35 | 36 | if upload.present? 37 | @post.update_column(:image_upload_id, upload.id) # post 38 | if @post.is_first_post? # topic 39 | @post.topic.update_column(:image_upload_id, upload.id) 40 | @post.topic.generate_thumbnails!(extra_sizes: get_extra_sizes) 41 | end 42 | else 43 | @post.update_column(:image_upload_id, nil) if @post.image_upload_id 44 | @post.topic.update_column(:image_upload_id, nil) if @post.topic.image_upload_id && @post.is_first_post? 45 | nil 46 | end 47 | end 48 | end 49 | 50 | def get_extra_sizes 51 | ThemeModifierHelper.new(theme_ids: Theme.all.pluck(:id)).topic_thumbnail_sizes 52 | end 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /lib/topic_previews/engine.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module ::TopicPreviews 4 | class Engine < ::Rails::Engine 5 | engine_name PLUGIN_NAME 6 | isolate_namespace TopicPreviews 7 | config.autoload_paths << File.join(config.root, "lib") 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /lib/topic_previews/list_helper_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TopicPreviews 4 | module ListHelperExtension 5 | class << self 6 | 7 | def load_previewed_posts(topics, user = nil) 8 | # TODO: better to keep track of previewed posts' id so they can be loaded at once 9 | posts_map = {} 10 | post_actions_map = {} 11 | accepted_answer_post_ids = [] 12 | qa_topic_ids = [] 13 | normal_topic_ids = [] 14 | previewed_post_ids = [] 15 | 16 | topics.each do |topic| 17 | if post_id = topic.custom_fields["accepted_answer_post_id"]&.to_i 18 | accepted_answer_post_ids << post_id 19 | elsif ::Topic.respond_to?(:qa_enabled) && ::Topic.qa_enabled(topic) 20 | qa_topic_ids << topic.id 21 | else 22 | normal_topic_ids << topic.id 23 | end 24 | end 25 | 26 | Post.where("id IN (?)", accepted_answer_post_ids).each do |post| 27 | posts_map[post.topic_id] = post 28 | previewed_post_ids << post.id 29 | end 30 | 31 | Post.where("post_number <> 1 AND sort_order = 1 AND topic_id in (?)", qa_topic_ids).each do |post| 32 | posts_map[post.topic_id] = post 33 | previewed_post_ids << post.id 34 | end 35 | 36 | Post.where("post_number = 1 AND topic_id IN (?)", normal_topic_ids).each do |post| 37 | posts_map[post.topic_id] = post 38 | previewed_post_ids << post.id 39 | end 40 | 41 | if user 42 | PostAction.where("post_id IN (?) AND user_id = ?", previewed_post_ids, user.id).each do |post_action| 43 | (post_actions_map[post_action.post_id] ||= []) << post_action 44 | end 45 | end 46 | 47 | topics.each do |topic| 48 | topic.previewed_post = posts_map[topic.id] 49 | topic.previewed_post_actions = post_actions_map[topic.previewed_post.id] if topic.previewed_post 50 | topic.previewed_post_bookmark = Bookmark.find_by(bookmarkable_id: topic.first_post.id) 51 | end 52 | 53 | topics 54 | end 55 | end 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /lib/topic_previews/optimized_image_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require_dependency 'optimized_image' 3 | 4 | module TopicPreviews 5 | module OptimizedImageExtension 6 | 7 | def optimize(operation, from, to, dimensions, opts = {}) 8 | method_name = "#{operation}_instructions" 9 | 10 | pp "########################### ###########################" 11 | pp method_name 12 | pp "########################### ###########################" 13 | instructions = self.public_send(method_name.to_sym, from, to, dimensions, opts) 14 | pp "########################### ###########################" 15 | pp instructions 16 | pp "########################### ###########################" 17 | pp from 18 | pp "########################### ###########################" 19 | pp to 20 | pp "########################### ###########################" 21 | pp dimensions 22 | pp "########################### ###########################" 23 | pp opts 24 | pp "########################### ###########################" 25 | convert_with(instructions, to, opts) 26 | end 27 | 28 | def border_elimination_instructions 29 | %W{ 30 | -gravity center 31 | -crop 100%x75% 32 | +repage 33 | } 34 | end 35 | 36 | def resize_instructions(from, to, dimensions, opts = {}) 37 | if crop_for_youtube?(opts) 38 | dimensions = dimensions.split("x", 2)[0] 39 | end 40 | 41 | ensure_safe_paths!(from, to) 42 | 43 | # note FROM my not be named correctly 44 | from = prepend_decoder!(from, to, opts) 45 | to = prepend_decoder!(to, to, opts) 46 | 47 | instructions = ['convert', "#{from}[0]"] 48 | 49 | if opts[:colors] 50 | instructions << "-colors" << opts[:colors].to_s 51 | end 52 | 53 | if opts[:quality] 54 | instructions << "-quality" << opts[:quality].to_s 55 | end 56 | 57 | # NOTE: ORDER is important! 58 | instructions.concat(%W{ 59 | -auto-orient 60 | -gravity center 61 | }) 62 | 63 | if crop_for_youtube?(opts) 64 | instructions.concat(%W{ 65 | -#{thumbnail_or_resize} #{dimensions.split("x", 2)[0]}^ 66 | }) 67 | else 68 | instructions.concat(%W{ 69 | -background transparent 70 | -#{thumbnail_or_resize} #{dimensions}^ 71 | -extent #{dimensions} 72 | }) 73 | end 74 | 75 | if crop_for_youtube?(opts) 76 | instructions.concat(border_elimination_instructions) 77 | end 78 | 79 | instructions.concat(%W{ 80 | -interpolate catrom 81 | -unsharp 2x0.5+0.7+0 82 | -interlace none 83 | -profile #{File.join(Rails.root, 'vendor', 'data', 'RT_sRGB.icm')} 84 | }) 85 | 86 | instructions.concat(%W{ 87 | #{to} 88 | }) 89 | end 90 | 91 | def self.crop_instructions(from, to, dimensions, opts = {}) 92 | if crop_for_youtube?(opts) 93 | dimensions = dimensions.split("x", 2)[0] 94 | end 95 | 96 | ensure_safe_paths!(from, to) 97 | 98 | from = prepend_decoder!(from, to, opts) 99 | to = prepend_decoder!(to, to, opts) 100 | 101 | instructions = ['convert', "#{from}[0]"] 102 | 103 | if crop_for_youtube?(opts) 104 | instructions.concat(border_elimination_instructions) 105 | end 106 | 107 | instructions.concat(%W{ 108 | -auto-orient 109 | -gravity north 110 | -background transparent 111 | -#{thumbnail_or_resize} #{dimensions}^ 112 | -crop #{dimensions}+0+0 113 | -unsharp 2x0.5+0.7+0 114 | -interlace none 115 | -profile #{File.join(Rails.root, 'vendor', 'data', 'RT_sRGB.icm')} 116 | }) 117 | 118 | if opts[:quality] 119 | instructions << "-quality" << opts[:quality].to_s 120 | end 121 | 122 | instructions << to 123 | end 124 | 125 | def self.downsize_instructions(from, to, dimensions, opts = {}) 126 | ensure_safe_paths!(from, to) 127 | 128 | from = prepend_decoder!(from, to, opts) 129 | to = prepend_decoder!(to, to, opts) 130 | 131 | instructions = ['convert', "#{from}[0]"] 132 | 133 | instructions.concat(%W{ 134 | -auto-orient 135 | -gravity center 136 | }) 137 | 138 | unless crop_for_youtube?(opts) 139 | instructions.concat(%W{ 140 | -background transparent 141 | }) 142 | end 143 | 144 | instructions.concat(%W{ 145 | -interlace none 146 | -resize #{dimensions} 147 | -profile #{File.join(Rails.root, 'vendor', 'data', 'RT_sRGB.icm')} 148 | }) 149 | 150 | if SiteSetting.topic_list_enable_thumbnail_black_border_elimination && is_youtube_four_by_three 151 | instructions.concat(border_elimination_instructions) 152 | end 153 | 154 | instructions.concat(%W{ 155 | #{to} 156 | }) 157 | end 158 | 159 | def crop_for_youtube?(opts) 160 | is_youtube_four_by_three = false 161 | if opts[:upload_id] 162 | is_youtube_four_by_three = Upload.find(opts[:upload_id]).original_filename == "hqdefault.jpg" 163 | end 164 | SiteSetting.topic_list_enable_thumbnail_black_border_elimination && 165 | is_youtube_four_by_three 166 | end 167 | 168 | end 169 | end 170 | -------------------------------------------------------------------------------- /lib/topic_previews/post_guardian_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require_dependency 'guardian' 3 | require_dependency 'guardian/post_guardian' 4 | 5 | module TopicPreviews 6 | module PostGuardianExtension 7 | # Passing existing loaded topic record avoids an N+1. 8 | def previewed_post_can_act?(post, topic, action_key, opts = {}) 9 | taken = opts[:taken_actions].try(:keys).to_a 10 | is_flag = PostActionType.is_flag?(action_key) 11 | already_taken_this_action = taken.any? && taken.include?(PostActionType.types[action_key]) 12 | already_did_flagging = taken.any? && (taken & PostActionType.flag_types.values).any? 13 | 14 | result = if authenticated? && post && !@user.anonymous? 15 | 16 | return false if action_key == :notify_moderators && !SiteSetting.enable_private_messages 17 | 18 | # we allow flagging for trust level 1 and higher 19 | # always allowed for private messages 20 | (is_flag && not(already_did_flagging) && (@user.has_trust_level?(TrustLevel[1]) || topic.private_message?)) || 21 | 22 | # not a flagging action, and haven't done it already 23 | not(is_flag || already_taken_this_action) && 24 | 25 | # nothing except flagging on archived topics 26 | not(topic.try(:archived?)) && 27 | 28 | # nothing except flagging on deleted posts 29 | not(post.trashed?) && 30 | 31 | # don't like your own stuff 32 | not(action_key == :like && is_my_own?(post)) && 33 | 34 | # new users can't notify_user because they are not allowed to send private messages 35 | not(action_key == :notify_user && !@user.has_trust_level?(SiteSetting.min_trust_to_send_messages)) && 36 | 37 | # non-staff can't send an official warning 38 | not(action_key == :notify_user && !is_staff? && opts[:is_warning].present? && opts[:is_warning] == 'true') && 39 | 40 | # can't send private messages if they're disabled globally 41 | not(action_key == :notify_user && !SiteSetting.enable_private_messages) && 42 | 43 | # no voting more than once on single vote topics 44 | not(action_key == :vote && opts[:voted_in_topic] && topic.has_meta_data_boolean?(:single_vote)) 45 | end 46 | 47 | !!result 48 | end 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /lib/topic_previews/search_topic_list_item_serializer_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module TopicPreviews 3 | module SearchTopicListItemSerializerExtension 4 | def include_thumbnails? 5 | true 6 | end 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /lib/topic_previews/suggested_topic_serializer_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TopicPreviews 4 | module SuggestedTopicSerializerExtension 5 | extend ActiveSupport::Concern 6 | 7 | include TopicListItemEditsMixin 8 | 9 | included do 10 | 11 | attributes :sidecar_installed, 12 | :dominant_colour, 13 | :include_dominant_colour?, 14 | :topic_post_id, 15 | :topic_post_liked, 16 | :topic_post_like_count, 17 | :topic_post_can_like, 18 | :topic_post_can_unlike, 19 | :topic_post_bookmarked, 20 | :topic_post_is_current_users, 21 | :topic_post_number, 22 | :topic_post_user 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /lib/topic_previews/thumbnail_selection_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module ::TopicPreviews::ThumbnailSelectionHelper 3 | 4 | def self.extract_images_for_post (doc) 5 | # all images with a src attribute 6 | doc.css("img[src]") - 7 | # minus emojis 8 | doc.css("img.emoji") - 9 | # minus images inside quotes 10 | doc.css(".quote img") - 11 | # minus onebox site icons 12 | doc.css("img.site-icon") - 13 | # minus onebox avatars 14 | doc.css("img.onebox-avatar") #- 15 | # minus small onebox images (large images are .aspect-image-full-size) 16 | # @doc.css(".onebox .aspect-image img") 17 | end 18 | 19 | def self.get_thumbnails_from_topic(topic) 20 | 21 | thumbnails = [] 22 | 23 | posts = topic.posts 24 | 25 | posts.map do |post| 26 | post_id = post.id.to_i 27 | 28 | @post = Post.find(post_id) 29 | 30 | doc = Nokogiri::HTML5::fragment(@post.cooked) 31 | 32 | eligible_image_fragments = extract_images_for_post(doc) 33 | 34 | @post.each_upload_url(fragments: eligible_image_fragments) do |src, path, sha1| 35 | upload = Upload.find_by(sha1: sha1) 36 | if upload 37 | thumbnails << { image_url: upload.url, post_id: post_id, upload_id: upload.id } 38 | end 39 | end 40 | end 41 | thumbnails 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /lib/topic_previews/topic_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module TopicPreviews 3 | module TopicExtension 4 | 5 | attr_accessor :previewed_post 6 | attr_accessor :previewed_post_actions 7 | attr_accessor :previewed_post_bookmark 8 | 9 | def dominant_color 10 | hex = Upload.find_by(id: Topic.find_by(id: self.id)&.image_upload_id)&.dominant_color 11 | if !hex.blank? 12 | colour_array = hex.scan(/../).map { |colour| colour.to_i(16) } 13 | { red: colour_array[0], green: colour_array[1], blue: colour_array[2] } 14 | else 15 | {} 16 | end 17 | end 18 | 19 | def generate_thumbnails!(extra_sizes: []) 20 | return nil unless SiteSetting.create_thumbnails 21 | return nil unless original = image_upload 22 | return nil if original.filesize >= SiteSetting.max_image_size_kb.kilobytes 23 | return nil unless original.width && original.height 24 | extra_sizes = [] unless extra_sizes.kind_of?(Array) 25 | 26 | if SiteSetting.topic_list_enable_thumbnail_recreation_on_post_rebuild 27 | TopicThumbnail.where(upload_id: original.id).each do |tn| 28 | optimized_image_id = tn.optimized_image_id 29 | tn.destroy 30 | OptimizedImage.find(optimized_image_id).destroy if !optimized_image_id.blank? 31 | end 32 | end 33 | 34 | (Topic.thumbnail_sizes + extra_sizes).each do |dim| 35 | TopicThumbnail.find_or_create_for!(original, max_width: dim[0], max_height: dim[1]) 36 | end 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /lib/topic_previews/topic_list_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TopicPreviews 4 | module TopicListExtension 5 | # attr_accessor :featured_topics 6 | # include ListHelper 7 | 8 | def load_topics 9 | @topics = super 10 | 11 | if SiteSetting.topic_list_previews_enabled 12 | @topics = load_previewed_posts(@topics, @current_user) 13 | end 14 | 15 | @topics 16 | end 17 | 18 | def load_previewed_posts(topics, user = nil) 19 | # TODO: better to keep track of previewed posts' id so they can be loaded at once 20 | posts_map = {} 21 | post_actions_map = {} 22 | accepted_answer_post_ids = [] 23 | qa_topic_ids = [] 24 | normal_topic_ids = [] 25 | previewed_post_ids = [] 26 | 27 | topics.each do |topic| 28 | if post_id = topic.custom_fields["accepted_answer_post_id"]&.to_i 29 | accepted_answer_post_ids << post_id 30 | elsif ::Topic.respond_to?(:qa_enabled) && ::Topic.qa_enabled(topic) 31 | qa_topic_ids << topic.id 32 | else 33 | normal_topic_ids << topic.id 34 | end 35 | end 36 | 37 | Post.where("id IN (?)", accepted_answer_post_ids).each do |post| 38 | posts_map[post.topic_id] = post 39 | previewed_post_ids << post.id 40 | end 41 | 42 | Post.where("post_number <> 1 AND sort_order = 1 AND topic_id in (?)", qa_topic_ids).each do |post| 43 | posts_map[post.topic_id] = post 44 | previewed_post_ids << post.id 45 | end 46 | 47 | Post.where("post_number = 1 AND topic_id IN (?)", normal_topic_ids).each do |post| 48 | posts_map[post.topic_id] = post 49 | previewed_post_ids << post.id 50 | end 51 | 52 | if user 53 | PostAction.where("post_id IN (?) AND user_id = ?", previewed_post_ids, user.id).each do |post_action| 54 | (post_actions_map[post_action.post_id] ||= []) << post_action 55 | end 56 | end 57 | 58 | topics.each do |topic| 59 | topic.previewed_post = posts_map[topic.id] 60 | topic.previewed_post_actions = post_actions_map[topic.previewed_post.id] if topic.previewed_post 61 | topic.previewed_post_bookmark = Bookmark.find_by(bookmarkable_id: topic.first_post.id) 62 | end 63 | 64 | topics 65 | end 66 | end 67 | end 68 | -------------------------------------------------------------------------------- /lib/topic_previews/topic_list_item_edits_mixin.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module TopicPreviews 4 | module TopicListItemEditsMixin 5 | 6 | def sidecar_installed 7 | SiteSetting.topic_list_previews_enabled || false 8 | end 9 | 10 | def excerpt 11 | if object.previewed_post 12 | doc = Nokogiri::HTML5::fragment(object.previewed_post.cooked) 13 | doc.search('.//img').remove 14 | if !SiteSetting.topic_list_excerpt_remove_links 15 | PrettyText.excerpt(doc.to_html, SiteSetting.topic_list_excerpt_length, keep_emoji_images: true) 16 | else 17 | ::TopicPreviews::TopicListSerializerLib.remove_links(PrettyText.excerpt(doc.to_html, SiteSetting.topic_list_excerpt_length, keep_emoji_images: true)) 18 | end 19 | else 20 | object.excerpt 21 | end 22 | end 23 | 24 | def include_topic_post_id? 25 | object.previewed_post.present? && SiteSetting.topic_list_previews_enabled 26 | end 27 | 28 | def topic_post_id 29 | object.previewed_post&.id 30 | end 31 | 32 | def topic_post_number 33 | object.previewed_post&.post_number 34 | end 35 | 36 | def topic_post_user 37 | if object.previewed_post 38 | @topic_post_user ||= BasicUserSerializer.new(object.previewed_post.user, scope: scope, root: false).as_json 39 | else 40 | nil 41 | end 42 | end 43 | 44 | def include_topic_post_user? 45 | topic_post_user.present? 46 | end 47 | 48 | def topic_post_actions 49 | object.previewed_post_actions || [] 50 | end 51 | 52 | def topic_like_action 53 | topic_post_actions.select { |a| a.post_action_type_id == PostActionType.types[:like] } 54 | end 55 | 56 | def topic_post_bookmarked 57 | object.previewed_post_bookmark.present? # || false 58 | end 59 | 60 | alias :include_topic_post_bookmarked? :include_topic_post_id? 61 | 62 | def topic_post_liked 63 | topic_like_action.any? 64 | end 65 | alias :include_topic_post_liked? :include_topic_post_id? 66 | 67 | def topic_post_like_count 68 | object.previewed_post&.like_count 69 | end 70 | 71 | def include_topic_post_like_count? 72 | object.previewed_post&.id && topic_post_like_count > 0 && SiteSetting.topic_list_previews_enabled 73 | end 74 | 75 | def topic_post_can_like 76 | return false if !scope.current_user || topic_post_is_current_users 77 | scope.previewed_post_can_act?(object.previewed_post, object, PostActionType.types[:like], taken_actions: topic_post_actions) 78 | end 79 | alias :include_topic_post_can_like? :include_topic_post_id? 80 | 81 | def topic_post_is_current_users 82 | scope.current_user && (object.previewed_post&.user_id == scope.current_user.id) 83 | end 84 | alias :include_topic_post_is_current_users? :include_topic_post_id? 85 | 86 | def topic_post_can_unlike 87 | return false if !scope.current_user 88 | action = topic_like_action[0] 89 | !!(action && (action.user_id == scope.current_user.id) && (action.created_at > SiteSetting.post_undo_action_window_mins.minutes.ago)) 90 | end 91 | 92 | def include_dominant_colour? 93 | SiteSetting.topic_list_enable_thumbnail_colour_determination 94 | end 95 | 96 | def dominant_colour 97 | object.dominant_color || object.custom_fields['dominant_colour'] 98 | end 99 | end 100 | end 101 | -------------------------------------------------------------------------------- /lib/topic_previews/topic_list_item_serializer_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module TopicPreviews 3 | module TopicListItemSerializerExtension 4 | extend ActiveSupport::Concern 5 | 6 | include TopicListItemEditsMixin 7 | 8 | included do 9 | 10 | attributes :sidecar_installed, 11 | :dominant_colour, 12 | :dominant_color, 13 | :include_dominant_colour?, 14 | :topic_post_id, 15 | :topic_post_liked, 16 | :topic_post_like_count, 17 | :topic_post_can_like, 18 | :topic_post_can_unlike, 19 | :topic_post_bookmarked, 20 | :topic_post_is_current_users, 21 | :topic_post_number, 22 | :topic_post_user 23 | 24 | alias :include_topic_post_can_unlike? :include_topic_post_id? 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /lib/topic_previews/topic_list_serializer_lib.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | require 'nokogiri' 3 | 4 | module TopicPreviews 5 | module TopicListSerializerLib 6 | 7 | def self.remove_links (excerpt) 8 | doc = Nokogiri::HTML excerpt 9 | node = doc.at("a") 10 | node.replace(node.text) if node 11 | if SiteSetting.topic_list_keep_link_text_content 12 | doc.to_str.strip 13 | else 14 | doc.to_str.gsub(/#{URI::regexp}/, '').gsub(/\s+/, ' ').strip 15 | end 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /lib/topic_previews/topic_view_serializer_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module TopicPreviews 3 | module TopicViewSerializerExtension 4 | extend ActiveSupport::Concern 5 | 6 | included do 7 | attributes :user_chosen_thumbnail_url, 8 | :sidecar_installed 9 | end 10 | 11 | def user_chosen_thumbnail_url 12 | object.topic.custom_fields['user_chosen_thumbnail_url'] 13 | end 14 | 15 | def sidecar_installed 16 | true 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /lib/topic_previews/upload_extension.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module TopicPreviews 3 | module UploadExtension 4 | 5 | DOMINANT_COLOR_COMMAND_TIMEOUT_SECONDS = 5 6 | 7 | def calculate_dominant_color!(local_path = nil) 8 | color = nil 9 | 10 | color = "" if !FileHelper.is_supported_image?("image.#{extension}") || extension == "svg" 11 | 12 | if color.nil? 13 | local_path ||= 14 | if local? 15 | Discourse.store.path_for(self) 16 | else 17 | Discourse.store.download_safe(self)&.path 18 | end 19 | 20 | if local_path.nil? 21 | # Download failed. Could be too large to download, or file could be missing in s3 22 | color = "" 23 | end 24 | 25 | color ||= 26 | begin 27 | data = 28 | Discourse::Utils.execute_command( 29 | "nice", 30 | "-n", 31 | "10", 32 | "convert", 33 | local_path, 34 | "-depth", 35 | "8", 36 | "-colors", 37 | SiteSetting.topic_list_dominant_color_quantisation.to_s, 38 | "-define", 39 | "histogram:unique-colors=true", 40 | "-format", 41 | "%c", 42 | "histogram:info:", 43 | timeout: DOMINANT_COLOR_COMMAND_TIMEOUT_SECONDS, 44 | ) 45 | 46 | # Output format: 47 | # 1: (110.873,116.226,93.8821) #6F745E srgb(43.4798%,45.5789%,36.8165%) 48 | 49 | color = data[/#([0-9A-F]{6})/, 1] 50 | 51 | raise "Calculated dominant color but unable to parse output:\n#{data}" if color.nil? 52 | 53 | color 54 | rescue Discourse::Utils::CommandError => e 55 | # Timeout or unable to parse image 56 | # This can happen due to bad user input - ignore and save 57 | # an empty string to prevent re-evaluation 58 | "" 59 | end 60 | end 61 | 62 | if persisted? 63 | self.update_column(:dominant_color, color) 64 | else 65 | self.dominant_color = color 66 | end 67 | end 68 | end 69 | end 70 | -------------------------------------------------------------------------------- /plugin.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | # name: discourse-topic-previews-sidecar 3 | # about: Sidecar Plugin to support Topic List Preview Theme Component 4 | # version: 6.0.1 5 | # authors: Robert Barrow, Angus McLeod 6 | # url: https://github.com/paviliondev/discourse-topic-previews 7 | 8 | enabled_site_setting :topic_list_previews_enabled 9 | 10 | DiscoursePluginRegistry.serialized_current_user_fields << "tlp_user_prefs_prefer_low_res_thumbnails" 11 | 12 | module ::TopicPreviews 13 | PLUGIN_NAME = "topic-previews".freeze 14 | end 15 | 16 | require_relative "lib/topic_previews/engine" 17 | 18 | after_initialize do 19 | reloadable_patch do 20 | Upload.prepend(TopicPreviews::UploadExtension) 21 | Topic.prepend(TopicPreviews::TopicExtension) 22 | TopicViewSerializer.include(TopicPreviews::TopicViewSerializerExtension) 23 | ListHelper.prepend(TopicPreviews::ListHelperExtension) 24 | TopicList.prepend(TopicPreviews::TopicListExtension) 25 | TopicListItemSerializer.include(TopicPreviews::TopicListItemSerializerExtension) 26 | OptimizedImage.singleton_class.prepend(TopicPreviews::OptimizedImageExtension) 27 | CookedPostProcessor.prepend(TopicPreviews::CookedPostProcessorExtension) 28 | PostGuardian.prepend(TopicPreviews::PostGuardianExtension) 29 | SuggestedTopicSerializer.include(TopicPreviews::SuggestedTopicSerializerExtension) 30 | if SiteSetting.topic_list_search_previews_enabled 31 | SearchTopicListItemSerializer.prepend(TopicPreviews::SearchTopicListItemSerializerExtension) 32 | end 33 | end 34 | 35 | User.register_custom_field_type('tlp_user_prefs_prefer_low_res_thumbnails', :boolean) 36 | Topic.register_custom_field_type('user_chosen_thumbnail_url', :string) 37 | Topic.register_custom_field_type('dominant_colour', :json) 38 | register_editable_user_custom_field :tlp_user_prefs_prefer_low_res_thumbnails 39 | TopicList.preloaded_custom_fields << "accepted_answer_post_id" if TopicList.respond_to? :preloaded_custom_fields 40 | TopicList.preloaded_custom_fields << "dominant_colour" if TopicList.respond_to? :preloaded_custom_fields 41 | TopicView.preloaded_custom_fields << "accepted_answer_post_id" if TopicView.respond_to? :preloaded_custom_fields 42 | TopicView.preloaded_custom_fields << "dominant_colour" if TopicView.respond_to? :preloaded_custom_fields 43 | Topic.preloaded_custom_fields << "accepted_answer_post_id" if Topic.respond_to? :preloaded_custom_fields 44 | Topic.preloaded_custom_fields << "dominant_colour" if Topic.respond_to? :preloaded_custom_fields 45 | # DiscourseEvent.on(:accepted_solution) do |post| 46 | # if post.image_url && SiteSetting.topic_list_previews_enabled 47 | # ListHelper.create_topic_thumbnails(post, post.image_url)[:id] 48 | # end 49 | # end 50 | 51 | TopicList.preloaded_custom_fields << "user_chosen_thumbnail_url" if TopicList.respond_to? :preloaded_custom_fields 52 | PostRevisor.track_topic_field("user_chosen_thumbnail_url".to_sym) do |tc, tf| 53 | tc.record_change("user_chosen_thumbnail_url", tc.topic.custom_fields["user_thumbnail_choice"], tf) 54 | tc.topic.custom_fields["user_chosen_thumbnail_url"] = tf 55 | end 56 | PostRevisor.track_topic_field("image_upload_id".to_sym) do |tc, tf| 57 | tc.record_change("image_upload_id", tc.topic.image_upload_id, tf) 58 | tc.topic.image_upload_id = tf 59 | end 60 | 61 | DiscourseEvent.trigger(:topic_previews_ready) 62 | end 63 | --------------------------------------------------------------------------------