-
Notifications
You must be signed in to change notification settings - Fork 569
Expand file tree
/
Copy pathDotcomRenderingUtils.scala
More file actions
382 lines (335 loc) · 13.7 KB
/
Copy pathDotcomRenderingUtils.scala
File metadata and controls
382 lines (335 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package model.dotcomrendering
import ab.ABTests
import com.github.nscala_time.time.Imports.DateTime
import com.gu.contentapi.client.model.v1.{Block => APIBlock, BlockElement => ClientBlockElement, Blocks => APIBlocks}
import com.gu.contentapi.client.utils.format.{ImmersiveDisplay, LiveBlogDesign}
import com.gu.contentapi.client.utils.{AdvertisementFeature, DesignType}
import common.{Edition, Environment, LinkTo}
import conf.switches.Switches
import conf.{Configuration, Static}
import model.content.Atom
import model.dotcomrendering.pageElements.{PageElement, TextCleaner}
import model.meta.BlocksOn
import model.pressed.{PressedContent, SpecialReport}
import model.{
ArticleDateTimes,
CanonicalLiveBlog,
ContentFormat,
ContentPage,
ContentType,
GUDateTimeFormatNew,
LiveBlogPage,
Pillar,
}
import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import org.jsoup.Jsoup
import play.api.libs.json._
import play.api.mvc.RequestHeader
import views.support.AffiliateLinksCleaner
import java.net.URLEncoder
import model.Tags
sealed trait DotcomRenderingMatchType
object DotcomRenderingMatchType {
implicit val matchTypesWrites: Writes[DotcomRenderingMatchType] = (matchType: DotcomRenderingMatchType) =>
JsString(matchType.toString)
}
case object CricketMatchType extends DotcomRenderingMatchType
case object FootballMatchType extends DotcomRenderingMatchType
case class DotcomRenderingMatchData(
matchUrl: String,
matchHeaderUrl: Option[String],
matchStatsUrl: Option[String],
matchType: DotcomRenderingMatchType,
)
sealed trait MatchEndpoint {
val urlSegment: String
}
case object MatchHeaderEndpoint extends MatchEndpoint { val urlSegment = "match-header" }
case object MatchStatsEndpoint extends MatchEndpoint { val urlSegment = "match-stats" }
case object MatchStatsSummaryEndpoint extends MatchEndpoint { val urlSegment = "match-stats-summary" }
trait DCARUrlHelper {
def getPageUrl(path: String)(implicit request: RequestHeader): String = {
if (Environment.app == "preview") s"${Configuration.site.viewerProxyBaseUrl}$path" else LinkTo(path)
}
def getAjaxHost: String = {
if (Environment.app == "preview") s"${Configuration.site.viewerProxyBaseUrl}" else Configuration.ajax.url
}
}
object DotcomRenderingUtils extends DCARUrlHelper {
def makeMatchData(articlePage: ContentPage, pageType: PageType): Option[DotcomRenderingMatchData] = {
makeFootballMatch(articlePage, pageType).orElse(makeCricketMatch(articlePage.item))
}
def hasExactlyTwoTeams(tags: Tags): Boolean = tags.tags.count(tag => {
tag.id.endsWith("-cricket-team") || tag.id.endsWith("cricketteam")
}) == 2
def makeCricketMatch(item: ContentType): Option[DotcomRenderingMatchData] = {
val date = item.content.cricketMatchDate
val team = item.content.cricketTeam
(date, team, hasExactlyTwoTeams(item.content.tags)) match {
case (Some(date), Some(team), true) =>
Some(
DotcomRenderingMatchData(
matchUrl = s"${getAjaxHost}/sport/cricket/match-scoreboard/$date/$team.json",
matchHeaderUrl = Some(s"${getAjaxHost}/sport/cricket/match-header/$date/$team.json"),
matchStatsUrl = Some(s"${getAjaxHost}/sport/cricket/match-stats-summary/$date/$team.json"),
matchType = CricketMatchType,
),
)
case _ => None
}
}
def getMatchNavUrl(host: String, date: LocalDate, team1: String, team2: String, pageId: String): String = {
val formatter = DateTimeFormat.forPattern("yyyy/MM/dd")
val datePath = formatter.print(date)
val encodedPageId = URLEncoder.encode(pageId, "UTF-8")
s"$host/football/api/match-nav/$datePath/$team1/$team2.json?dcr=true&page=$encodedPageId"
}
def getMatchUrl(
host: String,
date: LocalDate,
team1: String,
team2: String,
endpoint: MatchEndpoint,
): String = {
val formatter = DateTimeFormat.forPattern("yyyy/MM/dd")
val datePath = formatter.print(date)
s"$host/football/api/${endpoint.urlSegment}/$datePath/$team1/$team2.json"
}
def makeFootballMatch(articlePage: ContentPage, pageType: PageType): Option[DotcomRenderingMatchData] = {
def extraction1(references: JsValue): Option[IndexedSeq[JsValue]] = {
val sequence = references match {
case JsArray(elements) => Some(elements)
case _ => None
}
sequence
}.map(_.toIndexedSeq)
def entryToDataPair(entry: JsValue): Option[(String, String)] = {
/*
Examples:
{
"esa-football-team": "/\" + \"football/\" + \"team/\" + \"331"
}
{
"pa-football-competition": "500"
}
{
"pa-football-team": "26305"
}
*/
val obj = entry.as[JsObject]
obj.fields.map(pair => (pair._1, pair._2.as[String])).headOption
}
val optionalUrl = for {
references <- articlePage.getJavascriptConfig.get("references")
entries1 <- extraction1(references)
entries2 =
entries1
.map(entryToDataPair)
.filter(_.isDefined)
.map(_.get) // .get is fundamentally dangerous but fine in this case because we filtered the Nones out.
.filter(_._1 == "pa-football-team")
} yield {
entries2.toList match {
case e1 :: e2 :: _ =>
val statsUrlSegment: MatchEndpoint =
if (pageType.isLiveblog) MatchStatsSummaryEndpoint else MatchStatsEndpoint
val localDate = articlePage.item.trail.webPublicationDate.toLocalDate
val navUrl = getMatchNavUrl(getAjaxHost, localDate, e1._2, e2._2, articlePage.metadata.id)
val headerUrl = getMatchUrl(getAjaxHost, localDate, e1._2, e2._2, MatchHeaderEndpoint)
val statsUrl = getMatchUrl(getAjaxHost, localDate, e1._2, e2._2, statsUrlSegment)
Some(
DotcomRenderingMatchData(
matchUrl = navUrl,
matchHeaderUrl = Some(headerUrl),
matchStatsUrl = Some(statsUrl),
matchType = FootballMatchType,
),
)
case _ => None
}
}
optionalUrl.flatten
}
def assetURL(bundlePath: String): String = {
// This function exists because for some reasons `Static` behaves differently in { PROD and CODE } versus LOCAL
if (Configuration.environment.isProd || Configuration.environment.isCode) {
Static(bundlePath)
} else {
s"${Configuration.site.host}${Static(bundlePath)}"
}
}
// note: this is duplicated in the onward service (DotcomponentsOnwardsModels - if duplicating again consider moving to common! :()
def findPillar(pillar: Option[Pillar], designType: Option[DesignType]): String = {
pillar
.map { pillar =>
if (designType.contains(AdvertisementFeature)) "labs"
else if (pillar.toString.toLowerCase == "arts") "culture"
else pillar.toString.toLowerCase()
}
.getOrElse("news")
}
def getLatest60Blocks(blocks: APIBlocks): Option[List[APIBlock]] = {
blocks.requestedBodyBlocks.flatMap(_.get(CanonicalLiveBlog.firstPage).map(_.toList))
}
def blocksForLiveblogPage(
pageBlocks: BlocksOn[LiveBlogPage],
): Seq[APIBlock] = {
val blocks = pageBlocks.blocks
val allBlocks = getLatest60Blocks(blocks).getOrElse(List.empty)
// For the newest page, the latest 60 blocks are requested, but for other page,
// all of the blocks have been requested and returned in the blocks.body bit
// of the response so we use those
val relevantBlocks = if (allBlocks.isEmpty) blocks.body.getOrElse(Nil) else allBlocks
val ids = pageBlocks.page.currentPage.currentPage.blocks.map(_.id).toSet
relevantBlocks.filter(block => ids(block.id))
}.toSeq
def stringContainsAffiliateableLinks(textString: String): Boolean = {
AffiliateLinksCleaner.stringContainsAffiliateableLinks(textString)
}
def blockElementsToPageElements(
capiElems: Seq[ClientBlockElement],
request: RequestHeader,
article: ContentType,
affiliateLinks: Boolean,
isMainBlock: Boolean,
campaigns: Option[JsValue],
calloutsUrl: Option[String],
): List[PageElement] = {
val atoms: Iterable[Atom] = article.atoms.map(_.all).getOrElse(Seq())
val edition = Edition(request)
val elems = capiElems.toList
.flatMap(el =>
PageElement.make(
element = el,
addAffiliateLinks = affiliateLinks,
pageUrl = request.uri,
atoms = atoms,
isMainBlock,
article.content.metadata.format.exists(_.display == ImmersiveDisplay),
campaigns,
calloutsUrl,
article.elements.thumbnail,
edition,
article.trail.webPublicationDate,
article.content.isGallery,
article.content.isUSProductionOffice,
abTests = ABTests.getParticipations(request),
),
)
.filter(PageElement.isSupported)
val withTagLinks =
if (article.content.isPaidContent) elems
else TextCleaner.tagLinks(elems, article.content.tags, article.content.showInRelated, edition)
withTagLinks
}
def isSpecialReport(page: ContentPage): Boolean =
page.item.content.cardStyle == SpecialReport
def secondaryDateString(content: ContentType, request: RequestHeader): String = {
def format(dt: DateTime, req: RequestHeader): String = GUDateTimeFormatNew.formatDateTimeForDisplay(dt, req)
val firstPublicationDate = content.fields.firstPublicationDate
val webPublicationDate = content.trail.webPublicationDate
val isModified = content.content.hasBeenModified && (!firstPublicationDate.contains(webPublicationDate))
if (isModified) {
"First published on " + format(firstPublicationDate.getOrElse(webPublicationDate), request)
} else {
"Last modified on " + format(content.fields.lastModified, request)
}
}
def withoutNull(json: JsValue): JsValue = {
json match {
case JsObject(fields) => JsObject(fields.filterNot { case (_, value) => value == JsNull })
case other => other
}
}
def withoutDeepNull(json: JsValue): JsValue = {
json match {
case JsObject(fields) =>
JsObject(fields.collect {
case (key, value) if value != JsNull => key -> withoutDeepNull(value)
})
case JsArray(values) =>
JsArray(values.collect {
case value if value != JsNull => withoutDeepNull(value)
})
case other => other
}
}
def shouldAddAffiliateLinks(content: ContentType): Boolean = {
if (content.content.isGallery) {
// For galleries, the disclaimer is only inserted in the header so we don't need
// a check for paragraphs as in other articles
AffiliateLinksCleaner.shouldAddAffiliateLinks(
switchedOn = Switches.AffiliateLinks.isSwitchedOn,
showAffiliateLinks = content.content.fields.showAffiliateLinks,
alwaysOffTags = Configuration.affiliateLinks.alwaysOffTags,
tagPaths = content.content.tags.tags.map(_.id),
)
} else {
val contentHtml = Jsoup.parse(content.fields.body)
val bodyElements = contentHtml.select("body").first().children()
/** On smaller devices, the disclaimer is inserted before paragraph 2 of the article body and floats left. This
* logic ensures there are two clear paragraphs of text at the top of the article. We don't support inserting the
* disclaimer next to other element types. It also ensures the second paragraph is long enough to accommodate the
* disclaimer appearing alongside it.
*/
if (bodyElements.size >= 2) {
val firstEl = bodyElements.get(0)
val secondEl = bodyElements.get(1)
if (firstEl.tagName == "p" && secondEl.tagName == "p" && secondEl.text().length >= 150) {
AffiliateLinksCleaner.shouldAddAffiliateLinks(
switchedOn = Switches.AffiliateLinks.isSwitchedOn,
showAffiliateLinks = content.content.fields.showAffiliateLinks,
alwaysOffTags = Configuration.affiliateLinks.alwaysOffTags,
tagPaths = content.content.tags.tags.map(_.id),
)
} else false
} else false
}
}
def contentDateTimes(content: ContentType): ArticleDateTimes = {
ArticleDateTimes(
webPublicationDate = content.trail.webPublicationDate,
firstPublicationDate = content.fields.firstPublicationDate,
hasBeenModified = content.content.hasBeenModified,
lastModificationDate = content.fields.lastModified,
)
}
def getModifiedContent(content: ContentType, forceLive: Boolean): ContentFormat = {
val originalFormat = content.metadata.format.getOrElse(ContentFormat.defaultContentFormat)
if (forceLive) {
originalFormat.copy(design = LiveBlogDesign)
} else {
originalFormat
}
}
def getMostRecentBlockId(blocks: APIBlocks): Option[String] = {
blocks.requestedBodyBlocks
.flatMap(_.get(CanonicalLiveBlog.firstPage))
.getOrElse(blocks.body.getOrElse(Seq.empty))
.headOption
.map(block => s"block-${block.id}")
}
def orderBlocks(blocks: Seq[APIBlock]): Seq[APIBlock] =
blocks.sortBy(block => block.firstPublishedDate.orElse(block.createdDate).map(_.dateTime)).reverse
def ensureSummaryTitle(block: APIBlock): APIBlock = {
if (block.attributes.summary.contains(true) && block.title.isEmpty) {
block.copy(title = Some("Summary"))
} else block
}
def getStoryPackage(
faciaItems: Seq[PressedContent],
requestHeader: RequestHeader,
): Option[OnwardCollectionResponse] = {
faciaItems match {
case Nil => None
case _ =>
Some(
OnwardCollectionResponse(
heading = "More on this story",
trails = faciaItems.map(faciaItem => Trail.pressedContentToTrail(faciaItem)(requestHeader)).take(10),
),
)
}
}
}