#? stdtmpl(subsChar = '$', metaChar = '#')
## SPDX-License-Identifier: AGPL-3.0-only
#import strutils, xmltree, strformat, options, unicode, algorithm
#import ../types, ../utils, ../formatters, ../prefs
#
#proc getTitle(tweet: Tweet; retweet: string): string =
#if tweet.pinned: result = "Pinned: "
#elif retweet.len > 0: result = &"RT by @{retweet}: "
#elif tweet.reply.len > 0: result = &"R to @{tweet.reply[0]}: "
#end if
#var text = stripHtml(tweet.text)
##if unicode.runeLen(text) > 32:
##  text = unicode.runeSubStr(text, 0, 32) & "..."
##end if
#result &= xmltree.escape(text)
#if result.len > 0: return
#end if
#if tweet.photos.len > 0:
#  result &= "Image"
#elif tweet.video.isSome:
#  result &= "Video"
#elif tweet.gif.isSome:
#  result &= "Gif"
#end if
#end proc
#
#proc getDescription(desc: string; cfg: Config): string =
Twitter feed for: ${desc}. Generated by ${cfg.hostname}
#end proc
#
## Copied from views/tweet.nim
#proc isPlaybackEnabled(prefs: Prefs; playbackType: VideoType): bool =
#  case playbackType
#  of mp4: return prefs.mp4Playback
#  of m3u8, vmap: return prefs.hlsPlayback
#  end case
#end proc
#
#proc hasMp4Url(video: Video): bool =
#  video.variants.anyIt(it.contentType == mp4)
#end proc
#
#proc getVideoDisabledText(playbackType: VideoType): string =
#  case playbackType
#  of mp4:
     mp4 playback disabled in preferences
#  of m3u8, vmap:
     hls playback disabled in preferences
#  end case
#end proc
#
#proc getVideoUnavailableText(video: Video): string =
#  case video.reason
#  of "dmcaed":
     This media has been disabled in response to a report by the copyright owner
#  else:
     This media is unavailable
#  end case
#end proc
#
#proc renderRssTweet(tweet: Tweet; cfg: Config; prefs: Prefs): string =
#let tweet = tweet.retweet.get(tweet)
#let urlPrefix = getUrlPrefix(cfg)
#let text = replaceUrls(tweet.text, defaultPrefs, absolute=urlPrefix)
<p>${text.replace("\n", "<br>\n")}</p>
#if tweet.quote.isSome and get(tweet.quote).available:
#  let quoteLink = getLink(get(tweet.quote))
<p><a href="${urlPrefix}${quoteLink}">${cfg.hostname}${quoteLink}</a></p>
#end if
#if tweet.photos.len > 0:
#  for photo in tweet.photos:
<img src="${urlPrefix}${getPicUrl(photo)}" style="max-width:250px;" />
#  end for
#elif tweet.video.isSome:
#  let video = get(tweet.video)
#  let thumb = &"{urlPrefix}{getPicUrl(video.thumb)}"
#  let playbackType = if not prefs.proxyVideos and video.hasMp4Url: mp4
#                     else: video.playbackType
#  if not video.available:
     <img src="${thumb}" style="max-width:250px;" />
     <p>${getVideoUnavailableText(video)}</p>
#  elif not isPlaybackEnabled(prefs, playbackType):
     <img src="${thumb}" style="max-width:250px;" />
     <p>${getVideoDisabledText(playbackType)}</p>
#  else:
#    let vars = video.variants.filterIt(it.contentType == playbackType)
#    let vidUrl = vars.sortedByIt(it.resolution)[^1].url
#    let source = if prefs.proxyVideos: getVidUrl(vidUrl)
#                 else: vidUrl
#    let mutedAttribute = if prefs.muteVideos: "muted=\"\""
#                         else: ""
     <video poster="${thumb}" controls="" ${mutedAttribute} style="max-width:250px;">
       <source src="${source}" type="${playbackType}" />
     </video>
#  end if
#elif tweet.gif.isSome:
#  let thumb = &"{urlPrefix}{getPicUrl(get(tweet.gif).thumb)}"
#  let url = &"{urlPrefix}{getPicUrl(get(tweet.gif).url)}"
<video poster="${thumb}" autoplay muted loop style="max-width:250px;">
  <source src="${url}" type="video/mp4"></video>
