content.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 commentjson
  11. import email.parser
  12. from shutil import copyfile
  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. emojiDictCtr=0
  329. while not emojiDict and emojiDictCtr<5:
  330. if emojiDictCtr>0:
  331. print('Retry emoji load '+baseDir+'/emoji/emoji.json')
  332. try:
  333. with open(baseDir+'/emoji/emoji.json', 'r') as fp:
  334. emojiDict=commentjson.load(fp)
  335. if emojiDictCtr>0:
  336. print('emojiDict loaded on try '+str(emojiDictCtr))
  337. break
  338. except:
  339. print('WARN: commentjson exception addHtmlTags')
  340. print('Failed to load emoji (try '+str(emojiDictCtr)+'): '+baseDir+'/emoji/emoji.json')
  341. time.sleep(1)
  342. emojiDictCtr+=1
  343. #print('TAG: looking up emoji for :'+wordStr2+':')
  344. addEmoji(baseDir,':'+wordStr2+':',httpPrefix,originalDomain,replaceEmoji,hashtags,emojiDict)
  345. # replace words with their html versions
  346. for wordStr,replaceStr in replaceMentions.items():
  347. content=content.replace(wordStr,replaceStr)
  348. for wordStr,replaceStr in replaceHashTags.items():
  349. content=content.replace(wordStr,replaceStr)
  350. if not isJsonContent:
  351. for wordStr,replaceStr in replaceEmoji.items():
  352. content=content.replace(wordStr,replaceStr)
  353. content=addWebLinks(content)
  354. if longWordsList:
  355. content=removeLongWords(content,maxWordLength,longWordsList)
  356. content=content.replace(' --linebreak-- ','</p><p>')
  357. return '<p>'+content+'</p>'
  358. def getMentionsFromHtml(htmlText: str,matchStr="<span class=\"h-card\"><a href=\"") -> []:
  359. """Extracts mentioned actors from the given html content string
  360. """
  361. mentions=[]
  362. if matchStr not in htmlText:
  363. return mentions
  364. mentionsList=htmlText.split(matchStr)
  365. for mentionStr in mentionsList:
  366. if '"' not in mentionStr:
  367. continue
  368. actorStr=mentionStr.split('"')[0]
  369. if actorStr.startswith('http') or \
  370. actorStr.startswith('dat:'):
  371. if actorStr not in mentions:
  372. mentions.append(actorStr)
  373. return mentions
  374. def extractMediaInFormPOST(postBytes,boundary,name: str):
  375. """Extracts the binary encoding for image/video/audio within a http form POST
  376. Returns the media bytes and the remaining bytes
  377. """
  378. imageStartBoundary=b'Content-Disposition: form-data; name="'+name.encode('utf8', 'ignore')+b'";'
  379. imageStartLocation=postBytes.find(imageStartBoundary)
  380. if imageStartLocation==-1:
  381. return None,postBytes
  382. # bytes after the start boundary appears
  383. mediaBytes=postBytes[imageStartLocation:]
  384. # look for the next boundary
  385. imageEndBoundary=boundary.encode('utf8', 'ignore')
  386. imageEndLocation=mediaBytes.find(imageEndBoundary)
  387. if imageEndLocation==-1:
  388. # no ending boundary
  389. return mediaBytes,postBytes[:imageStartLocation]
  390. # remaining bytes after the end of the image
  391. remainder=mediaBytes[imageEndLocation:]
  392. # remove bytes after the end boundary
  393. mediaBytes=mediaBytes[:imageEndLocation]
  394. # return the media and the before+after bytes
  395. return mediaBytes,postBytes[:imageStartLocation]+remainder
  396. def saveMediaInFormPOST(mediaBytes,debug: bool, \
  397. filenameBase=None) -> (str,str):
  398. """Saves the given media bytes extracted from http form POST
  399. Returns the filename and attachment type
  400. """
  401. if not mediaBytes:
  402. if debug:
  403. print('DEBUG: No media found within POST')
  404. return None,None
  405. mediaLocation=-1
  406. searchStr=''
  407. filename=None
  408. # directly search the binary array for the beginning
  409. # of an image
  410. extensionList= {
  411. 'png': 'image/png',
  412. 'jpeg': 'image/jpeg',
  413. 'gif': 'image/gif',
  414. 'webp': 'image/webp',
  415. 'mp4': 'video/mp4',
  416. 'ogv': 'video/ogv',
  417. 'mp3': 'audio/mpeg',
  418. 'ogg': 'audio/ogg'
  419. }
  420. detectedExtension=None
  421. for extension,contentType in extensionList.items():
  422. searchStr=b'Content-Type: '+contentType.encode('utf8', 'ignore')
  423. mediaLocation=mediaBytes.find(searchStr)
  424. if mediaLocation>-1:
  425. if extension=='jpeg':
  426. extension='jpg'
  427. elif extension=='mpeg':
  428. extension='mp3'
  429. filename=filenameBase+'.'+extension
  430. attachmentMediaType= \
  431. searchStr.decode().split('/')[0].replace('Content-Type: ','')
  432. detectedExtension=extension
  433. break
  434. if not filename:
  435. return None,None
  436. # locate the beginning of the image, after any
  437. # carriage returns
  438. startPos=mediaLocation+len(searchStr)
  439. for offset in range(1,8):
  440. if mediaBytes[startPos+offset]!=10:
  441. if mediaBytes[startPos+offset]!=13:
  442. startPos+=offset
  443. break
  444. # remove any existing image files with a different format
  445. extensionTypes=('png','jpg','jpeg','gif','webp')
  446. for ex in extensionTypes:
  447. if ex==detectedExtension:
  448. continue
  449. possibleOtherFormat=filename.replace('.temp','').replace('.'+detectedExtension,'.'+ex)
  450. if os.path.isfile(possibleOtherFormat):
  451. os.remove(possibleOtherFormat)
  452. fd = open(filename, 'wb')
  453. fd.write(mediaBytes[startPos:])
  454. fd.close()
  455. return filename,attachmentMediaType
  456. def extractTextFieldsInPOST(postBytes,boundary,debug: bool) -> {}:
  457. """Returns a dictionary containing the text fields of a http form POST
  458. The boundary argument comes from the http header
  459. """
  460. msg = email.parser.BytesParser().parsebytes(postBytes)
  461. if debug:
  462. print('DEBUG: POST arriving '+msg.get_payload(decode=True).decode('utf-8'))
  463. messageFields=msg.get_payload(decode=True).decode('utf-8').split(boundary)
  464. fields={}
  465. # examine each section of the POST, separated by the boundary
  466. for f in messageFields:
  467. if f=='--':
  468. continue
  469. if ' name="' not in f:
  470. continue
  471. postStr=f.split(' name="',1)[1]
  472. if '"' not in postStr:
  473. continue
  474. postKey=postStr.split('"',1)[0]
  475. postValueStr=postStr.split('"',1)[1]
  476. if ';' in postValueStr:
  477. continue
  478. if '\r\n' not in postValueStr:
  479. continue
  480. postLines=postValueStr.split('\r\n')
  481. postValue=''
  482. if len(postLines)>2:
  483. for line in range(2,len(postLines)-1):
  484. if line>2:
  485. postValue+='\n'
  486. postValue+=postLines[line]
  487. fields[postKey]=postValue
  488. return fields