content.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. __filename__ = "content.py"
  2. __author__ = "Bob Mottram"
  3. __license__ = "AGPL3+"
  4. __version__ = "1.0.0"
  5. __maintainer__ = "Bob Mottram"
  6. __email__ = "bob@freedombone.net"
  7. __status__ = "Production"
  8. import os
  9. import time
  10. import email.parser
  11. from shutil import copyfile
  12. from utils import loadJson
  13. def replaceEmojiFromTags(content: str,tag: [],messageType: str) -> str:
  14. """Uses the tags to replace :emoji: with html image markup
  15. """
  16. for tagItem in tag:
  17. if not tagItem.get('type'):
  18. continue
  19. if tagItem['type']!='Emoji':
  20. continue
  21. if not tagItem.get('name'):
  22. continue
  23. if not tagItem.get('icon'):
  24. continue
  25. if not tagItem['icon'].get('url'):
  26. continue
  27. if tagItem['name'] not in content:
  28. continue
  29. htmlClass='emoji'
  30. if messageType=='post header':
  31. htmlClass='emojiheader'
  32. if messageType=='profile':
  33. htmlClass='emojiprofile'
  34. emojiHtml="<img src=\""+tagItem['icon']['url']+"\" alt=\""+tagItem['name'].replace(':','')+"\" align=\"middle\" class=\""+htmlClass+"\"/>"
  35. content=content.replace(tagItem['name'],emojiHtml)
  36. return content
  37. def addMusicTag(content: str,tag: str) -> str:
  38. """If a music link is found then ensure that the post is tagged appropriately
  39. """
  40. if '#' not in tag:
  41. tag='#'+tag
  42. if tag in content:
  43. return content
  44. musicSites=['soundcloud.com','bandcamp.com']
  45. musicSiteFound=False
  46. for site in musicSites:
  47. if site+'/' in content:
  48. musicSiteFound=True
  49. break
  50. if not musicSiteFound:
  51. return content
  52. return ':music: '+content+' '+tag+' '
  53. def addWebLinks(content: str) -> str:
  54. """Adds markup for web links
  55. """
  56. if not ('https://' in content or 'http://' in content):
  57. return content
  58. maxLinkLength=40
  59. words=content.replace('\n',' --linebreak-- ').split(' ')
  60. replaceDict={}
  61. for w in words:
  62. if w.startswith('https://') or \
  63. w.startswith('http://') or \
  64. w.startswith('dat://'):
  65. if w.endswith('.') or w.endswith(';'):
  66. w=w[:-1]
  67. markup='<a href="'+w+'" rel="nofollow noopener" target="_blank">'
  68. if w.startswith('https://'):
  69. markup+='<span class="invisible">https://</span>'
  70. elif w.startswith('http://'):
  71. markup+='<span class="invisible">http://</span>'
  72. elif w.startswith('dat://'):
  73. markup+='<span class="invisible">dat://</span>'
  74. linkText=w.replace('https://','').replace('http://','').replace('dat://','')
  75. # prevent links from becoming too long
  76. if len(linkText)>maxLinkLength:
  77. markup+='<span class="ellipsis">'+linkText[:maxLinkLength]+'</span>'
  78. markup+='<span class="invisible">'+linkText[maxLinkLength:]+'</span></a>'
  79. else:
  80. markup+='<span class="ellipsis">'+linkText+'</span></a>'
  81. replaceDict[w]=markup
  82. for url,markup in replaceDict.items():
  83. content=content.replace(url,markup)
  84. content=content.replace(' --linebreak-- ','<br>')
  85. return content
  86. def validHashTag(hashtag: str) -> bool:
  87. """Returns true if the give hashtag contains valid characters
  88. """
  89. validChars = set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  90. if set(hashtag).issubset(validChars):
  91. return True
  92. return False
  93. def addHashTags(wordStr: str,httpPrefix: str,domain: str,replaceHashTags: {},postHashtags: {}) -> bool:
  94. """Detects hashtags and adds them to the replacements dict
  95. Also updates the hashtags list to be added to the post
  96. """
  97. if replaceHashTags.get(wordStr):
  98. return True
  99. hashtag=wordStr[1:]
  100. if not validHashTag(hashtag):
  101. return False
  102. hashtagUrl=httpPrefix+"://"+domain+"/tags/"+hashtag
  103. postHashtags[hashtag]= {
  104. 'href': hashtagUrl,
  105. 'name': '#'+hashtag,
  106. 'type': 'Hashtag'
  107. }
  108. replaceHashTags[wordStr]= \
  109. "<a href=\""+hashtagUrl+"\" class=\"mention hashtag\" rel=\"tag\">#<span>"+hashtag+"</span></a>"
  110. return True
  111. def loadEmojiDict(emojiDataFilename: str,emojiDict: {}) -> None:
  112. """Creates an emoji dictionary based on emoji/emoji-data.txt
  113. """
  114. if not os.path.isfile(emojiDataFilename):
  115. return
  116. with open (emojiDataFilename, "r") as fileHandler:
  117. for line in fileHandler:
  118. if len(line)<5:
  119. continue
  120. if line.startswith('#'):
  121. continue
  122. if '; Emoji' not in line:
  123. continue
  124. if ')' not in line:
  125. continue
  126. emojiUnicode=line.split(' ')[0]
  127. if len(emojiUnicode)<4:
  128. continue
  129. if '..' in emojiUnicode:
  130. emojiUnicode=emojiUnicode.split('..')[0]
  131. emojiName=line.split(')',1)[1].strip().replace('\n','').replace(' ','').replace('-','')
  132. if '..' in emojiName:
  133. emojiName=emojiName.split('..')[0]
  134. emojiDict[emojiName.lower()]=emojiUnicode
  135. def addEmoji(baseDir: str,wordStr: str,httpPrefix: str,domain: str,replaceEmoji: {},postTags: {},emojiDict: {}) -> bool:
  136. """Detects Emoji and adds them to the replacements dict
  137. Also updates the tags list to be added to the post
  138. """
  139. if not wordStr.startswith(':'):
  140. return False
  141. if not wordStr.endswith(':'):
  142. return False
  143. if len(wordStr)<3:
  144. return False
  145. if replaceEmoji.get(wordStr):
  146. return True
  147. # remove leading and trailing : characters
  148. emoji=wordStr[1:]
  149. emoji=emoji[:-1]
  150. # is the text of the emoji valid?
  151. if not validHashTag(emoji):
  152. return False
  153. if not emojiDict.get(emoji):
  154. return False
  155. emojiFilename=baseDir+'/emoji/'+emojiDict[emoji]+'.png'
  156. if not os.path.isfile(emojiFilename):
  157. return False
  158. emojiUrl=httpPrefix+"://"+domain+"/emoji/"+emojiDict[emoji]+'.png'
  159. postTags[emoji]= {
  160. 'icon': {
  161. 'mediaType': 'image/png',
  162. 'type': 'Image',
  163. 'url': emojiUrl
  164. },
  165. 'name': ':'+emoji+':',
  166. 'type': 'Emoji'
  167. }
  168. return True
  169. def addMention(wordStr: str,httpPrefix: str,following: str,replaceMentions: {},recipients: [],tags: {}) -> bool:
  170. """Detects mentions and adds them to the replacements dict and recipients list
  171. """
  172. possibleHandle=wordStr[1:]
  173. # @nick
  174. if following and '@' not in possibleHandle:
  175. # fall back to a best effort match against the following list
  176. # if no domain was specified. eg. @nick
  177. possibleNickname=possibleHandle
  178. for follow in following:
  179. if follow.startswith(possibleNickname+'@'):
  180. replaceDomain=follow.replace('\n','').split('@')[1]
  181. recipientActor=httpPrefix+"://"+replaceDomain+"/users/"+possibleNickname
  182. if recipientActor not in recipients:
  183. recipients.append(recipientActor)
  184. tags[wordStr]={
  185. 'href': recipientActor,
  186. 'name': wordStr,
  187. 'type': 'Mention'
  188. }
  189. replaceMentions[wordStr]="<span class=\"h-card\"><a href=\""+httpPrefix+"://"+replaceDomain+"/@"+possibleNickname+"\" class=\"u-url mention\">@<span>"+possibleNickname+"</span></a></span>"
  190. return True
  191. return False
  192. possibleNickname=None
  193. possibleDomain=None
  194. if '@' not in possibleHandle:
  195. return False
  196. possibleNickname=possibleHandle.split('@')[0]
  197. if not possibleNickname:
  198. return False
  199. possibleDomain=possibleHandle.split('@')[1].strip('\n')
  200. if not possibleDomain:
  201. return False
  202. if following:
  203. for follow in following:
  204. if follow.replace('\n','')!=possibleHandle:
  205. continue
  206. recipientActor=httpPrefix+"://"+possibleDomain+"/users/"+possibleNickname
  207. if recipientActor not in recipients:
  208. recipients.append(recipientActor)
  209. tags[wordStr]={
  210. 'href': recipientActor,
  211. 'name': wordStr,
  212. 'type': 'Mention'
  213. }
  214. replaceMentions[wordStr]="<span class=\"h-card\"><a href=\""+httpPrefix+"://"+possibleDomain+"/@"+possibleNickname+"\" class=\"u-url mention\">@<span>"+possibleNickname+"</span></a></span>"
  215. return True
  216. # @nick@domain
  217. if not (possibleDomain=='localhost' or '.' in possibleDomain):
  218. return False
  219. recipientActor=httpPrefix+"://"+possibleDomain+"/users/"+possibleNickname
  220. if recipientActor not in recipients:
  221. recipients.append(recipientActor)
  222. tags[wordStr]={
  223. 'href': recipientActor,
  224. 'name': wordStr,
  225. 'type': 'Mention'
  226. }
  227. replaceMentions[wordStr]="<span class=\"h-card\"><a href=\""+httpPrefix+"://"+possibleDomain+"/@"+possibleNickname+"\" class=\"u-url mention\">@<span>"+possibleNickname+"</span></a></span>"
  228. return True
  229. def removeLongWords(content: str,maxWordLength: int,longWordsList: []) -> str:
  230. """Breaks up long words so that on mobile screens this doesn't disrupt the layout
  231. """
  232. words=content.split(' ')
  233. if not longWordsList:
  234. longWordsList=[]
  235. for wordStr in words:
  236. if len(wordStr)>maxWordLength:
  237. if wordStr not in longWordsList:
  238. longWordsList.append(wordStr)
  239. for wordStr in longWordsList:
  240. if wordStr.startswith('<'):
  241. continue
  242. if '=\"' in wordStr:
  243. continue
  244. if '@' in wordStr:
  245. if '@@' not in wordStr:
  246. continue
  247. if 'https:' in wordStr:
  248. continue
  249. elif 'http:' in wordStr:
  250. continue
  251. elif 'dat:' in wordStr:
  252. continue
  253. if '<' in wordStr:
  254. wordStr=wordStr.split('<',1)[0]
  255. if '/' in wordStr:
  256. continue
  257. if len(wordStr[maxWordLength:])<maxWordLength:
  258. content= \
  259. content.replace(wordStr, \
  260. wordStr[:maxWordLength]+'\n'+ \
  261. wordStr[maxWordLength:])
  262. else:
  263. content= \
  264. content.replace(wordStr, \
  265. wordStr[:maxWordLength])
  266. return content
  267. def addHtmlTags(baseDir: str,httpPrefix: str, \
  268. nickname: str,domain: str,content: str, \
  269. recipients: [],hashtags: {},isJsonContent=False) -> str:
  270. """ Replaces plaintext mentions such as @nick@domain into html
  271. by matching against known following accounts
  272. """
  273. if content.startswith('<p>'):
  274. return content
  275. maxWordLength=40
  276. content=content.replace('\n',' --linebreak-- ')
  277. content=addMusicTag(content,'nowplaying')
  278. words=content.replace(',',' ').replace(';',' ').split(' ')
  279. # remove . for words which are not mentions
  280. wordCtr=0
  281. newWords=[]
  282. for wordIndex in range(0,len(words)):
  283. wordStr=words[wordIndex]
  284. if wordStr.endswith('.'):
  285. if not wordStr.startswith('@'):
  286. wordStr=wordStr[:-1]
  287. if wordStr.startswith('.'):
  288. wordStr=wordStr[1:]
  289. newWords.append(wordStr)
  290. words=newWords
  291. replaceMentions={}
  292. replaceHashTags={}
  293. replaceEmoji={}
  294. emojiDict={}
  295. originalDomain=domain
  296. if ':' in domain:
  297. domain=domain.split(':')[0]
  298. followingFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/following.txt'
  299. # read the following list so that we can detect just @nick
  300. # in addition to @nick@domain
  301. following=None
  302. if '@' in words:
  303. if os.path.isfile(followingFilename):
  304. with open(followingFilename, "r") as f:
  305. following = f.readlines()
  306. # extract mentions and tags from words
  307. longWordsList=[]
  308. for wordStr in words:
  309. wordLen=len(wordStr)
  310. if wordLen>2:
  311. if wordLen>maxWordLength:
  312. longWordsList.append(wordStr)
  313. firstChar=wordStr[0]
  314. if firstChar=='@':
  315. if addMention(wordStr,httpPrefix,following,replaceMentions,recipients,hashtags):
  316. continue
  317. elif firstChar=='#':
  318. if addHashTags(wordStr,httpPrefix,originalDomain,replaceHashTags,hashtags):
  319. continue
  320. elif ':' in wordStr:
  321. #print('TAG: emoji located - '+wordStr)
  322. wordStr2=wordStr.split(':')[1]
  323. if not emojiDict:
  324. # emoji.json is generated so that it can be customized and the changes
  325. # will be retained even if default_emoji.json is subsequently updated
  326. if not os.path.isfile(baseDir+'/emoji/emoji.json'):
  327. copyfile(baseDir+'/emoji/default_emoji.json',baseDir+'/emoji/emoji.json')
  328. emojiDict=loadJson(baseDir+'/emoji/emoji.json')
  329. #print('TAG: looking up emoji for :'+wordStr2+':')
  330. addEmoji(baseDir,':'+wordStr2+':',httpPrefix,originalDomain,replaceEmoji,hashtags,emojiDict)
  331. # replace words with their html versions
  332. for wordStr,replaceStr in replaceMentions.items():
  333. content=content.replace(wordStr,replaceStr)
  334. for wordStr,replaceStr in replaceHashTags.items():
  335. content=content.replace(wordStr,replaceStr)
  336. if not isJsonContent:
  337. for wordStr,replaceStr in replaceEmoji.items():
  338. content=content.replace(wordStr,replaceStr)
  339. content=addWebLinks(content)
  340. if longWordsList:
  341. content=removeLongWords(content,maxWordLength,longWordsList)
  342. content=content.replace(' --linebreak-- ','</p><p>')
  343. return '<p>'+content+'</p>'
  344. def getMentionsFromHtml(htmlText: str,matchStr="<span class=\"h-card\"><a href=\"") -> []:
  345. """Extracts mentioned actors from the given html content string
  346. """
  347. mentions=[]
  348. if matchStr not in htmlText:
  349. return mentions
  350. mentionsList=htmlText.split(matchStr)
  351. for mentionStr in mentionsList:
  352. if '"' not in mentionStr:
  353. continue
  354. actorStr=mentionStr.split('"')[0]
  355. if actorStr.startswith('http') or \
  356. actorStr.startswith('dat:'):
  357. if actorStr not in mentions:
  358. mentions.append(actorStr)
  359. return mentions
  360. def extractMediaInFormPOST(postBytes,boundary,name: str):
  361. """Extracts the binary encoding for image/video/audio within a http form POST
  362. Returns the media bytes and the remaining bytes
  363. """
  364. imageStartBoundary=b'Content-Disposition: form-data; name="'+name.encode('utf8', 'ignore')+b'";'
  365. imageStartLocation=postBytes.find(imageStartBoundary)
  366. if imageStartLocation==-1:
  367. return None,postBytes
  368. # bytes after the start boundary appears
  369. mediaBytes=postBytes[imageStartLocation:]
  370. # look for the next boundary
  371. imageEndBoundary=boundary.encode('utf8', 'ignore')
  372. imageEndLocation=mediaBytes.find(imageEndBoundary)
  373. if imageEndLocation==-1:
  374. # no ending boundary
  375. return mediaBytes,postBytes[:imageStartLocation]
  376. # remaining bytes after the end of the image
  377. remainder=mediaBytes[imageEndLocation:]
  378. # remove bytes after the end boundary
  379. mediaBytes=mediaBytes[:imageEndLocation]
  380. # return the media and the before+after bytes
  381. return mediaBytes,postBytes[:imageStartLocation]+remainder
  382. def saveMediaInFormPOST(mediaBytes,debug: bool, \
  383. filenameBase=None) -> (str,str):
  384. """Saves the given media bytes extracted from http form POST
  385. Returns the filename and attachment type
  386. """
  387. if not mediaBytes:
  388. if debug:
  389. print('DEBUG: No media found within POST')
  390. return None,None
  391. mediaLocation=-1
  392. searchStr=''
  393. filename=None
  394. # directly search the binary array for the beginning
  395. # of an image
  396. extensionList= {
  397. 'png': 'image/png',
  398. 'jpeg': 'image/jpeg',
  399. 'gif': 'image/gif',
  400. 'webp': 'image/webp',
  401. 'mp4': 'video/mp4',
  402. 'ogv': 'video/ogv',
  403. 'mp3': 'audio/mpeg',
  404. 'ogg': 'audio/ogg'
  405. }
  406. detectedExtension=None
  407. for extension,contentType in extensionList.items():
  408. searchStr=b'Content-Type: '+contentType.encode('utf8', 'ignore')
  409. mediaLocation=mediaBytes.find(searchStr)
  410. if mediaLocation>-1:
  411. if extension=='jpeg':
  412. extension='jpg'
  413. elif extension=='mpeg':
  414. extension='mp3'
  415. filename=filenameBase+'.'+extension
  416. attachmentMediaType= \
  417. searchStr.decode().split('/')[0].replace('Content-Type: ','')
  418. detectedExtension=extension
  419. break
  420. if not filename:
  421. return None,None
  422. # locate the beginning of the image, after any
  423. # carriage returns
  424. startPos=mediaLocation+len(searchStr)
  425. for offset in range(1,8):
  426. if mediaBytes[startPos+offset]!=10:
  427. if mediaBytes[startPos+offset]!=13:
  428. startPos+=offset
  429. break
  430. # remove any existing image files with a different format
  431. extensionTypes=('png','jpg','jpeg','gif','webp')
  432. for ex in extensionTypes:
  433. if ex==detectedExtension:
  434. continue
  435. possibleOtherFormat=filename.replace('.temp','').replace('.'+detectedExtension,'.'+ex)
  436. if os.path.isfile(possibleOtherFormat):
  437. os.remove(possibleOtherFormat)
  438. fd = open(filename, 'wb')
  439. fd.write(mediaBytes[startPos:])
  440. fd.close()
  441. return filename,attachmentMediaType
  442. def extractTextFieldsInPOST(postBytes,boundary,debug: bool) -> {}:
  443. """Returns a dictionary containing the text fields of a http form POST
  444. The boundary argument comes from the http header
  445. """
  446. msg = email.parser.BytesParser().parsebytes(postBytes)
  447. if debug:
  448. print('DEBUG: POST arriving '+msg.get_payload(decode=True).decode('utf-8'))
  449. messageFields=msg.get_payload(decode=True).decode('utf-8').split(boundary)
  450. fields={}
  451. # examine each section of the POST, separated by the boundary
  452. for f in messageFields:
  453. if f=='--':
  454. continue
  455. if ' name="' not in f:
  456. continue
  457. postStr=f.split(' name="',1)[1]
  458. if '"' not in postStr:
  459. continue
  460. postKey=postStr.split('"',1)[0]
  461. postValueStr=postStr.split('"',1)[1]
  462. if ';' in postValueStr:
  463. continue
  464. if '\r\n' not in postValueStr:
  465. continue
  466. postLines=postValueStr.split('\r\n')
  467. postValue=''
  468. if len(postLines)>2:
  469. for line in range(2,len(postLines)-1):
  470. if line>2:
  471. postValue+='\n'
  472. postValue+=postLines[line]
  473. fields[postKey]=postValue
  474. return fields