#elif tweet.card.isSome:
#  let card = tweet.card.get()
#  if card.image.len > 0:
<img src="${urlPrefix}${getPicUrl(card.image)}" style="max-width:250px;" />
#  end if
#end if
#end proc
#
#proc renderRssTweets(tweets: seq[Tweets]; cfg: Config; prefs: Prefs; userId=""): string =
#let urlPrefix = getUrlPrefix(cfg)
#var links: seq[string]
#for thread in tweets:
#  for tweet in thread:
#    if userId.len > 0 and tweet.user.id != userId: continue
#    end if
#
#    let retweet = if tweet.retweet.isSome: tweet.user.username else: ""
#    let tweet = if retweet.len > 0: tweet.retweet.get else: tweet
#    let link = getLink(tweet)
#    if link in links: continue
#    end if
#    links.add link
      <item>
        <title>${getTitle(tweet, retweet)}</title>
        <dc:creator>@${tweet.user.username}</dc:creator>
        <description><![CDATA[${renderRssTweet(tweet, cfg, prefs).strip(chars={'\n'})}]]></description>
        <pubDate>${getRfc822Time(tweet)}</pubDate>
        <guid>${urlPrefix & link}</guid>
        <link>${urlPrefix & link}</link>
      </item>
#  end for
#end for
#end proc
#
#proc renderTimelineRss*(profile: Profile; cfg: Config; prefs: Prefs; tab, param: string; multi=false): string =
#let urlPrefix = getUrlPrefix(cfg)
#var atomLink = &"{urlPrefix}/{profile.user.username}"
#var link = &"{urlPrefix}/{profile.user.username}"
#if tab != "":
#  atomLink &= "/" & tab
#  link &= "/" & tab
#end if
#atomLink &= "/rss"
#if param != "":
#  let escParam = xmltree.escape(param)
#  atomLink &= "?" & escParam
#  link &= "?" & escParam
#end if
#result = ""
#let handle = (if multi: "" else: "@") & profile.user.username
#var title = profile.user.fullname
#if not multi: title &= " / " & handle
#end if
#title = xmltree.escape(title).sanitizeXml
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <atom:link href="${atomLink}" rel="self" type="application/rss+xml" />
    <title>${title}</title>
    <link>${link}</link>
    <description>${getDescription(handle, cfg)}</description>
    <language>en-us</language>
    <ttl>40</ttl>
    <image>
      <title>${title}</title>
      <link>${urlPrefix}/${profile.user.username}</link>
      <url>${urlPrefix}${getPicUrl(profile.user.getUserPic(style="_400x400"))}</url>
      <width>128</width>
      <height>128</height>
    </image>
#if profile.tweets.content.len > 0:
${renderRssTweets(profile.tweets.content, cfg, prefs, userId=profile.user.id)}
#end if
  </channel>
</rss>
#end proc
#
#proc renderListRss*(tweets: seq[Tweets]; list: List; cfg: Config; prefs: Prefs): string =
#let link = &"{getUrlPrefix(cfg)}/i/lists/{list.id}"
#result = ""
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <atom:link href="${link}" rel="self" type="application/rss+xml" />
    <title>${xmltree.escape(list.name)} / @${list.username}</title>
    <link>${link}</link>
    <description>${getDescription(&"{list.name} by @{list.username}", cfg)}</description>
    <language>en-us</language>
    <ttl>40</ttl>
${renderRssTweets(tweets, cfg, prefs)}
 </channel>
</rss>
#end proc
#
#proc renderSearchRss*(tweets: seq[Tweets]; name, param: string; cfg: Config; prefs: Prefs): string =
#let urlPrefix = getUrlPrefix(cfg)
#let escName = xmltree.escape(name)
#let escParam = xmltree.escape(param)
#result = ""
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <atom:link href="${urlPrefix}/search/rss?${escParam}" rel="self" type="application/rss+xml" />
    <title>Search results for "${escName}"</title>
    <link>${urlPrefix}/search?${escParam}</link>
    <description>${getDescription(&"Search \"{escName}\"", cfg)}</description>
    <language>en-us</language>
    <ttl>40</ttl>
${renderRssTweets(tweets, cfg, prefs)}
  </channel>
</rss>
#end proc
