utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. __filename__ = "utils.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 shutil
  11. import datetime
  12. import json
  13. def saveJson(jsonObject: {},filename: str) -> bool:
  14. """Saves json to a file
  15. """
  16. tries=0
  17. while tries<5:
  18. try:
  19. with open(filename, 'w') as fp:
  20. fp.write(json.dumps(jsonObject))
  21. return True
  22. except:
  23. print('WARN: saveJson '+str(tries))
  24. time.sleep(1)
  25. tries+=1
  26. return False
  27. def loadJson(filename: str,delaySec=2) -> {}:
  28. """Makes a few attempts to load a json formatted file
  29. """
  30. jsonObject=None
  31. tries=0
  32. while tries<5:
  33. try:
  34. with open(filename, 'r') as fp:
  35. data=fp.read()
  36. jsonObject=json.loads(data)
  37. break
  38. except:
  39. print('WARN: loadJson exception')
  40. if delaySec>0:
  41. time.sleep(delaySec)
  42. tries+=1
  43. return jsonObject
  44. def getStatusNumber() -> (str,str):
  45. """Returns the status number and published date
  46. """
  47. currTime=datetime.datetime.utcnow()
  48. daysSinceEpoch=(currTime - datetime.datetime(1970,1,1)).days
  49. # status is the number of seconds since epoch
  50. statusNumber=str(((daysSinceEpoch*24*60*60) + (currTime.hour*60*60) + (currTime.minute*60) + currTime.second)*1000 + int(currTime.microsecond/1000))
  51. # See https://github.com/tootsuite/mastodon/blob/995f8b389a66ab76ec92d9a240de376f1fc13a38/lib/mastodon/snowflake.rb
  52. # use the leftover microseconds as the sequence number
  53. sequenceId=currTime.microsecond % 1000
  54. # shift by 16bits "sequence data"
  55. statusNumber=str((int(statusNumber)<<16)+sequenceId)
  56. published=currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
  57. return statusNumber,published
  58. def isEvil(domain: str) -> bool:
  59. # https://www.youtube.com/watch?v=5qw1hcevmdU
  60. evilDomains=('gab.com','gabfed.com','spinster.xyz','kiwifarms.cc','djitter.com')
  61. for concentratedEvil in evilDomains:
  62. if domain.endswith(concentratedEvil):
  63. return True
  64. return False
  65. def createPersonDir(nickname: str,domain: str,baseDir: str,dirname: str) -> str:
  66. """Create a directory for a person
  67. """
  68. handle=nickname+'@'+domain
  69. if not os.path.isdir(baseDir+'/accounts/'+handle):
  70. os.mkdir(baseDir+'/accounts/'+handle)
  71. boxDir=baseDir+'/accounts/'+handle+'/'+dirname
  72. if not os.path.isdir(boxDir):
  73. os.mkdir(boxDir)
  74. return boxDir
  75. def createOutboxDir(nickname: str,domain: str,baseDir: str) -> str:
  76. """Create an outbox for a person
  77. """
  78. return createPersonDir(nickname,domain,baseDir,'outbox')
  79. def createInboxQueueDir(nickname: str,domain: str,baseDir: str) -> str:
  80. """Create an inbox queue and returns the feed filename and directory
  81. """
  82. return createPersonDir(nickname,domain,baseDir,'queue')
  83. def domainPermitted(domain: str, federationList: []):
  84. if len(federationList)==0:
  85. return True
  86. if ':' in domain:
  87. domain=domain.split(':')[0]
  88. if domain in federationList:
  89. return True
  90. return False
  91. def urlPermitted(url: str,federationList: [],capability: str):
  92. if isEvil(url):
  93. return False
  94. if not federationList:
  95. return True
  96. for domain in federationList:
  97. if domain in url:
  98. return True
  99. return False
  100. def getDisplayName(baseDir: str,actor: str,personCache: {}) -> str:
  101. """Returns the display name for the given actor
  102. """
  103. if '/statuses/' in actor:
  104. actor=actor.split('/statuses/')[0]
  105. if not personCache.get(actor):
  106. return None
  107. if personCache[actor].get('actor'):
  108. if personCache[actor]['actor'].get('name'):
  109. return personCache[actor]['actor']['name']
  110. else:
  111. # Try to obtain from the cached actors
  112. cachedActorFilename=baseDir+'/cache/actors/'+(actor.replace('/','#'))+'.json'
  113. if os.path.isfile(cachedActorFilename):
  114. actorJson=loadJson(cachedActorFilename,1)
  115. if actorJson:
  116. if actorJson.get('name'):
  117. return(actorJson['name'])
  118. return None
  119. def getNicknameFromActor(actor: str) -> str:
  120. """Returns the nickname from an actor url
  121. """
  122. if '/users/' not in actor:
  123. if '/profile/' in actor:
  124. nickStr=actor.split('/profile/')[1].replace('@','')
  125. if '/' not in nickStr:
  126. return nickStr
  127. else:
  128. return nickStr.split('/')[0]
  129. if '/channel/' in actor:
  130. nickStr=actor.split('/channel/')[1].replace('@','')
  131. if '/' not in nickStr:
  132. return nickStr
  133. else:
  134. return nickStr.split('/')[0]
  135. # https://domain/@nick
  136. if '/@' in actor:
  137. nickStr=actor.split('/@')[1]
  138. if '/' in nickStr:
  139. nickStr=nickStr.split('/')[0]
  140. return nickStr
  141. return None
  142. nickStr=actor.split('/users/')[1].replace('@','')
  143. if '/' not in nickStr:
  144. return nickStr
  145. else:
  146. return nickStr.split('/')[0]
  147. def getDomainFromActor(actor: str) -> (str,int):
  148. """Returns the domain name from an actor url
  149. """
  150. port=None
  151. if '/profile/' in actor:
  152. domain = actor.split('/profile/')[0].replace('https://','').replace('http://','').replace('dat://','')
  153. else:
  154. if '/channel/' in actor:
  155. domain = actor.split('/channel/')[0].replace('https://','').replace('http://','').replace('dat://','')
  156. else:
  157. if '/users/' not in actor:
  158. domain = actor.replace('https://','').replace('http://','').replace('dat://','')
  159. if '/' in actor:
  160. domain=domain.split('/')[0]
  161. else:
  162. domain = actor.split('/users/')[0].replace('https://','').replace('http://','').replace('dat://','')
  163. if ':' in domain:
  164. port=int(domain.split(':')[1])
  165. domain=domain.split(':')[0]
  166. return domain,port
  167. def followPerson(baseDir: str,nickname: str, domain: str, \
  168. followNickname: str, followDomain: str, \
  169. federationList: [],debug: bool, \
  170. followFile='following.txt') -> bool:
  171. """Adds a person to the follow list
  172. """
  173. if not domainPermitted(followDomain.lower().replace('\n',''), \
  174. federationList):
  175. if debug:
  176. print('DEBUG: follow of domain '+followDomain+' not permitted')
  177. return False
  178. if debug:
  179. print('DEBUG: follow of domain '+followDomain)
  180. if ':' in domain:
  181. handle=nickname+'@'+domain.split(':')[0].lower()
  182. else:
  183. handle=nickname+'@'+domain.lower()
  184. if ':' in followDomain:
  185. handleToFollow=followNickname+'@'+followDomain.split(':')[0].lower()
  186. else:
  187. handleToFollow=followNickname+'@'+followDomain.lower()
  188. if not os.path.isdir(baseDir+'/accounts'):
  189. os.mkdir(baseDir+'/accounts')
  190. if not os.path.isdir(baseDir+'/accounts/'+handle):
  191. os.mkdir(baseDir+'/accounts/'+handle)
  192. filename=baseDir+'/accounts/'+handle+'/'+followFile
  193. if os.path.isfile(filename):
  194. if handleToFollow in open(filename).read():
  195. if debug:
  196. print('DEBUG: follow already exists')
  197. return True
  198. # prepend to follow file
  199. try:
  200. with open(filename, 'r+') as followFile:
  201. content = followFile.read()
  202. followFile.seek(0, 0)
  203. followFile.write(followNickname+'@'+followDomain+'\n'+content)
  204. if debug:
  205. print('DEBUG: follow added')
  206. return True
  207. except Exception as e:
  208. print('WARN: Failed to write entry to follow file '+filename+' '+str(e))
  209. if debug:
  210. print('DEBUG: creating new following file')
  211. with open(filename, "w") as followfile:
  212. followfile.write(followNickname+'@'+followDomain+'\n')
  213. return True
  214. def locatePost(baseDir: str,nickname: str,domain: str,postUrl: str,replies=False) -> str:
  215. """Returns the filename for the given status post url
  216. """
  217. if not replies:
  218. extension='json'
  219. else:
  220. extension='replies'
  221. # if this post in the shared inbox?
  222. handle='inbox@'+domain
  223. postUrl=postUrl.replace('/','#').replace('/activity','').strip()
  224. boxName='inbox'
  225. postFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/'+boxName+'/'+postUrl+'.'+extension
  226. if os.path.isfile(postFilename):
  227. return postFilename
  228. boxName='outbox'
  229. postFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/'+boxName+'/'+postUrl+'.'+extension
  230. if os.path.isfile(postFilename):
  231. return postFilename
  232. # if this post in the inbox of the person?
  233. boxName='inbox'
  234. postFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/'+boxName+'/'+postUrl+'.'+extension
  235. if os.path.isfile(postFilename):
  236. return postFilename
  237. postFilename=baseDir+'/cache/announce/'+nickname+'/'+postUrl+'.'+extension
  238. if os.path.isfile(postFilename):
  239. return postFilename
  240. print('WARN: unable to locate '+nickname+' '+postUrl+'.'+extension)
  241. return None
  242. def removeAttachment(baseDir: str,httpPrefix: str,domain: str,postJson: {}):
  243. if not postJson.get('attachment'):
  244. return
  245. if not postJson['attachment'][0].get('url'):
  246. return
  247. if port:
  248. if port!=80 and port!=443:
  249. if ':' not in domain:
  250. domain=domain+':'+str(port)
  251. attachmentUrl=postJson['attachment'][0]['url']
  252. if not attachmentUrl:
  253. return
  254. mediaFilename=baseDir+'/'+attachmentUrl.replace(httpPrefix+'://'+domain+'/','')
  255. if os.path.isfile(mediaFilename):
  256. os.remove(mediaFilename)
  257. etagFilename=mediaFilename+'.etag'
  258. if os.path.isfile(etagFilename):
  259. os.remove(etagFilename)
  260. postJson['attachment']=[]
  261. def removeModerationPostFromIndex(baseDir: str,postUrl: str,debug: bool) -> None:
  262. """Removes a url from the moderation index
  263. """
  264. moderationIndexFile=baseDir+'/accounts/moderation.txt'
  265. if not os.path.isfile(moderationIndexFile):
  266. return
  267. postId=postUrl.replace('/activity','')
  268. if postId in open(moderationIndexFile).read():
  269. with open(moderationIndexFile, "r") as f:
  270. lines = f.readlines()
  271. with open(moderationIndexFile, "w+") as f:
  272. for line in lines:
  273. if line.strip("\n") != postId:
  274. f.write(line)
  275. else:
  276. if debug:
  277. print('DEBUG: removed '+postId+' from moderation index')
  278. def deletePost(baseDir: str,httpPrefix: str,nickname: str,domain: str,postFilename: str,debug: bool) -> None:
  279. """Recursively deletes a post and its replies and attachments
  280. """
  281. postJsonObject=loadJson(postFilename,1)
  282. if postJsonObject:
  283. # don't allow deletion of bookmarked posts
  284. bookmarksIndexFilename=baseDir+'/accounts/'+nickname+'@'+domain+'/bookmarks.index'
  285. if os.path.isfile(bookmarksIndexFilename):
  286. bookmarkIndex=postFilename.split('/')[-1]+'\n'
  287. if bookmarkIndex in open(bookmarksIndexFilename).read():
  288. return
  289. # remove any attachment
  290. removeAttachment(baseDir,httpPrefix,domain,postJsonObject)
  291. # remove any mute file
  292. muteFilename=postFilename+'.muted'
  293. if os.path.isfile(muteFilename):
  294. os.remove(muteFilename)
  295. # remove cached html version of the post
  296. cachedPostFilename= \
  297. getCachedPostFilename(baseDir,nickname,domain,postJsonObject)
  298. if cachedPostFilename:
  299. if os.path.isfile(cachedPostFilename):
  300. os.remove(cachedPostFilename)
  301. #removePostFromCache(postJsonObject,recentPostsCache)
  302. hasObject=False
  303. if postJsonObject.get('object'):
  304. hasObject=True
  305. # remove from moderation index file
  306. if hasObject:
  307. if isinstance(postJsonObject['object'], dict):
  308. if postJsonObject['object'].get('moderationStatus'):
  309. if postJsonObject.get('id'):
  310. postId=postJsonObject['id'].replace('/activity','')
  311. removeModerationPostFromIndex(baseDir,postId,debug)
  312. # remove any hashtags index entries
  313. removeHashtagIndex=False
  314. if hasObject:
  315. if hasObject and isinstance(postJsonObject['object'], dict):
  316. if postJsonObject['object'].get('content'):
  317. if '#' in postJsonObject['object']['content']:
  318. removeHashtagIndex=True
  319. if removeHashtagIndex:
  320. if postJsonObject['object'].get('id') and postJsonObject['object'].get('tag'):
  321. # get the id of the post
  322. postId=postJsonObject['object']['id'].replace('/activity','')
  323. for tag in postJsonObject['object']['tag']:
  324. if tag['type']!='Hashtag':
  325. continue
  326. # find the index file for this tag
  327. tagIndexFilename=baseDir+'/tags/'+tag['name'][1:]+'.txt'
  328. if not os.path.isfile(tagIndexFilename):
  329. continue
  330. # remove postId from the tag index file
  331. with open(tagIndexFilename, "r") as f:
  332. lines = f.readlines()
  333. with open(tagIndexFilename, "w+") as f:
  334. for line in lines:
  335. if line.strip("\n") != postId:
  336. f.write(line)
  337. # remove any replies
  338. repliesFilename=postFilename.replace('.json','.replies')
  339. if os.path.isfile(repliesFilename):
  340. if debug:
  341. print('DEBUG: removing replies to '+postFilename)
  342. with open(repliesFilename,'r') as f:
  343. for replyId in f:
  344. replyFile=locatePost(baseDir,nickname,domain,replyId)
  345. if replyFile:
  346. if os.path.isfile(replyFile):
  347. deletePost(baseDir,httpPrefix,nickname,domain,replyFile,debug)
  348. # remove the replies file
  349. os.remove(repliesFilename)
  350. # finally, remove the post itself
  351. os.remove(postFilename)
  352. def validNickname(domain: str,nickname: str) -> bool:
  353. forbiddenChars=['.',' ','/','?',':',';','@']
  354. for c in forbiddenChars:
  355. if c in nickname:
  356. return False
  357. if nickname==domain:
  358. return False
  359. reservedNames=['inbox','dm','outbox','following','public','followers','profile','channel','capabilities','calendar','tlreplies','tlmedia','moderation','activity','undo','reply','replies','question','like','likes','users','statuses','updates','repeat','announce','shares']
  360. if nickname in reservedNames:
  361. return False
  362. return True
  363. def noOfAccounts(baseDir: str) -> bool:
  364. """Returns the number of accounts on the system
  365. """
  366. accountCtr=0
  367. for subdir, dirs, files in os.walk(baseDir+'/accounts'):
  368. for account in dirs:
  369. if '@' in account:
  370. if not account.startswith('inbox@'):
  371. accountCtr+=1
  372. return accountCtr
  373. def noOfActiveAccountsMonthly(baseDir: str,months: int) -> bool:
  374. """Returns the number of accounts on the system this month
  375. """
  376. accountCtr=0
  377. currTime=int(time.time())
  378. monthSeconds=int(60*60*24*30*months)
  379. for subdir, dirs, files in os.walk(baseDir+'/accounts'):
  380. for account in dirs:
  381. if '@' in account:
  382. if not account.startswith('inbox@'):
  383. lastUsedFilename=baseDir+'/accounts/'+account+'/.lastUsed'
  384. if os.path.isfile(lastUsedFilename):
  385. with open(lastUsedFilename, 'r') as lastUsedFile:
  386. lastUsed = lastUsedFile.read()
  387. if lastUsed.isdigit():
  388. timeDiff=(currTime-int(lastUsed))
  389. if timeDiff<monthSeconds:
  390. accountCtr+=1
  391. return accountCtr
  392. def isPublicPost(postJsonObject: {}) -> bool:
  393. """Returns true if the given post is public
  394. """
  395. if not postJsonObject.get('type'):
  396. return False
  397. if postJsonObject['type']!='Create':
  398. return False
  399. if not postJsonObject.get('object'):
  400. return False
  401. if not isinstance(postJsonObject['object'], dict):
  402. return False
  403. if not postJsonObject['object'].get('to'):
  404. return False
  405. for recipient in postJsonObject['object']['to']:
  406. if recipient.endswith('#Public'):
  407. return True
  408. return False
  409. def copytree(src: str, dst: str, symlinks=False, ignore=None):
  410. """Copy a directory
  411. """
  412. for item in os.listdir(src):
  413. s = os.path.join(src, item)
  414. d = os.path.join(dst, item)
  415. if os.path.isdir(s):
  416. shutil.copytree(s, d, symlinks, ignore)
  417. else:
  418. shutil.copy2(s, d)
  419. def getCachedPostDirectory(baseDir: str,nickname: str,domain: str) -> str:
  420. """Returns the directory where the html post cache exists
  421. """
  422. htmlPostCacheDir=baseDir+'/accounts/'+nickname+'@'+domain+'/postcache'
  423. return htmlPostCacheDir
  424. def getCachedPostFilename(baseDir: str,nickname: str,domain: str, \
  425. postJsonObject: {}) -> str:
  426. """Returns the html cache filename for the given post
  427. """
  428. cachedPostDir=getCachedPostDirectory(baseDir,nickname,domain)
  429. if not os.path.isdir(cachedPostDir):
  430. print('ERROR: invalid html cache directory '+cachedPostDir)
  431. return None
  432. if '@' not in cachedPostDir:
  433. print('ERROR: invalid html cache directory '+cachedPostDir)
  434. return None
  435. cachedPostFilename= \
  436. cachedPostDir+ \
  437. '/'+postJsonObject['id'].replace('/activity','').replace('/','#')
  438. cachedPostFilename=cachedPostFilename+'.html'
  439. return cachedPostFilename
  440. def removePostFromCache(postJsonObject: {},recentPostsCache: {}):
  441. """ if the post exists in the recent posts cache then remove it
  442. """
  443. if not postJsonObject.get('id'):
  444. return
  445. if not recentPostsCache.get('index'):
  446. return
  447. postId=postJsonObject['id']
  448. if '#' in postId:
  449. postId=postId.split('#',1)[0]
  450. postId=postId.replace('/activity','').replace('/','#')
  451. if postId not in recentPostsCache['index']:
  452. return
  453. if recentPostsCache['json'].get(postId):
  454. del recentPostsCache['json'][postId]
  455. if recentPostsCache['html'].get(postId):
  456. del recentPostsCache['html'][postId]
  457. recentPostsCache['index'].remove(postId)
  458. def updateRecentPostsCache(recentPostsCache: {},maxRecentPosts: int, \
  459. postJsonObject: {},htmlStr: str) -> None:
  460. """Store recent posts in memory so that they can be quickly recalled
  461. """
  462. if not postJsonObject.get('id'):
  463. return
  464. postId=postJsonObject['id']
  465. if '#' in postId:
  466. postId=postId.split('#',1)[0]
  467. postId=postId.replace('/activity','').replace('/','#')
  468. if recentPostsCache.get('index'):
  469. if postId in recentPostsCache['index']:
  470. return
  471. recentPostsCache['index'].append(postId)
  472. postJsonObject['muted']=False
  473. recentPostsCache['json'][postId]=json.dumps(postJsonObject)
  474. recentPostsCache['html'][postId]=htmlStr
  475. while len(recentPostsCache['html'].items())>maxRecentPosts:
  476. recentPostsCache['index'].pop(0)
  477. del recentPostsCache['json'][postId]
  478. del recentPostsCache['html'][postId]
  479. else:
  480. recentPostsCache['index']=[postId]
  481. recentPostsCache['json']={}
  482. recentPostsCache['html']={}
  483. recentPostsCache['json'][postId]=json.dumps(postJsonObject)
  484. recentPostsCache['html'][postId]=htmlStr