async def updatePreview(self): textData = self.currentDocument.toPlainText() pDocument = self.currentDocument.previewDocument try: mimeType = await detectMimeTypeFromBuffer(textData.encode()) except: pass if self.currentDocument.filename: await self.writeDocument(self.currentDocument) if mimeType and mimeType.isHtml: if self.currentDocument.filename: url = self.checkoutChildFileUrl(self.currentDocument.filename) self.previewWidget.setUrl(url) else: self.previewWidget.setHtml(textData) else: try: html = markitdown(textData) pDocument.setHtml(html) self.previewWidget.setHtml(html) except Exception: pDocument.setPlainText(textData)
def onTimerOut(self): textData = self.textEditUser.toPlainText() try: html = markitdown(textData) self.textEditMarkdown.setHtml(html) except Exception: pass self.updateTimer.stop()
def showText(self, textData, preview=False): if preview: text = textData newDocument = self.newDocument(text=textData) try: html = markitdown(text) newDocument.setHtml(html) except Exception: newDocument.setPlainText(text) self.textEditor.setReadOnly(True) return newDocument else: doc = self.newDocument(text=textData) self.textEditor.setReadOnly(not self.editing) return doc
def feedAddPosts(self, blogPosts, feed, ftype='ipfs'): for post in blogPosts: ppath = self.sitePath.child( posixIpfsPath.join('blog', post['postname'], 'view')) fEntry = feed.add_entry() fEntry.title(post['title']) if ftype == 'ipfs': url = ppath.ipfsUrl elif ftype == 'publicgw': url = ppath.publicGwUrl fEntry.id(url) fEntry.link(href=url, rel='alternate') fEntry.updated(post['date_modified']) fEntry.published(post['date_published']) fEntry.content(content=markitdown(post['body']), type='html') fEntry.author({'name': self.profile.userInfo.iphandle}) for tag in post['tags']: fEntry.category(term=tag)
async def onChatMessageReceived(self, key, message): now = datetimeNow() if message.chatMessageType == ChatRoomMessage.CHATMSG_TYPE_HEARTBEAT: await self.userHeartbeat(message) return self.ui.chatLog.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor) self.ui.chatLog.insertPlainText('\n') formatted = '<p style="margin-left: 0px">' formatted += '<span style="color: black">{date}</span> '.format( date=now.strftime('%H:%M')) formatted += '<span style="color: #e67300">{sender}</span>: '.format( sender=message.peerCtx.spaceHandle.short) if message.chatMessageType == ChatRoomMessage.CHATMSG_TYPE_MESSAGE: if not self.isVisible(): self.setTabIcon(getIcon('chat-active.png')) else: self.setTabIcon(getIcon('qta:mdi.chat-outline')) # System tray notification if the main window is not visible if not self.app.mainWindow.isActiveWindow(): self.app.systemTrayMessage( iChat(), iChatMessageNotification( self.channel, message.peerCtx.spaceHandle.short), timeout=4000) formatted += '<p> {message}</p>'.format( message=markitdown(message.message)) elif message.chatMessageType == ChatRoomMessage.CHATMSG_TYPE_JOINED: await self.userHeartbeat(message) formatted += '<span style="color: blue">{message}</span>'.format( message='joined the channel') formatted += '</p>' elif message.chatMessageType == ChatRoomMessage.CHATMSG_TYPE_LEFT: await self.userLeft(message) formatted += '<span style="color: red">{message}</span>'.format( message='left the channel') formatted += '</p>' elif message.chatMessageType == ChatRoomMessage.CHATMSG_TYPE_HEARTBEAT: pass if len(message.links) > 0: for obj in message.links: if not isinstance(obj, str): continue try: path = IPFSPath(obj, autoCidConv=True) if not path.valid: continue formatted += '<p style="margin-left: 30px">Link ' formatted += '<a href="{objhref}">{name}<a>'.format( objhref=path.ipfsUrl, name=path.objPath) formatted += '</p>' except Exception: continue self.ui.chatLog.insertHtml('<br>') self.ui.chatLog.insertHtml(formatted) self.ui.chatLog.verticalScrollBar().setValue( self.ui.chatLog.verticalScrollBar().maximum())
def markdownconv(text): return markitdown(text)
async def onChatMessageReceived(self, ipfsop, key, hubMessage): sender, message = hubMessage now = datetimeNow() fromUs = (message.peerCtx.peerId == ipfsop.ctx.node.id) defAvatar = IPFSPath(ipfsop.ctx.resources['ipfs-cube-64']) avatarPath = str(message.peerCtx.avatarPath) if \ message.peerCtx.avatarPath else defAvatar.objPath if message.command == ChatRoomMessage.COMMAND_HEARTBEAT: # await self.userHeartbeat(message) return if message.command == ChatRoomMessage.COMMAND_MSGMARKDOWN: if not isinstance(message.messageBody, str): return if len(message.messageBody) not in range(1, 768): return if not self.isVisible(): self.setTabIcon(getIcon('chat-active.png')) self.tabActiveNotify() else: self.setTabIcon(getIcon('chat.png')) # System tray notification if the main window is not visible if not self.app.mainWindow.isActiveWindow(): self.app.systemTrayMessage( iChat(), iChatMessageNotification( self.channel, message.peerCtx.spaceHandle.short), timeout=3000) self.chatView.hChat.chatMsgReceived.emit( QVariant({ 'uid': message.uid, 'time': now.strftime('%H:%M'), 'local': fromUs, 'spaceHandle': str(message.peerCtx.spaceHandle.short), 'message': markitdown(message.messageBody), 'avatarPath': avatarPath })) if len(message.links) > 0: attach = [] for obj in message.links: if not isinstance(obj, str): continue try: path = IPFSPath(obj, autoCidConv=True) if not path.valid: continue mType, stat = await self.app.rscAnalyzer(path) if not mType or not stat: continue attach.append({ 'objPath': path.objPath, 'url': path.ipfsUrl, 'mimeType': str(mType), 'stat': stat }) except Exception: continue if len(attach) > 0: self.chatView.hChat.chatMsgAttachments.emit( message.uid, QVariant(attach)) elif message.command == ChatRoomMessage.COMMAND_JOIN: self.chatView.hChat.chatJoinLeftReceived.emit( QVariant({ 'avatarPath': avatarPath, 'status': 'joined', 'time': now.strftime('%H:%M'), 'local': fromUs, 'spaceHandle': str(message.peerCtx.spaceHandle.short) })) await self.userHeartbeat(message) elif message.command == ChatRoomMessage.COMMAND_LEAVE: self.chatView.hChat.chatJoinLeftReceived.emit( QVariant({ 'avatarPath': avatarPath, 'status': 'left', 'time': now.strftime('%H:%M'), 'local': fromUs, 'spaceHandle': str(message.peerCtx.spaceHandle.short) })) await self.userLeft(message)
async def init(self, ipfsop): """ Initialize the profile's filesystem """ yield 10, 'Initializing filesystem' await ipfsop.filesMkdir(self.root) for directory in self.tree: await ipfsop.filesMkdir(directory) wPath = posixIpfsPath.join(self.pathHome, 'welcome') welcomeEnt = await ipfsop.filesList(wPath) if not welcomeEnt: try: welcome = readQrcTextFile(':/share/static/misc/welcome.md') tmpPath = self.ctx.app.tempDir.filePath('welcome.html') await asyncWriteFile(tmpPath, markitdown(welcome), mode='w+t') await ipfsop.filesLink(await ipfsop.addPath(tmpPath, wrap=True), self.pathHome, name='welcome') except Exception: pass self.filesModel = createMFSModel() self.filesModel.setupItemsFromProfile(self) yield 20, 'Generating IPNS keys' key = await ipfsop.keyFind(self.keyRoot) if key is not None: self.keyRootId = key.get('Id', None) else: self.userLogInfo('Generating main IPNS key') result = await ipfsop.keyGen(self.keyRoot) self.keyRootId = result.get('Id', None) self.debug('IPNS key({0}): {1}'.format(self.keyRoot, self.keyRootId)) yield 30, 'Initializing crypto' if not await self.cryptoInit(): self.userLogInfo('Error while initializing crypto') raise ProfileError('Crypto init failed') if not await ipfsop.hasDagCommand(): self.userLogInfo('No DAG API! ..') raise ProfileError('No DAG API') yield 40, 'Initializing EDAGs ..' self._dagUser = UserDAG(self.pathUserDagMeta, loop=self.ctx.loop) self._dagChatChannels = ChannelsDAG(self.pathChatChannelsDagMeta, loop=self.ctx.loop) self._dagNetwork = PeersGraphDAG(self.pathEDagNetwork, loop=self.ctx.loop, autoUpdateDates=True) # Seeds self.dagSeedsMain = SeedsEDag(self.pathEdagSeedsMain, loop=self.ctx.loop, cipheredMeta=True) self.dagSeedsAll = MegaSeedsEDag(self.pathEdagSeedsAll, loop=self.ctx.loop, cipheredMeta=True) yield 50, 'Loading EDAGs ..' ensure(self.dagUser.load()) await self.dagUser.loaded # Chat channels await self.dagChatChannels.load() # Network EDAG await self.dagNetwork.load() # Seeds EDAGs await self.dagSeedsMain.load() await self.dagSeedsAll.load() await self.dagSeedsAll.associate(self.dagSeedsMain) self.dagUser.dagCidChanged.connect(self.onDagChange) ensure(self.publishDag(allowOffline=True, reschedule=True)) yield 60, 'Loading user blog ..' self.userWebsite = UserWebsite(self.dagUser, self, self.keyRootId, self.ctx.app.jinjaEnv, parent=self) await self.userWebsite.init() ensure(self.update()) self._initialized = True yield 70, 'Importing manual ..' ensure(self.ctx.app.manuals.importManuals(self)) self._initOptions = {} yield 100, 'Profile ready'
def mdToHtml(self, mdText: str): try: return markitdown(mdText) except Exception: return ''
async def showMessage(self, message: MaildirMessage): self.document.clear() self.browser.clearHistory() try: mfrom = message['From'] mto = message['To'] except Exception: self.browser.insertPlainText('Invalid message') return senderContact, recpContact = None, None try: sender = bmAddressExtract(mfrom) recp = bmAddressExtract(mto) senderContact = await database.bmContactByAddr(sender) recpContact = await database.bmContactByAddr(recp) except Exception: # Invalid BM addrs ? self.browser.insertPlainText('Invalid message') return senderName = senderContact.fullname if senderContact else sender recpName = recpContact.fullname if recpContact else recp subject = message.get('Subject') date = message.get('Date') self.browser.insertHtml( f'<p><b>From</b>: ' f'<a href="mailto: {sender}@bitmessage">{senderName}</a></p>\n') self.browser.insertHtml('<br />') self.browser.insertHtml( f'<p><b>To</b>: ' f'<a href="mailto: {recp}@bitmessage">{recpName}</a></p>\n') self.browser.insertHtml('<br />') if subject: self.browser.insertHtml(f"<p><b>Subject</b>: {subject}</p>\n") self.browser.insertHtml('<br />') if date: self.browser.insertHtml(f"<p><b>Date</b>: {date}</p>\n") self.browser.insertHtml('<br />') self.browser.insertHtml('<br />') for part in message.walk(): try: # contentType = message.get_content_type() # contentTypeParams = message.get_params() # Assume markdown markupType = message.get_param('markup', failobj='markdown') payload = part.get_payload() if markupType == 'markdown': self.browser.insertHtml(markitdown(payload)) self.browser.insertHtml('<br />') else: self.browser.insertPlainText(payload) except Exception: continue self.curMessage = message self.ui.replyButton.setEnabled(True)