{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n------=_Part_4200734_24778174.1344608186754--\n\"\"\"\n\nMAIL_TEMPLATE_PLAINTEXT = \"\"\"Return-Path: \nTo: {to}\nReceived: by mail1.openerp.com (Postfix, from userid 10002)\n id 5DF9ABFB2A; Fri, 10 Aug 2012 16:16:39 +0200 (CEST)\nFrom: Sylvie Lelitre \nSubject: {subject}\nMIME-Version: 1.0\nContent-Type: text/plain\nDate: Fri, 10 Aug 2012 14:16:26 +0000\nMessage-ID: {msg_id}\n{extra}\n\nPlease call me as soon as possible this afternoon!\n\n--\nSylvie\n\"\"\"\n\nMAIL_MULTIPART_MIXED = \"\"\"Return-Path: \nX-Original-To: raoul@grosbedon.fr\nDelivered-To: raoul@grosbedon.fr\nReceived: by mail1.grosbedon.com (Postfix, from userid 10002)\n id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)\nX-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on mail1.grosbedon.com\nX-Spam-Level: \nX-Spam-Status: No, score=-2.6 required=5.0 tests=BAYES_00,FREEMAIL_FROM,\n HTML_MESSAGE,RCVD_IN_DNSWL_LOW autolearn=unavailable version=3.3.1\nReceived: from mail-ie0-f173.google.com (mail-ie0-f173.google.com [209.85.223.173])\n by mail1.grosbedon.com (Postfix) with ESMTPS id 9BBD7BFAAA\n for ; Fri, 23 Aug 2013 13:17:55 +0200 (CEST)\nReceived: by mail-ie0-f173.google.com with SMTP id qd12so575130ieb.4\n for ; Fri, 23 Aug 2013 04:17:54 -0700 (PDT)\nDKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;\n d=gmail.com; s=20120113;\n h=mime-version:date:message-id:subject:from:to:content-type;\n bh=dMNHV52EC7GAa7+9a9tqwT9joy9z+1950J/3A6/M/hU=;\n b=DGuv0VjegdSrEe36ADC8XZ9Inrb3Iu+3/52Bm+caltddXFH9yewTr0JkCRQaJgMwG9\n qXTQgP8qu/VFEbCh6scu5ZgU1hknzlNCYr3LT+Ih7dAZVUEHUJdwjzUU1LFV95G2RaCd\n /Lwff6CibuUvrA+0CBO7IRKW0Sn5j0mukYu8dbaKsm6ou6HqS8Nuj85fcXJfHSHp6Y9u\n dmE8jBh3fHCHF/nAvU+8aBNSIzl1FGfiBYb2jCoapIuVFitKR4q5cuoodpkH9XqqtOdH\n DG+YjEyi8L7uvdOfN16eMr7hfUkQei1yQgvGu9/5kXoHg9+Gx6VsZIycn4zoaXTV3Nhn\n nu4g==\nMIME-Version: 1.0\nX-Received: by 10.50.124.65 with SMTP id mg1mr1144467igb.43.1377256674216;\n Fri, 23 Aug 2013 04:17:54 -0700 (PDT)\nReceived: by 10.43.99.71 with HTTP; Fri, 23 Aug 2013 04:17:54 -0700 (PDT)\nDate: Fri, 23 Aug 2013 13:17:54 +0200\nMessage-ID: \nSubject: Test mail multipart/mixed\nFrom: =?ISO-8859-1?Q?Raoul Grosbedon=E9e?= \nTo: Followers of ASUSTeK-Joseph-Walters \nContent-Type: multipart/mixed; boundary=089e01536c4ed4d17204e49b8e96\n\n--089e01536c4ed4d17204e49b8e96\nContent-Type: multipart/alternative; boundary=089e01536c4ed4d16d04e49b8e94\n\n--089e01536c4ed4d16d04e49b8e94\nContent-Type: text/plain; charset=ISO-8859-1\n\nShould create a multipart/mixed: from gmail, *bold*, with attachment.\n\n-- \nMarcel Boitempoils.\n\n--089e01536c4ed4d16d04e49b8e94\nContent-Type: text/html; charset=ISO-8859-1\n\n
Should create a multipart/mixed: from gmail, bold, with attachment.

--
Marcel Boitempoils.
\n\n--089e01536c4ed4d16d04e49b8e94--\n--089e01536c4ed4d17204e49b8e96\nContent-Type: text/plain; charset=US-ASCII; name=\"test.txt\"\nContent-Disposition: attachment; filename=\"test.txt\"\nContent-Transfer-Encoding: base64\nX-Attachment-Id: f_hkpb27k00\n\ndGVzdAo=\n--089e01536c4ed4d17204e49b8e96--\"\"\"\n\nMAIL_MULTIPART_MIXED_TWO = \"\"\"X-Original-To: raoul@grosbedon.fr\nDelivered-To: raoul@grosbedon.fr\nReceived: by mail1.grosbedon.com (Postfix, from userid 10002)\n id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)\nFrom: \"Bruce Wayne\" \nContent-Type: multipart/alternative;\n boundary=\"Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227\"\nMessage-Id: <6BB1FAB2-2104-438E-9447-07AE2C8C4A92@sexample.com>\nMime-Version: 1.0 (Mac OS X Mail 7.3 \\(1878.6\\))\n\n--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227\nContent-Transfer-Encoding: 7bit\nContent-Type: text/plain;\n charset=us-ascii\n\nFirst and second part\n\n--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227\nContent-Type: multipart/mixed;\n boundary=\"Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F\"\n\n--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F\nContent-Transfer-Encoding: 7bit\nContent-Type: text/html;\n charset=us-ascii\n\nFirst part\n\n--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F\nContent-Disposition: inline;\n filename=thetruth.pdf\nContent-Type: application/pdf;\n name=\"thetruth.pdf\"\nContent-Transfer-Encoding: base64\n\nSSBhbSB0aGUgQmF0TWFuCg==\n\n--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F\nContent-Transfer-Encoding: 7bit\nContent-Type: text/html;\n charset=us-ascii\n\nSecond part\n--Apple-Mail=_CA6C687E-6AA0-411E-B0FE-F0ABB4CFED1F--\n\n--Apple-Mail=_9331E12B-8BD2-4EC7-B53E-01F3FBEC9227--\n\"\"\"\n\nclass TestMailgateway(TestMail):\n\n def test_00_message_parse(self):\n \"\"\" Testing incoming emails parsing \"\"\"\n cr, uid = self.cr, self.uid\n\n res = self.mail_thread.message_parse(cr, uid, MAIL_TEMPLATE_PLAINTEXT)\n self.assertIn('Please call me as soon as possible this afternoon!', res.get('body', ''),\n 'message_parse: missing text in text/plain body after parsing')\n\n res = self.mail_thread.message_parse(cr, uid, MAIL_TEMPLATE)\n self.assertIn('

Please call me as soon as possible this afternoon!

', res.get('body', ''),\n 'message_parse: missing html in multipart/alternative body after parsing')\n\n res = self.mail_thread.message_parse(cr, uid, MAIL_MULTIPART_MIXED)\n self.assertNotIn('Should create a multipart/mixed: from gmail, *bold*, with attachment', res.get('body', ''),\n 'message_parse: text version should not be in body after parsing multipart/mixed')\n self.assertIn('
Should create a multipart/mixed: from gmail, bold, with attachment.

', res.get('body', ''),\n 'message_parse: html version should be in body after parsing multipart/mixed')\n\n res = self.mail_thread.message_parse(cr, uid, MAIL_MULTIPART_MIXED_TWO)\n self.assertNotIn('First and second part', res.get('body', ''),\n 'message_parse: text version should not be in body after parsing multipart/mixed')\n self.assertIn('First part', res.get('body', ''),\n 'message_parse: first part of the html version should be in body after parsing multipart/mixed')\n self.assertIn('Second part', res.get('body', ''),\n 'message_parse: second part of the html version should be in body after parsing multipart/mixed')\n\n @mute_logger('openerp.addons.mail.mail_thread', 'openerp.models')\n def test_10_message_process(self):\n \"\"\" Testing incoming emails processing. \"\"\"\n cr, uid, user_raoul = self.cr, self.uid, self.user_raoul\n\n def format_and_process(template, to='groups@example.com, other@gmail.com', subject='Frogs',\n extra='', email_from='Sylvie Lelitre ',\n msg_id='<1198923581.41972151344608186760.JavaMail@agrolait.com>',\n model=None):\n self.assertEqual(self.mail_group.search(cr, uid, [('name', '=', subject)]), [])\n mail = template.format(to=to, subject=subject, extra=extra, email_from=email_from, msg_id=msg_id)\n self.mail_thread.message_process(cr, uid, model, mail)\n return self.mail_group.search(cr, uid, [('name', '=', subject)])\n\n # --------------------------------------------------\n # Data creation\n # --------------------------------------------------\n\n # groups@.. will cause the creation of new mail groups\n self.mail_group_model_id = self.ir_model.search(cr, uid, [('model', '=', 'mail.group')])[0]\n alias_id = self.mail_alias.create(cr, uid, {\n 'alias_name': 'groups',\n 'alias_user_id': False,\n 'alias_model_id': self.mail_group_model_id,\n 'alias_parent_model_id': self.mail_group_model_id,\n 'alias_parent_thread_id': self.group_pigs_id,\n 'alias_contact': 'everyone'})\n\n # --------------------------------------------------\n # Test1: new record creation\n # --------------------------------------------------\n\n # Do: incoming mail from an unknown partner on an alias creates a new mail_group \"frogs\"\n self._init_mock_build_email()\n frog_groups = format_and_process(MAIL_TEMPLATE, to='groups@example.com, other@gmail.com')\n sent_emails = self._build_email_kwargs_list\n # Test: one group created by mailgateway administrator\n self.assertEqual(len(frog_groups), 1, 'message_process: a new mail.group should have been created')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n res = self.mail_group.get_metadata(cr, uid, [frog_group.id])[0].get('create_uid') or [None]\n self.assertEqual(res[0], uid,\n 'message_process: group should have been created by uid as alias_user__id is False on the alias')\n # Test: one message that is the incoming email\n self.assertEqual(len(frog_group.message_ids), 1,\n 'message_process: newly created group should have the incoming email in message_ids')\n msg = frog_group.message_ids[0]\n self.assertEqual('Frogs', msg.subject,\n 'message_process: newly created group should have the incoming email as first message')\n self.assertIn('Please call me as soon as possible this afternoon!', msg.body,\n 'message_process: newly created group should have the incoming email as first message')\n self.assertEqual('email', msg.type,\n 'message_process: newly created group should have an email as first message')\n self.assertEqual('Discussions', msg.subtype_id.name,\n 'message_process: newly created group should not have a log first message but an email')\n # Test: message: unknown email address -> message has email_from, not author_id\n self.assertFalse(msg.author_id,\n 'message_process: message on created group should not have an author_id')\n self.assertIn('test.sylvie.lelitre@agrolait.com', msg.email_from,\n 'message_process: message on created group should have an email_from')\n # Test: followers: nobody\n self.assertEqual(len(frog_group.message_follower_ids), 0, 'message_process: newly create group should not have any follower')\n # Test: sent emails: no-one\n self.assertEqual(len(sent_emails), 0,\n 'message_process: should create emails without any follower added')\n # Data: unlink group\n frog_group.unlink()\n\n # Do: incoming email from an unknown partner on a Partners only alias -> bounce\n self._init_mock_build_email()\n self.mail_alias.write(cr, uid, [alias_id], {'alias_contact': 'partners'})\n frog_groups = format_and_process(MAIL_TEMPLATE, to='groups@example.com, other2@gmail.com')\n # Test: no group created\n self.assertTrue(len(frog_groups) == 0)\n # Test: email bounced\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 1,\n 'message_process: incoming email on Partners alias should send a bounce email')\n self.assertIn('Frogs', sent_emails[0].get('subject'),\n 'message_process: bounce email on Partners alias should contain the original subject')\n self.assertIn('test.sylvie.lelitre@agrolait.com', sent_emails[0].get('email_to'),\n 'message_process: bounce email on Partners alias should have original email sender as recipient')\n\n # Do: incoming email from an unknown partner on a Followers only alias -> bounce\n self._init_mock_build_email()\n self.mail_alias.write(cr, uid, [alias_id], {'alias_contact': 'followers'})\n frog_groups = format_and_process(MAIL_TEMPLATE, to='groups@example.com, other3@gmail.com')\n # Test: no group created\n self.assertTrue(len(frog_groups) == 0)\n # Test: email bounced\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 1,\n 'message_process: incoming email on Followers alias should send a bounce email')\n self.assertIn('Frogs', sent_emails[0].get('subject'),\n 'message_process: bounce email on Followers alias should contain the original subject')\n self.assertIn('test.sylvie.lelitre@agrolait.com', sent_emails[0].get('email_to'),\n 'message_process: bounce email on Followers alias should have original email sender as recipient')\n\n # Do: incoming email from a known partner on a Partners alias -> ok (+ test on alias.user_id)\n self.mail_alias.write(cr, uid, [alias_id], {'alias_user_id': self.user_raoul_id, 'alias_contact': 'partners'})\n p1id = self.res_partner.create(cr, uid, {'name': 'Sylvie Lelitre', 'email': 'test.sylvie.lelitre@agrolait.com'})\n p2id = self.res_partner.create(cr, uid, {'name': 'Other Poilvache', 'email': 'other4@gmail.com'})\n self._init_mock_build_email()\n frog_groups = format_and_process(MAIL_TEMPLATE, to='groups@example.com, other4@gmail.com')\n sent_emails = self._build_email_kwargs_list\n # Test: one group created by Raoul\n self.assertEqual(len(frog_groups), 1, 'message_process: a new mail.group should have been created')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n res = self.mail_group.get_metadata(cr, uid, [frog_group.id])[0].get('create_uid') or [None]\n self.assertEqual(res[0], self.user_raoul_id,\n 'message_process: group should have been created by alias_user_id')\n # Test: one message that is the incoming email\n self.assertEqual(len(frog_group.message_ids), 1,\n 'message_process: newly created group should have the incoming email in message_ids')\n msg = frog_group.message_ids[0]\n # Test: message: author found\n self.assertEqual(p1id, msg.author_id.id,\n 'message_process: message on created group should have Sylvie as author_id')\n self.assertIn('Sylvie Lelitre ', msg.email_from,\n 'message_process: message on created group should have have an email_from')\n # Test: author (not recipient and not Raoul (as alias owner)) added as follower\n frog_follower_ids = set([p.id for p in frog_group.message_follower_ids])\n self.assertEqual(frog_follower_ids, set([p1id]),\n 'message_process: newly created group should have 1 follower (author, not creator, not recipients)')\n # Test: sent emails: no-one, no bounce effet\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 0,\n 'message_process: should not bounce incoming emails')\n # Data: unlink group\n frog_group.unlink()\n\n # Do: incoming email from a not follower Partner on a Followers only alias -> bounce\n self._init_mock_build_email()\n self.mail_alias.write(cr, uid, [alias_id], {'alias_user_id': False, 'alias_contact': 'followers'})\n frog_groups = format_and_process(MAIL_TEMPLATE, to='groups@example.com, other5@gmail.com')\n # Test: no group created\n self.assertTrue(len(frog_groups) == 0)\n # Test: email bounced\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 1,\n 'message_process: incoming email on Partners alias should send a bounce email')\n\n # Do: incoming email from a parent document follower on a Followers only alias -> ok\n self._init_mock_build_email()\n self.mail_group.message_subscribe(cr, uid, [self.group_pigs_id], [p1id])\n frog_groups = format_and_process(MAIL_TEMPLATE, to='groups@example.com, other6@gmail.com')\n # Test: one group created by Raoul (or Sylvie maybe, if we implement it)\n self.assertEqual(len(frog_groups), 1, 'message_process: a new mail.group should have been created')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: one message that is the incoming email\n self.assertEqual(len(frog_group.message_ids), 1,\n 'message_process: newly created group should have the incoming email in message_ids')\n # Test: author (and not recipient) added as follower\n frog_follower_ids = set([p.id for p in frog_group.message_follower_ids])\n self.assertEqual(frog_follower_ids, set([p1id]),\n 'message_process: newly created group should have 1 follower (author, not creator, not recipients)')\n # Test: sent emails: no-one, no bounce effet\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 0,\n 'message_process: should not bounce incoming emails')\n\n # --------------------------------------------------\n # Test2: update-like alias\n # --------------------------------------------------\n\n # Do: Pigs alias is restricted, should bounce\n self._init_mock_build_email()\n self.mail_group.write(cr, uid, [frog_group.id], {'alias_name': 'frogs', 'alias_contact': 'followers', 'alias_force_thread_id': frog_group.id})\n frog_groups = format_and_process(MAIL_TEMPLATE, email_from='other4@gmail.com',\n msg_id='<1198923581.41972151344608186760.JavaMail.diff1@agrolait.com>',\n to='frogs@example.com>', subject='Re: news')\n # Test: no group 'Re: news' created, still only 1 Frogs group\n self.assertEqual(len(frog_groups), 0,\n 'message_process: reply on Frogs should not have created a new group with new subject')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n self.assertEqual(len(frog_groups), 1,\n 'message_process: reply on Frogs should not have created a duplicate group with old subject')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: email bounced\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 1,\n 'message_process: incoming email on Followers alias should send a bounce email')\n self.assertIn('Re: news', sent_emails[0].get('subject'),\n 'message_process: bounce email on Followers alias should contain the original subject')\n\n # Do: Pigs alias is restricted, should accept Followers\n self._init_mock_build_email()\n self.mail_group.message_subscribe(cr, uid, [frog_group.id], [p2id])\n frog_groups = format_and_process(MAIL_TEMPLATE, email_from='other4@gmail.com',\n msg_id='<1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>',\n to='frogs@example.com>', subject='Re: cats')\n # Test: no group 'Re: news' created, still only 1 Frogs group\n self.assertEqual(len(frog_groups), 0,\n 'message_process: reply on Frogs should not have created a new group with new subject')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n self.assertEqual(len(frog_groups), 1,\n 'message_process: reply on Frogs should not have created a duplicate group with old subject')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: one new message\n self.assertEqual(len(frog_group.message_ids), 2, 'message_process: group should contain 2 messages after reply')\n # Test: sent emails: 1 (Sylvie copy of the incoming email, but no bounce)\n sent_emails = self._build_email_kwargs_list\n self.assertEqual(len(sent_emails), 1,\n 'message_process: one email should have been generated')\n self.assertIn('test.sylvie.lelitre@agrolait.com', sent_emails[0].get('email_to')[0],\n 'message_process: email should be sent to Sylvie')\n self.mail_group.message_unsubscribe(cr, uid, [frog_group.id], [p2id])\n\n # --------------------------------------------------\n # Test3: discussion and replies\n # --------------------------------------------------\n\n # Do: even with a wrong destination, a reply should end up in the correct thread\n frog_groups = format_and_process(MAIL_TEMPLATE, email_from='other4@gmail.com',\n msg_id='<1198923581.41972151344608186760.JavaMail.diff1@agrolait.com>',\n to='erroneous@example.com>', subject='Re: news',\n extra='In-Reply-To: <1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>\\n')\n # Test: no group 'Re: news' created, still only 1 Frogs group\n self.assertEqual(len(frog_groups), 0,\n 'message_process: reply on Frogs should not have created a new group with new subject')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n self.assertEqual(len(frog_groups), 1,\n 'message_process: reply on Frogs should not have created a duplicate group with old subject')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: one new message\n self.assertEqual(len(frog_group.message_ids), 3, 'message_process: group should contain 3 messages after reply')\n # Test: author (and not recipient) added as follower\n frog_follower_ids = set([p.id for p in frog_group.message_follower_ids])\n self.assertEqual(frog_follower_ids, set([p1id, p2id]),\n 'message_process: after reply, group should have 2 followers')\n\n # Do: incoming email with ref holding model / res_id but that does not match any message in the thread: must raise since OpenERP saas-3\n self.assertRaises(ValueError,\n format_and_process,\n MAIL_TEMPLATE, email_from='other5@gmail.com',\n to='noone@example.com', subject='spam',\n extra='In-Reply-To: <12321321-openerp-%d-mail.group@example.com>' % frog_group.id,\n msg_id='<1.1.JavaMail.new@agrolait.com>')\n\n # When 6.1 messages are present, compat mode is available\n # Create a fake 6.1 message\n tmp_msg_id = self.mail_message.create(cr, uid, {'model': 'mail.group', 'res_id': frog_group.id})\n self.mail_message.write(cr, uid, [tmp_msg_id], {'message_id': False})\n # Do: compat mode accepts partial-matching emails\n frog_groups = format_and_process(MAIL_TEMPLATE, email_from='other5@gmail.com',\n msg_id='<1.2.JavaMail.new@agrolait.com>',\n to='noone@example.com>', subject='spam',\n extra='In-Reply-To: <12321321-openerp-%d-mail.group@%s>' % (frog_group.id, socket.gethostname()))\n self.mail_message.unlink(cr, uid, [tmp_msg_id])\n # Test: no group 'Re: news' created, still only 1 Frogs group\n self.assertEqual(len(frog_groups), 0,\n 'message_process: reply on Frogs should not have created a new group with new subject')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n self.assertEqual(len(frog_groups), 1,\n 'message_process: reply on Frogs should not have created a duplicate group with old subject')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: one new message\n self.assertEqual(len(frog_group.message_ids), 4, 'message_process: group should contain 4 messages after reply')\n\n # 6.1 compat mode should not work if hostname does not match!\n tmp_msg_id = self.mail_message.create(cr, uid, {'model': 'mail.group', 'res_id': frog_group.id})\n self.mail_message.write(cr, uid, [tmp_msg_id], {'message_id': False})\n self.assertRaises(ValueError,\n format_and_process,\n MAIL_TEMPLATE, email_from='other5@gmail.com',\n msg_id='<1.3.JavaMail.new@agrolait.com>',\n to='noone@example.com>', subject='spam',\n extra='In-Reply-To: <12321321-openerp-%d-mail.group@neighbor.com>' % frog_group.id)\n self.mail_message.unlink(cr, uid, [tmp_msg_id])\n\n\n # Do: due to some issue, same email goes back into the mailgateway\n frog_groups = format_and_process(MAIL_TEMPLATE, email_from='other4@gmail.com',\n msg_id='<1198923581.41972151344608186760.JavaMail.diff1@agrolait.com>',\n subject='Re: news', extra='In-Reply-To: <1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>\\n')\n # Test: no group 'Re: news' created, still only 1 Frogs group\n self.assertEqual(len(frog_groups), 0,\n 'message_process: reply on Frogs should not have created a new group with new subject')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n self.assertEqual(len(frog_groups), 1,\n 'message_process: reply on Frogs should not have created a duplicate group with old subject')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: no new message\n self.assertEqual(len(frog_group.message_ids), 4, 'message_process: message with already existing message_id should not have been duplicated')\n # Test: message_id is still unique\n msg_ids = self.mail_message.search(cr, uid, [('message_id', 'ilike', '<1198923581.41972151344608186760.JavaMail.diff1@agrolait.com>')])\n self.assertEqual(len(msg_ids), 1,\n 'message_process: message with already existing message_id should not have been duplicated')\n\n # --------------------------------------------------\n # Test4: email_from and partner finding\n # --------------------------------------------------\n\n # Data: extra partner with Raoul's email -> test the 'better author finding'\n extra_partner_id = self.res_partner.create(cr, uid, {'name': 'A-Raoul', 'email': 'test_raoul@email.com'})\n\n # Do: post a new message, with a known partner -> duplicate emails -> partner\n format_and_process(MAIL_TEMPLATE, email_from='Lombrik Lubrik ',\n subject='Re: news (2)',\n msg_id='<1198923581.41972151344608186760.JavaMail.new1@agrolait.com>',\n extra='In-Reply-To: <1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: author is A-Raoul (only existing)\n self.assertEqual(frog_group.message_ids[0].author_id.id, extra_partner_id,\n 'message_process: email_from -> author_id wrong')\n\n # Do: post a new message with a non-existant email that is a substring of a partner email\n format_and_process(MAIL_TEMPLATE, email_from='Not really Lombrik Lubrik ',\n subject='Re: news (2)',\n msg_id='',\n extra='In-Reply-To: <1198923581.41972151344608186760.JavaMail@agrolait.com>\\n')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: author must not be set, otherwise the system is confusing different users\n self.assertFalse(frog_group.message_ids[0].author_id, 'message_process: email_from -> mismatching author_id')\n\n # Do: post a new message, with a known partner -> duplicate emails -> user\n frog_group.message_unsubscribe([extra_partner_id])\n self.res_users.write(cr, uid, self.user_raoul_id, {'email': 'test_raoul@email.com'})\n format_and_process(MAIL_TEMPLATE, email_from='Lombrik Lubrik ',\n to='groups@example.com', subject='Re: news (3)',\n msg_id='<1198923581.41972151344608186760.JavaMail.new2@agrolait.com>',\n extra='In-Reply-To: <1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: author is Raoul (user), not A-Raoul\n self.assertEqual(frog_group.message_ids[0].author_id.id, self.partner_raoul_id,\n 'message_process: email_from -> author_id wrong')\n\n # Do: post a new message, with a known partner -> duplicate emails -> partner because is follower\n frog_group.message_unsubscribe([self.partner_raoul_id])\n frog_group.message_subscribe([extra_partner_id])\n raoul_email = self.user_raoul.email\n self.res_users.write(cr, uid, self.user_raoul_id, {'email': 'test_raoul@email.com'})\n format_and_process(MAIL_TEMPLATE, email_from='Lombrik Lubrik ',\n to='groups@example.com', subject='Re: news (3)',\n msg_id='<1198923581.41972151344608186760.JavaMail.new3@agrolait.com>',\n extra='In-Reply-To: <1198923581.41972151344608186799.JavaMail.diff1@agrolait.com>')\n frog_groups = self.mail_group.search(cr, uid, [('name', '=', 'Frogs')])\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n # Test: author is Raoul (user), not A-Raoul\n self.assertEqual(frog_group.message_ids[0].author_id.id, extra_partner_id,\n 'message_process: email_from -> author_id wrong')\n\n self.res_users.write(cr, uid, self.user_raoul_id, {'email': raoul_email})\n\n # --------------------------------------------------\n # Test5: misc gateway features\n # --------------------------------------------------\n\n # Do: incoming email with model that does not accepts incoming emails must raise\n self.assertRaises(ValueError,\n format_and_process,\n MAIL_TEMPLATE,\n to='noone@example.com', subject='spam', extra='', model='res.country',\n msg_id='<1198923581.41972151344608186760.JavaMail.new4@agrolait.com>')\n\n # Do: incoming email without model and without alias must raise\n self.assertRaises(ValueError,\n format_and_process,\n MAIL_TEMPLATE,\n to='noone@example.com', subject='spam', extra='',\n msg_id='<1198923581.41972151344608186760.JavaMail.new5@agrolait.com>')\n\n # Do: incoming email with model that accepting incoming emails as fallback\n frog_groups = format_and_process(MAIL_TEMPLATE,\n to='noone@example.com',\n subject='Spammy', extra='', model='mail.group',\n msg_id='<1198923581.41972151344608186760.JavaMail.new6@agrolait.com>')\n self.assertEqual(len(frog_groups), 1,\n 'message_process: erroneous email but with a fallback model should have created a new mail.group')\n\n # Do: incoming email in plaintext should be stored as html\n frog_groups = format_and_process(MAIL_TEMPLATE_PLAINTEXT,\n to='groups@example.com', subject='Frogs Return', extra='',\n msg_id='')\n # Test: one group created with one message\n self.assertEqual(len(frog_groups), 1, 'message_process: a new mail.group should have been created')\n frog_group = self.mail_group.browse(cr, uid, frog_groups[0])\n msg = frog_group.message_ids[0]\n # Test: plain text content should be wrapped and stored as html\n self.assertIn('
\\nPlease call me as soon as possible this afternoon!\\n\\n--\\nSylvie\\n
', msg.body,\n 'message_process: plaintext incoming email incorrectly parsed')\n\n @mute_logger('openerp.addons.mail.mail_thread', 'openerp.models')\n def test_20_thread_parent_resolution(self):\n \"\"\" Testing parent/child relationships are correctly established when processing incoming mails \"\"\"\n cr, uid = self.cr, self.uid\n\n def format(template, to='Pretty Pigs , other@gmail.com', subject='Re: 1',\n extra='', email_from='Sylvie Lelitre ',\n msg_id='<1198923581.41972151344608186760.JavaMail@agrolait.com>'):\n return template.format(to=to, subject=subject, extra=extra, email_from=email_from, msg_id=msg_id)\n\n group_pigs = self.mail_group.browse(cr, uid, self.group_pigs_id)\n msg1 = group_pigs.message_post(body='My Body', subject='1')\n msg2 = group_pigs.message_post(body='My Body', subject='2')\n msg1, msg2 = self.mail_message.browse(cr, uid, [msg1, msg2])\n self.assertTrue(msg1.message_id, \"message_process: new message should have a proper message_id\")\n\n # Reply to msg1, make sure the reply is properly attached using the various reply identification mechanisms\n # 0. Direct alias match\n reply_msg1 = format(MAIL_TEMPLATE, to='Pretty Pigs ',\n extra='In-Reply-To: %s' % msg1.message_id,\n msg_id='<1198923581.41972151344608186760.JavaMail.2@agrolait.com>')\n self.mail_group.message_process(cr, uid, None, reply_msg1)\n\n # 1. In-Reply-To header\n reply_msg2 = format(MAIL_TEMPLATE, to='erroneous@example.com',\n extra='In-Reply-To: %s' % msg1.message_id,\n msg_id='<1198923581.41972151344608186760.JavaMail.3@agrolait.com>')\n self.mail_group.message_process(cr, uid, None, reply_msg2)\n\n # 2. References header\n reply_msg3 = format(MAIL_TEMPLATE, to='erroneous@example.com',\n extra='References: <2233@a.com>\\r\\n\\t<3edss_dsa@b.com> %s' % msg1.message_id,\n msg_id='<1198923581.41972151344608186760.JavaMail.4@agrolait.com>')\n self.mail_group.message_process(cr, uid, None, reply_msg3)\n\n # 3. Subject contains [] + model passed to message+process -> only attached to group, but not to mail (not in msg1.child_ids)\n reply_msg4 = format(MAIL_TEMPLATE, to='erroneous@example.com',\n extra='', subject='Re: [%s] 1' % self.group_pigs_id,\n msg_id='<1198923581.41972151344608186760.JavaMail.5@agrolait.com>')\n self.mail_group.message_process(cr, uid, 'mail.group', reply_msg4)\n\n group_pigs.refresh()\n msg1.refresh()\n self.assertEqual(6, len(group_pigs.message_ids), 'message_process: group should contain 6 messages')\n self.assertEqual(3, len(msg1.child_ids), 'message_process: msg1 should have 3 children now')\n\n def test_30_private_discussion(self):\n \"\"\" Testing private discussion between partners. \"\"\"\n cr, uid = self.cr, self.uid\n\n def format(template, to='Pretty Pigs , other@gmail.com', subject='Re: 1',\n extra='', email_from='Sylvie Lelitre ',\n msg_id='<1198923581.41972151344608186760.JavaMail@agrolait.com>'):\n return template.format(to=to, subject=subject, extra=extra, email_from=email_from, msg_id=msg_id)\n\n # Do: Raoul writes to Bert and Administrator, with a thread_model in context that should not be taken into account\n msg1_pids = [self.partner_admin_id, self.partner_bert_id]\n msg1_id = self.mail_thread.message_post(\n cr, self.user_raoul_id, False,\n partner_ids=msg1_pids,\n subtype='mail.mt_comment',\n context={'thread_model': 'mail.group'}\n )\n\n # Test: message recipients\n msg = self.mail_message.browse(cr, uid, msg1_id)\n msg_pids = [p.id for p in msg.partner_ids]\n msg_nids = [p.id for p in msg.notified_partner_ids]\n test_pids = msg1_pids\n test_nids = msg1_pids\n self.assertEqual(set(msg_pids), set(test_pids),\n 'message_post: private discussion: incorrect recipients')\n self.assertEqual(set(msg_nids), set(test_nids),\n 'message_post: private discussion: incorrect notified recipients')\n self.assertEqual(msg.model, False,\n 'message_post: private discussion: context key \"thread_model\" not correctly ignored when having no res_id')\n # Test: message-id\n self.assertIn('openerp-private', msg.message_id,\n 'message_post: private discussion: message-id should contain the private keyword')\n\n # Do: Bert replies through mailgateway (is a customer)\n reply_message = format(MAIL_TEMPLATE, to='not_important@mydomain.com',\n email_from='bert@bert.fr',\n extra='In-Reply-To: %s' % msg.message_id,\n msg_id='')\n self.mail_thread.message_process(cr, uid, None, reply_message)\n\n # Test: last mail_message created\n msg2_id = self.mail_message.search(cr, uid, [], limit=1)[0]\n\n # Test: message recipients\n msg = self.mail_message.browse(cr, uid, msg2_id)\n msg_pids = [p.id for p in msg.partner_ids]\n msg_nids = [p.id for p in msg.notified_partner_ids]\n test_pids = [self.partner_admin_id, self.partner_raoul_id]\n test_nids = test_pids\n self.assertEqual(msg.author_id.id, self.partner_bert_id,\n 'message_post: private discussion: wrong author through mailgatewya based on email')\n self.assertEqual(set(msg_pids), set(test_pids),\n 'message_post: private discussion: incorrect recipients when replying')\n self.assertEqual(set(msg_nids), set(test_nids),\n 'message_post: private discussion: incorrect notified recipients when replying')\n\n # Do: Bert replies through chatter (is a customer)\n msg3_id = self.mail_thread.message_post(\n cr, uid, False,\n author_id=self.partner_bert_id,\n parent_id=msg1_id, subtype='mail.mt_comment')\n\n # Test: message recipients\n msg = self.mail_message.browse(cr, uid, msg3_id)\n msg_pids = [p.id for p in msg.partner_ids]\n msg_nids = [p.id for p in msg.notified_partner_ids]\n test_pids = [self.partner_admin_id, self.partner_raoul_id]\n test_nids = test_pids\n self.assertEqual(set(msg_pids), set(test_pids),\n 'message_post: private discussion: incorrect recipients when replying')\n self.assertEqual(set(msg_nids), set(test_nids),\n 'message_post: private discussion: incorrect notified recipients when replying')\n\n # Do: Administrator replies\n msg3_id = self.mail_thread.message_post(cr, uid, False, parent_id=msg3_id, subtype='mail.mt_comment')\n\n # Test: message recipients\n msg = self.mail_message.browse(cr, uid, msg3_id)\n msg_pids = [p.id for p in msg.partner_ids]\n msg_nids = [p.id for p in msg.notified_partner_ids]\n test_pids = [self.partner_bert_id, self.partner_raoul_id]\n test_nids = test_pids\n self.assertEqual(set(msg_pids), set(test_pids),\n 'message_post: private discussion: incorrect recipients when replying')\n self.assertEqual(set(msg_nids), set(test_nids),\n 'message_post: private discussion: incorrect notified recipients when replying')\n"},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":6799802151477369000,"string":"6,799,802,151,477,369,000"},"line_mean":{"kind":"number","value":57.352303523,"string":"57.352304"},"line_max":{"kind":"number","value":166,"string":"166"},"alpha_frac":{"kind":"number","value":0.6217954672,"string":"0.621795"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":933,"cells":{"repo_name":{"kind":"string","value":"DxCx/nzbToMedia"},"path":{"kind":"string","value":"libs/unidecode/x097.py"},"copies":{"kind":"string","value":"252"},"size":{"kind":"string","value":"4643"},"content":{"kind":"string","value":"data = (\n'Xu ', # 0x00\n'Ji ', # 0x01\n'Mu ', # 0x02\n'Chen ', # 0x03\n'Xiao ', # 0x04\n'Zha ', # 0x05\n'Ting ', # 0x06\n'Zhen ', # 0x07\n'Pei ', # 0x08\n'Mei ', # 0x09\n'Ling ', # 0x0a\n'Qi ', # 0x0b\n'Chou ', # 0x0c\n'Huo ', # 0x0d\n'Sha ', # 0x0e\n'Fei ', # 0x0f\n'Weng ', # 0x10\n'Zhan ', # 0x11\n'Yin ', # 0x12\n'Ni ', # 0x13\n'Chou ', # 0x14\n'Tun ', # 0x15\n'Lin ', # 0x16\n'[?] ', # 0x17\n'Dong ', # 0x18\n'Ying ', # 0x19\n'Wu ', # 0x1a\n'Ling ', # 0x1b\n'Shuang ', # 0x1c\n'Ling ', # 0x1d\n'Xia ', # 0x1e\n'Hong ', # 0x1f\n'Yin ', # 0x20\n'Mo ', # 0x21\n'Mai ', # 0x22\n'Yun ', # 0x23\n'Liu ', # 0x24\n'Meng ', # 0x25\n'Bin ', # 0x26\n'Wu ', # 0x27\n'Wei ', # 0x28\n'Huo ', # 0x29\n'Yin ', # 0x2a\n'Xi ', # 0x2b\n'Yi ', # 0x2c\n'Ai ', # 0x2d\n'Dan ', # 0x2e\n'Deng ', # 0x2f\n'Xian ', # 0x30\n'Yu ', # 0x31\n'Lu ', # 0x32\n'Long ', # 0x33\n'Dai ', # 0x34\n'Ji ', # 0x35\n'Pang ', # 0x36\n'Yang ', # 0x37\n'Ba ', # 0x38\n'Pi ', # 0x39\n'Wei ', # 0x3a\n'[?] ', # 0x3b\n'Xi ', # 0x3c\n'Ji ', # 0x3d\n'Mai ', # 0x3e\n'Meng ', # 0x3f\n'Meng ', # 0x40\n'Lei ', # 0x41\n'Li ', # 0x42\n'Huo ', # 0x43\n'Ai ', # 0x44\n'Fei ', # 0x45\n'Dai ', # 0x46\n'Long ', # 0x47\n'Ling ', # 0x48\n'Ai ', # 0x49\n'Feng ', # 0x4a\n'Li ', # 0x4b\n'Bao ', # 0x4c\n'[?] ', # 0x4d\n'He ', # 0x4e\n'He ', # 0x4f\n'Bing ', # 0x50\n'Qing ', # 0x51\n'Qing ', # 0x52\n'Jing ', # 0x53\n'Tian ', # 0x54\n'Zhen ', # 0x55\n'Jing ', # 0x56\n'Cheng ', # 0x57\n'Qing ', # 0x58\n'Jing ', # 0x59\n'Jing ', # 0x5a\n'Dian ', # 0x5b\n'Jing ', # 0x5c\n'Tian ', # 0x5d\n'Fei ', # 0x5e\n'Fei ', # 0x5f\n'Kao ', # 0x60\n'Mi ', # 0x61\n'Mian ', # 0x62\n'Mian ', # 0x63\n'Pao ', # 0x64\n'Ye ', # 0x65\n'Tian ', # 0x66\n'Hui ', # 0x67\n'Ye ', # 0x68\n'Ge ', # 0x69\n'Ding ', # 0x6a\n'Cha ', # 0x6b\n'Jian ', # 0x6c\n'Ren ', # 0x6d\n'Di ', # 0x6e\n'Du ', # 0x6f\n'Wu ', # 0x70\n'Ren ', # 0x71\n'Qin ', # 0x72\n'Jin ', # 0x73\n'Xue ', # 0x74\n'Niu ', # 0x75\n'Ba ', # 0x76\n'Yin ', # 0x77\n'Sa ', # 0x78\n'Na ', # 0x79\n'Mo ', # 0x7a\n'Zu ', # 0x7b\n'Da ', # 0x7c\n'Ban ', # 0x7d\n'Yi ', # 0x7e\n'Yao ', # 0x7f\n'Tao ', # 0x80\n'Tuo ', # 0x81\n'Jia ', # 0x82\n'Hong ', # 0x83\n'Pao ', # 0x84\n'Yang ', # 0x85\n'Tomo ', # 0x86\n'Yin ', # 0x87\n'Jia ', # 0x88\n'Tao ', # 0x89\n'Ji ', # 0x8a\n'Xie ', # 0x8b\n'An ', # 0x8c\n'An ', # 0x8d\n'Hen ', # 0x8e\n'Gong ', # 0x8f\n'Kohaze ', # 0x90\n'Da ', # 0x91\n'Qiao ', # 0x92\n'Ting ', # 0x93\n'Wan ', # 0x94\n'Ying ', # 0x95\n'Sui ', # 0x96\n'Tiao ', # 0x97\n'Qiao ', # 0x98\n'Xuan ', # 0x99\n'Kong ', # 0x9a\n'Beng ', # 0x9b\n'Ta ', # 0x9c\n'Zhang ', # 0x9d\n'Bing ', # 0x9e\n'Kuo ', # 0x9f\n'Ju ', # 0xa0\n'La ', # 0xa1\n'Xie ', # 0xa2\n'Rou ', # 0xa3\n'Bang ', # 0xa4\n'Yi ', # 0xa5\n'Qiu ', # 0xa6\n'Qiu ', # 0xa7\n'He ', # 0xa8\n'Xiao ', # 0xa9\n'Mu ', # 0xaa\n'Ju ', # 0xab\n'Jian ', # 0xac\n'Bian ', # 0xad\n'Di ', # 0xae\n'Jian ', # 0xaf\n'On ', # 0xb0\n'Tao ', # 0xb1\n'Gou ', # 0xb2\n'Ta ', # 0xb3\n'Bei ', # 0xb4\n'Xie ', # 0xb5\n'Pan ', # 0xb6\n'Ge ', # 0xb7\n'Bi ', # 0xb8\n'Kuo ', # 0xb9\n'Tang ', # 0xba\n'Lou ', # 0xbb\n'Gui ', # 0xbc\n'Qiao ', # 0xbd\n'Xue ', # 0xbe\n'Ji ', # 0xbf\n'Jian ', # 0xc0\n'Jiang ', # 0xc1\n'Chan ', # 0xc2\n'Da ', # 0xc3\n'Huo ', # 0xc4\n'Xian ', # 0xc5\n'Qian ', # 0xc6\n'Du ', # 0xc7\n'Wa ', # 0xc8\n'Jian ', # 0xc9\n'Lan ', # 0xca\n'Wei ', # 0xcb\n'Ren ', # 0xcc\n'Fu ', # 0xcd\n'Mei ', # 0xce\n'Juan ', # 0xcf\n'Ge ', # 0xd0\n'Wei ', # 0xd1\n'Qiao ', # 0xd2\n'Han ', # 0xd3\n'Chang ', # 0xd4\n'[?] ', # 0xd5\n'Rou ', # 0xd6\n'Xun ', # 0xd7\n'She ', # 0xd8\n'Wei ', # 0xd9\n'Ge ', # 0xda\n'Bei ', # 0xdb\n'Tao ', # 0xdc\n'Gou ', # 0xdd\n'Yun ', # 0xde\n'[?] ', # 0xdf\n'Bi ', # 0xe0\n'Wei ', # 0xe1\n'Hui ', # 0xe2\n'Du ', # 0xe3\n'Wa ', # 0xe4\n'Du ', # 0xe5\n'Wei ', # 0xe6\n'Ren ', # 0xe7\n'Fu ', # 0xe8\n'Han ', # 0xe9\n'Wei ', # 0xea\n'Yun ', # 0xeb\n'Tao ', # 0xec\n'Jiu ', # 0xed\n'Jiu ', # 0xee\n'Xian ', # 0xef\n'Xie ', # 0xf0\n'Xian ', # 0xf1\n'Ji ', # 0xf2\n'Yin ', # 0xf3\n'Za ', # 0xf4\n'Yun ', # 0xf5\n'Shao ', # 0xf6\n'Le ', # 0xf7\n'Peng ', # 0xf8\n'Heng ', # 0xf9\n'Ying ', # 0xfa\n'Yun ', # 0xfb\n'Peng ', # 0xfc\n'Yin ', # 0xfd\n'Yin ', # 0xfe\n'Xiang ', # 0xff\n)\n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":-2384405795851090400,"string":"-2,384,405,795,851,090,400"},"line_mean":{"kind":"number","value":16.996124031,"string":"16.996124"},"line_max":{"kind":"number","value":20,"string":"20"},"alpha_frac":{"kind":"number","value":0.388757269,"string":"0.388757"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":934,"cells":{"repo_name":{"kind":"string","value":"eonpatapon/neutron"},"path":{"kind":"string","value":"neutron/db/db_base_plugin_common.py"},"copies":{"kind":"string","value":"2"},"size":{"kind":"string","value":"11824"},"content":{"kind":"string","value":"# Copyright (c) 2015 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport functools\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom sqlalchemy.orm import exc\n\nfrom neutron.api.v2 import attributes\nfrom neutron.common import constants\nfrom neutron.common import exceptions as n_exc\nfrom neutron.common import utils\nfrom neutron.db import common_db_mixin\nfrom neutron.db import models_v2\n\nLOG = logging.getLogger(__name__)\n\n\nclass DbBasePluginCommon(common_db_mixin.CommonDbMixin):\n \"\"\"Stores getters and helper methods for db_base_plugin_v2\n\n All private getters and simple helpers like _make_*_dict were moved from\n db_base_plugin_v2.\n More complicated logic and public methods left in db_base_plugin_v2.\n Main purpose of this class is to make getters accessible for Ipam\n backends.\n \"\"\"\n\n @staticmethod\n def _generate_mac():\n return utils.get_random_mac(cfg.CONF.base_mac.split(':'))\n\n @staticmethod\n def _delete_ip_allocation(context, network_id, subnet_id, ip_address):\n\n # Delete the IP address from the IPAllocate table\n LOG.debug(\"Delete allocated IP %(ip_address)s \"\n \"(%(network_id)s/%(subnet_id)s)\",\n {'ip_address': ip_address,\n 'network_id': network_id,\n 'subnet_id': subnet_id})\n context.session.query(models_v2.IPAllocation).filter_by(\n network_id=network_id,\n ip_address=ip_address,\n subnet_id=subnet_id).delete()\n\n @staticmethod\n def _store_ip_allocation(context, ip_address, network_id, subnet_id,\n port_id):\n LOG.debug(\"Allocated IP %(ip_address)s \"\n \"(%(network_id)s/%(subnet_id)s/%(port_id)s)\",\n {'ip_address': ip_address,\n 'network_id': network_id,\n 'subnet_id': subnet_id,\n 'port_id': port_id})\n allocated = models_v2.IPAllocation(\n network_id=network_id,\n port_id=port_id,\n ip_address=ip_address,\n subnet_id=subnet_id\n )\n context.session.add(allocated)\n\n def _make_subnet_dict(self, subnet, fields=None, context=None):\n res = {'id': subnet['id'],\n 'name': subnet['name'],\n 'tenant_id': subnet['tenant_id'],\n 'network_id': subnet['network_id'],\n 'ip_version': subnet['ip_version'],\n 'cidr': subnet['cidr'],\n 'subnetpool_id': subnet.get('subnetpool_id'),\n 'allocation_pools': [{'start': pool['first_ip'],\n 'end': pool['last_ip']}\n for pool in subnet['allocation_pools']],\n 'gateway_ip': subnet['gateway_ip'],\n 'enable_dhcp': subnet['enable_dhcp'],\n 'ipv6_ra_mode': subnet['ipv6_ra_mode'],\n 'ipv6_address_mode': subnet['ipv6_address_mode'],\n 'dns_nameservers': [dns['address']\n for dns in subnet['dns_nameservers']],\n 'host_routes': [{'destination': route['destination'],\n 'nexthop': route['nexthop']}\n for route in subnet['routes']],\n }\n # The shared attribute for a subnet is the same as its parent network\n res['shared'] = self._make_network_dict(subnet.networks,\n context=context)['shared']\n # Call auxiliary extend functions, if any\n self._apply_dict_extend_functions(attributes.SUBNETS, res, subnet)\n return self._fields(res, fields)\n\n def _make_subnetpool_dict(self, subnetpool, fields=None):\n default_prefixlen = str(subnetpool['default_prefixlen'])\n min_prefixlen = str(subnetpool['min_prefixlen'])\n max_prefixlen = str(subnetpool['max_prefixlen'])\n res = {'id': subnetpool['id'],\n 'name': subnetpool['name'],\n 'tenant_id': subnetpool['tenant_id'],\n 'default_prefixlen': default_prefixlen,\n 'min_prefixlen': min_prefixlen,\n 'max_prefixlen': max_prefixlen,\n 'shared': subnetpool['shared'],\n 'prefixes': [prefix['cidr']\n for prefix in subnetpool['prefixes']],\n 'ip_version': subnetpool['ip_version'],\n 'default_quota': subnetpool['default_quota']}\n return self._fields(res, fields)\n\n def _make_port_dict(self, port, fields=None,\n process_extensions=True):\n res = {\"id\": port[\"id\"],\n 'name': port['name'],\n \"network_id\": port[\"network_id\"],\n 'tenant_id': port['tenant_id'],\n \"mac_address\": port[\"mac_address\"],\n \"admin_state_up\": port[\"admin_state_up\"],\n \"status\": port[\"status\"],\n \"fixed_ips\": [{'subnet_id': ip[\"subnet_id\"],\n 'ip_address': ip[\"ip_address\"]}\n for ip in port[\"fixed_ips\"]],\n \"device_id\": port[\"device_id\"],\n \"device_owner\": port[\"device_owner\"]}\n # Call auxiliary extend functions, if any\n if process_extensions:\n self._apply_dict_extend_functions(\n attributes.PORTS, res, port)\n return self._fields(res, fields)\n\n def _get_network(self, context, id):\n try:\n network = self._get_by_id(context, models_v2.Network, id)\n except exc.NoResultFound:\n raise n_exc.NetworkNotFound(net_id=id)\n return network\n\n def _get_subnet(self, context, id):\n try:\n subnet = self._get_by_id(context, models_v2.Subnet, id)\n except exc.NoResultFound:\n raise n_exc.SubnetNotFound(subnet_id=id)\n return subnet\n\n def _get_subnetpool(self, context, id):\n try:\n return self._get_by_id(context, models_v2.SubnetPool, id)\n except exc.NoResultFound:\n raise n_exc.SubnetPoolNotFound(subnetpool_id=id)\n\n def _get_all_subnetpools(self, context):\n # NOTE(tidwellr): see note in _get_all_subnets()\n return context.session.query(models_v2.SubnetPool).all()\n\n def _get_port(self, context, id):\n try:\n port = self._get_by_id(context, models_v2.Port, id)\n except exc.NoResultFound:\n raise n_exc.PortNotFound(port_id=id)\n return port\n\n def _get_dns_by_subnet(self, context, subnet_id):\n dns_qry = context.session.query(models_v2.DNSNameServer)\n return dns_qry.filter_by(subnet_id=subnet_id).all()\n\n def _get_route_by_subnet(self, context, subnet_id):\n route_qry = context.session.query(models_v2.SubnetRoute)\n return route_qry.filter_by(subnet_id=subnet_id).all()\n\n def _get_router_gw_ports_by_network(self, context, network_id):\n port_qry = context.session.query(models_v2.Port)\n return port_qry.filter_by(network_id=network_id,\n device_owner=constants.DEVICE_OWNER_ROUTER_GW).all()\n\n def _get_subnets_by_network(self, context, network_id):\n subnet_qry = context.session.query(models_v2.Subnet)\n return subnet_qry.filter_by(network_id=network_id).all()\n\n def _get_subnets_by_subnetpool(self, context, subnetpool_id):\n subnet_qry = context.session.query(models_v2.Subnet)\n return subnet_qry.filter_by(subnetpool_id=subnetpool_id).all()\n\n def _get_all_subnets(self, context):\n # NOTE(salvatore-orlando): This query might end up putting\n # a lot of stress on the db. Consider adding a cache layer\n return context.session.query(models_v2.Subnet).all()\n\n def _get_subnets(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n marker_obj = self._get_marker_obj(context, 'subnet', limit, marker)\n make_subnet_dict = functools.partial(self._make_subnet_dict,\n context=context)\n return self._get_collection(context, models_v2.Subnet,\n make_subnet_dict,\n filters=filters, fields=fields,\n sorts=sorts,\n limit=limit,\n marker_obj=marker_obj,\n page_reverse=page_reverse)\n\n def _make_network_dict(self, network, fields=None,\n process_extensions=True, context=None):\n res = {'id': network['id'],\n 'name': network['name'],\n 'tenant_id': network['tenant_id'],\n 'admin_state_up': network['admin_state_up'],\n 'mtu': network.get('mtu', constants.DEFAULT_NETWORK_MTU),\n 'status': network['status'],\n 'subnets': [subnet['id']\n for subnet in network['subnets']]}\n # The shared attribute for a network now reflects if the network\n # is shared to the calling tenant via an RBAC entry.\n shared = False\n matches = ('*',) + ((context.tenant_id,) if context else ())\n for entry in network.rbac_entries:\n if (entry.action == 'access_as_shared' and\n entry.target_tenant in matches):\n shared = True\n break\n res['shared'] = shared\n # TODO(pritesh): Move vlan_transparent to the extension module.\n # vlan_transparent here is only added if the vlantransparent\n # extension is enabled.\n if ('vlan_transparent' in network and network['vlan_transparent'] !=\n attributes.ATTR_NOT_SPECIFIED):\n res['vlan_transparent'] = network['vlan_transparent']\n # Call auxiliary extend functions, if any\n if process_extensions:\n self._apply_dict_extend_functions(\n attributes.NETWORKS, res, network)\n return self._fields(res, fields)\n\n def _make_subnet_args(self, detail, subnet, subnetpool_id):\n gateway_ip = str(detail.gateway_ip) if detail.gateway_ip else None\n args = {'tenant_id': detail.tenant_id,\n 'id': detail.subnet_id,\n 'name': subnet['name'],\n 'network_id': subnet['network_id'],\n 'ip_version': subnet['ip_version'],\n 'cidr': str(detail.subnet_cidr),\n 'subnetpool_id': subnetpool_id,\n 'enable_dhcp': subnet['enable_dhcp'],\n 'gateway_ip': gateway_ip}\n if subnet['ip_version'] == 6 and subnet['enable_dhcp']:\n if attributes.is_attr_set(subnet['ipv6_ra_mode']):\n args['ipv6_ra_mode'] = subnet['ipv6_ra_mode']\n if attributes.is_attr_set(subnet['ipv6_address_mode']):\n args['ipv6_address_mode'] = subnet['ipv6_address_mode']\n return args\n\n def _make_fixed_ip_dict(self, ips):\n # Excludes from dict all keys except subnet_id and ip_address\n return [{'subnet_id': ip[\"subnet_id\"],\n 'ip_address': ip[\"ip_address\"]}\n for ip in ips]\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-7870414294914171000,"string":"-7,870,414,294,914,171,000"},"line_mean":{"kind":"number","value":43.2846441948,"string":"43.284644"},"line_max":{"kind":"number","value":78,"string":"78"},"alpha_frac":{"kind":"number","value":0.5661366712,"string":"0.566137"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":935,"cells":{"repo_name":{"kind":"string","value":"cubicova17/annet"},"path":{"kind":"string","value":"venv/lib/python2.7/site-packages/south/management/commands/convert_to_south.py"},"copies":{"kind":"string","value":"24"},"size":{"kind":"string","value":"3676"},"content":{"kind":"string","value":"\"\"\"\nQuick conversion command module.\n\"\"\"\n\nfrom optparse import make_option\nimport sys\n\nfrom django.core.management.base import BaseCommand\nfrom django.core.management.color import no_style\nfrom django.conf import settings\nfrom django.db import models\nfrom django.core import management\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom south.migration import Migrations\nfrom south.hacks import hacks\nfrom south.exceptions import NoMigrations\n\nclass Command(BaseCommand):\n \n option_list = BaseCommand.option_list\n if '--verbosity' not in [opt.get_opt_string() for opt in BaseCommand.option_list]:\n option_list += (\n make_option('--verbosity', action='store', dest='verbosity', default='1',\n type='choice', choices=['0', '1', '2'],\n help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),\n )\n option_list += (\n make_option('--delete-ghost-migrations', action='store_true', dest='delete_ghosts', default=False,\n help=\"Tells South to delete any 'ghost' migrations (ones in the database but not on disk).\"),\n make_option('--ignore-ghost-migrations', action='store_true', dest='ignore_ghosts', default=False,\n help=\"Tells South to ignore any 'ghost' migrations (ones in the database but not on disk) and continue to apply new migrations.\"), \n )\n\n help = \"Quickly converts the named application to use South if it is currently using syncdb.\"\n\n def handle(self, app=None, *args, **options):\n \n # Make sure we have an app\n if not app:\n print \"Please specify an app to convert.\"\n return\n \n # See if the app exists\n app = app.split(\".\")[-1]\n try:\n app_module = models.get_app(app)\n except ImproperlyConfigured:\n print \"There is no enabled application matching '%s'.\" % app\n return\n \n # Try to get its list of models\n model_list = models.get_models(app_module)\n if not model_list:\n print \"This application has no models; this command is for applications that already have models syncdb'd.\"\n print \"Make some models, and then use ./manage.py schemamigration %s --initial instead.\" % app\n return\n \n # Ask South if it thinks it's already got migrations\n try:\n Migrations(app)\n except NoMigrations:\n pass\n else:\n print \"This application is already managed by South.\"\n return\n \n # Finally! It seems we've got a candidate, so do the two-command trick\n verbosity = int(options.get('verbosity', 0))\n management.call_command(\"schemamigration\", app, initial=True, verbosity=verbosity)\n \n # Now, we need to re-clean and sanitise appcache\n hacks.clear_app_cache()\n hacks.repopulate_app_cache()\n \n # And also clear our cached Migration classes\n Migrations._clear_cache()\n \n # Now, migrate\n management.call_command(\n \"migrate\",\n app,\n \"0001\",\n fake=True,\n verbosity=verbosity,\n ignore_ghosts=options.get(\"ignore_ghosts\", False),\n delete_ghosts=options.get(\"delete_ghosts\", False),\n )\n \n print \n print \"App '%s' converted. Note that South assumed the application's models matched the database\" % app\n print \"(i.e. you haven't changed it since last syncdb); if you have, you should delete the %s/migrations\" % app\n print \"directory, revert models.py so it matches the database, and try again.\"\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":2805439749809700000,"string":"2,805,439,749,809,700,000"},"line_mean":{"kind":"number","value":38.5268817204,"string":"38.526882"},"line_max":{"kind":"number","value":143,"string":"143"},"alpha_frac":{"kind":"number","value":0.6224156692,"string":"0.622416"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":936,"cells":{"repo_name":{"kind":"string","value":"sdague/home-assistant"},"path":{"kind":"string","value":"homeassistant/helpers/template.py"},"copies":{"kind":"string","value":"2"},"size":{"kind":"string","value":"43562"},"content":{"kind":"string","value":"\"\"\"Template helper methods for rendering strings with Home Assistant data.\"\"\"\nfrom ast import literal_eval\nimport asyncio\nimport base64\nimport collections.abc\nfrom datetime import datetime, timedelta\nfrom functools import partial, wraps\nimport json\nimport logging\nimport math\nfrom operator import attrgetter\nimport random\nimport re\nfrom typing import Any, Dict, Generator, Iterable, Optional, Type, Union\nfrom urllib.parse import urlencode as urllib_urlencode\nimport weakref\n\nimport jinja2\nfrom jinja2 import contextfilter, contextfunction\nfrom jinja2.sandbox import ImmutableSandboxedEnvironment\nfrom jinja2.utils import Namespace # type: ignore\nimport voluptuous as vol\n\nfrom homeassistant.const import (\n ATTR_ENTITY_ID,\n ATTR_LATITUDE,\n ATTR_LONGITUDE,\n ATTR_UNIT_OF_MEASUREMENT,\n LENGTH_METERS,\n STATE_UNKNOWN,\n)\nfrom homeassistant.core import State, callback, split_entity_id, valid_entity_id\nfrom homeassistant.exceptions import TemplateError\nfrom homeassistant.helpers import location as loc_helper\nfrom homeassistant.helpers.typing import HomeAssistantType, TemplateVarsType\nfrom homeassistant.loader import bind_hass\nfrom homeassistant.util import convert, dt as dt_util, location as loc_util\nfrom homeassistant.util.async_ import run_callback_threadsafe\nfrom homeassistant.util.thread import ThreadWithException\n\n# mypy: allow-untyped-calls, allow-untyped-defs\n# mypy: no-check-untyped-defs, no-warn-return-any\n\n_LOGGER = logging.getLogger(__name__)\n_SENTINEL = object()\nDATE_STR_FORMAT = \"%Y-%m-%d %H:%M:%S\"\n\n_RENDER_INFO = \"template.render_info\"\n_ENVIRONMENT = \"template.environment\"\n\n_RE_JINJA_DELIMITERS = re.compile(r\"\\{%|\\{\\{|\\{#\")\n\n_RESERVED_NAMES = {\"contextfunction\", \"evalcontextfunction\", \"environmentfunction\"}\n\n_GROUP_DOMAIN_PREFIX = \"group.\"\n\n_COLLECTABLE_STATE_ATTRIBUTES = {\n \"state\",\n \"attributes\",\n \"last_changed\",\n \"last_updated\",\n \"context\",\n \"domain\",\n \"object_id\",\n \"name\",\n}\n\nALL_STATES_RATE_LIMIT = timedelta(minutes=1)\nDOMAIN_STATES_RATE_LIMIT = timedelta(seconds=1)\n\n\n@bind_hass\ndef attach(hass: HomeAssistantType, obj: Any) -> None:\n \"\"\"Recursively attach hass to all template instances in list and dict.\"\"\"\n if isinstance(obj, list):\n for child in obj:\n attach(hass, child)\n elif isinstance(obj, collections.abc.Mapping):\n for child_key, child_value in obj.items():\n attach(hass, child_key)\n attach(hass, child_value)\n elif isinstance(obj, Template):\n obj.hass = hass\n\n\ndef render_complex(value: Any, variables: TemplateVarsType = None) -> Any:\n \"\"\"Recursive template creator helper function.\"\"\"\n if isinstance(value, list):\n return [render_complex(item, variables) for item in value]\n if isinstance(value, collections.abc.Mapping):\n return {\n render_complex(key, variables): render_complex(item, variables)\n for key, item in value.items()\n }\n if isinstance(value, Template):\n return value.async_render(variables)\n\n return value\n\n\ndef is_complex(value: Any) -> bool:\n \"\"\"Test if data structure is a complex template.\"\"\"\n if isinstance(value, Template):\n return True\n if isinstance(value, list):\n return any(is_complex(val) for val in value)\n if isinstance(value, collections.abc.Mapping):\n return any(is_complex(val) for val in value.keys()) or any(\n is_complex(val) for val in value.values()\n )\n return False\n\n\ndef is_template_string(maybe_template: str) -> bool:\n \"\"\"Check if the input is a Jinja2 template.\"\"\"\n return _RE_JINJA_DELIMITERS.search(maybe_template) is not None\n\n\nclass ResultWrapper:\n \"\"\"Result wrapper class to store render result.\"\"\"\n\n render_result: Optional[str]\n\n\ndef gen_result_wrapper(kls):\n \"\"\"Generate a result wrapper.\"\"\"\n\n class Wrapper(kls, ResultWrapper):\n \"\"\"Wrapper of a kls that can store render_result.\"\"\"\n\n def __init__(self, *args: tuple, render_result: Optional[str] = None) -> None:\n super().__init__(*args)\n self.render_result = render_result\n\n def __str__(self) -> str:\n if self.render_result is None:\n # Can't get set repr to work\n if kls is set:\n return str(set(self))\n\n return kls.__str__(self)\n\n return self.render_result\n\n return Wrapper\n\n\nclass TupleWrapper(tuple, ResultWrapper):\n \"\"\"Wrap a tuple.\"\"\"\n\n # This is all magic to be allowed to subclass a tuple.\n\n def __new__(\n cls, value: tuple, *, render_result: Optional[str] = None\n ) -> \"TupleWrapper\":\n \"\"\"Create a new tuple class.\"\"\"\n return super().__new__(cls, tuple(value))\n\n # pylint: disable=super-init-not-called\n\n def __init__(self, value: tuple, *, render_result: Optional[str] = None):\n \"\"\"Initialize a new tuple class.\"\"\"\n self.render_result = render_result\n\n def __str__(self) -> str:\n \"\"\"Return string representation.\"\"\"\n if self.render_result is None:\n return super().__str__()\n\n return self.render_result\n\n\nRESULT_WRAPPERS: Dict[Type, Type] = {\n kls: gen_result_wrapper(kls) for kls in (list, dict, set)\n}\nRESULT_WRAPPERS[tuple] = TupleWrapper\n\n\ndef _true(arg: Any) -> bool:\n return True\n\n\ndef _false(arg: Any) -> bool:\n return False\n\n\nclass RenderInfo:\n \"\"\"Holds information about a template render.\"\"\"\n\n def __init__(self, template):\n \"\"\"Initialise.\"\"\"\n self.template = template\n # Will be set sensibly once frozen.\n self.filter_lifecycle = _true\n self.filter = _true\n self._result = None\n self.is_static = False\n self.exception = None\n self.all_states = False\n self.all_states_lifecycle = False\n self.domains = set()\n self.domains_lifecycle = set()\n self.entities = set()\n self.rate_limit = None\n self.has_time = False\n\n def __repr__(self) -> str:\n \"\"\"Representation of RenderInfo.\"\"\"\n return f\" has_time={self.has_time}\"\n\n def _filter_domains_and_entities(self, entity_id: str) -> bool:\n \"\"\"Template should re-render if the entity state changes when we match specific domains or entities.\"\"\"\n return (\n split_entity_id(entity_id)[0] in self.domains or entity_id in self.entities\n )\n\n def _filter_entities(self, entity_id: str) -> bool:\n \"\"\"Template should re-render if the entity state changes when we match specific entities.\"\"\"\n return entity_id in self.entities\n\n def _filter_lifecycle_domains(self, entity_id: str) -> bool:\n \"\"\"Template should re-render if the entity is added or removed with domains watched.\"\"\"\n return split_entity_id(entity_id)[0] in self.domains_lifecycle\n\n def result(self) -> str:\n \"\"\"Results of the template computation.\"\"\"\n if self.exception is not None:\n raise self.exception\n return self._result\n\n def _freeze_static(self) -> None:\n self.is_static = True\n self._freeze_sets()\n self.all_states = False\n\n def _freeze_sets(self) -> None:\n self.entities = frozenset(self.entities)\n self.domains = frozenset(self.domains)\n self.domains_lifecycle = frozenset(self.domains_lifecycle)\n\n def _freeze(self) -> None:\n self._freeze_sets()\n\n if self.rate_limit is None:\n if self.all_states or self.exception:\n self.rate_limit = ALL_STATES_RATE_LIMIT\n elif self.domains or self.domains_lifecycle:\n self.rate_limit = DOMAIN_STATES_RATE_LIMIT\n\n if self.exception:\n return\n\n if not self.all_states_lifecycle:\n if self.domains_lifecycle:\n self.filter_lifecycle = self._filter_lifecycle_domains\n else:\n self.filter_lifecycle = _false\n\n if self.all_states:\n return\n\n if self.domains:\n self.filter = self._filter_domains_and_entities\n elif self.entities:\n self.filter = self._filter_entities\n else:\n self.filter = _false\n\n\nclass Template:\n \"\"\"Class to hold a template and manage caching and rendering.\"\"\"\n\n __slots__ = (\n \"__weakref__\",\n \"template\",\n \"hass\",\n \"is_static\",\n \"_compiled_code\",\n \"_compiled\",\n )\n\n def __init__(self, template, hass=None):\n \"\"\"Instantiate a template.\"\"\"\n if not isinstance(template, str):\n raise TypeError(\"Expected template to be a string\")\n\n self.template: str = template.strip()\n self._compiled_code = None\n self._compiled = None\n self.hass = hass\n self.is_static = not is_template_string(template)\n\n @property\n def _env(self):\n if self.hass is None:\n return _NO_HASS_ENV\n ret = self.hass.data.get(_ENVIRONMENT)\n if ret is None:\n ret = self.hass.data[_ENVIRONMENT] = TemplateEnvironment(self.hass)\n return ret\n\n def ensure_valid(self):\n \"\"\"Return if template is valid.\"\"\"\n if self._compiled_code is not None:\n return\n\n try:\n self._compiled_code = self._env.compile(self.template)\n except jinja2.TemplateError as err:\n raise TemplateError(err) from err\n\n def render(\n self,\n variables: TemplateVarsType = None,\n parse_result: bool = True,\n **kwargs: Any,\n ) -> Any:\n \"\"\"Render given template.\"\"\"\n if self.is_static:\n if self.hass.config.legacy_templates or not parse_result:\n return self.template\n return self._parse_result(self.template)\n\n return run_callback_threadsafe(\n self.hass.loop,\n partial(self.async_render, variables, parse_result, **kwargs),\n ).result()\n\n @callback\n def async_render(\n self,\n variables: TemplateVarsType = None,\n parse_result: bool = True,\n **kwargs: Any,\n ) -> Any:\n \"\"\"Render given template.\n\n This method must be run in the event loop.\n \"\"\"\n if self.is_static:\n if self.hass.config.legacy_templates or not parse_result:\n return self.template\n return self._parse_result(self.template)\n\n compiled = self._compiled or self._ensure_compiled()\n\n if variables is not None:\n kwargs.update(variables)\n\n try:\n render_result = compiled.render(kwargs)\n except Exception as err: # pylint: disable=broad-except\n raise TemplateError(err) from err\n\n render_result = render_result.strip()\n\n if self.hass.config.legacy_templates or not parse_result:\n return render_result\n\n return self._parse_result(render_result)\n\n def _parse_result(self, render_result: str) -> Any: # pylint: disable=no-self-use\n \"\"\"Parse the result.\"\"\"\n try:\n result = literal_eval(render_result)\n\n if type(result) in RESULT_WRAPPERS:\n result = RESULT_WRAPPERS[type(result)](\n result, render_result=render_result\n )\n\n # If the literal_eval result is a string, use the original\n # render, by not returning right here. The evaluation of strings\n # resulting in strings impacts quotes, to avoid unexpected\n # output; use the original render instead of the evaluated one.\n if not isinstance(result, str):\n return result\n except (ValueError, TypeError, SyntaxError, MemoryError):\n pass\n\n return render_result\n\n async def async_render_will_timeout(\n self, timeout: float, variables: TemplateVarsType = None, **kwargs: Any\n ) -> bool:\n \"\"\"Check to see if rendering a template will timeout during render.\n\n This is intended to check for expensive templates\n that will make the system unstable. The template\n is rendered in the executor to ensure it does not\n tie up the event loop.\n\n This function is not a security control and is only\n intended to be used as a safety check when testing\n templates.\n\n This method must be run in the event loop.\n \"\"\"\n assert self.hass\n\n if self.is_static:\n return False\n\n compiled = self._compiled or self._ensure_compiled()\n\n if variables is not None:\n kwargs.update(variables)\n\n finish_event = asyncio.Event()\n\n def _render_template():\n try:\n compiled.render(kwargs)\n except TimeoutError:\n pass\n finally:\n run_callback_threadsafe(self.hass.loop, finish_event.set)\n\n try:\n template_render_thread = ThreadWithException(target=_render_template)\n template_render_thread.start()\n await asyncio.wait_for(finish_event.wait(), timeout=timeout)\n except asyncio.TimeoutError:\n template_render_thread.raise_exc(TimeoutError)\n return True\n finally:\n template_render_thread.join()\n\n return False\n\n @callback\n def async_render_to_info(\n self, variables: TemplateVarsType = None, **kwargs: Any\n ) -> RenderInfo:\n \"\"\"Render the template and collect an entity filter.\"\"\"\n assert self.hass and _RENDER_INFO not in self.hass.data\n\n render_info = RenderInfo(self)\n\n # pylint: disable=protected-access\n if self.is_static:\n render_info._result = self.template.strip()\n render_info._freeze_static()\n return render_info\n\n self.hass.data[_RENDER_INFO] = render_info\n try:\n render_info._result = self.async_render(variables, **kwargs)\n except TemplateError as ex:\n render_info.exception = ex\n finally:\n del self.hass.data[_RENDER_INFO]\n\n render_info._freeze()\n return render_info\n\n def render_with_possible_json_value(self, value, error_value=_SENTINEL):\n \"\"\"Render template with value exposed.\n\n If valid JSON will expose value_json too.\n \"\"\"\n if self.is_static:\n return self.template\n\n return run_callback_threadsafe(\n self.hass.loop,\n self.async_render_with_possible_json_value,\n value,\n error_value,\n ).result()\n\n @callback\n def async_render_with_possible_json_value(\n self, value, error_value=_SENTINEL, variables=None\n ):\n \"\"\"Render template with value exposed.\n\n If valid JSON will expose value_json too.\n\n This method must be run in the event loop.\n \"\"\"\n if self.is_static:\n return self.template\n\n if self._compiled is None:\n self._ensure_compiled()\n\n variables = dict(variables or {})\n variables[\"value\"] = value\n\n try:\n variables[\"value_json\"] = json.loads(value)\n except (ValueError, TypeError):\n pass\n\n try:\n return self._compiled.render(variables).strip()\n except jinja2.TemplateError as ex:\n if error_value is _SENTINEL:\n _LOGGER.error(\n \"Error parsing value: %s (value: %s, template: %s)\",\n ex,\n value,\n self.template,\n )\n return value if error_value is _SENTINEL else error_value\n\n def _ensure_compiled(self):\n \"\"\"Bind a template to a specific hass instance.\"\"\"\n self.ensure_valid()\n\n assert self.hass is not None, \"hass variable not set on template\"\n\n env = self._env\n\n self._compiled = jinja2.Template.from_code(\n env, self._compiled_code, env.globals, None\n )\n\n return self._compiled\n\n def __eq__(self, other):\n \"\"\"Compare template with another.\"\"\"\n return (\n self.__class__ == other.__class__\n and self.template == other.template\n and self.hass == other.hass\n )\n\n def __hash__(self) -> int:\n \"\"\"Hash code for template.\"\"\"\n return hash(self.template)\n\n def __repr__(self) -> str:\n \"\"\"Representation of Template.\"\"\"\n return 'Template(\"' + self.template + '\")'\n\n\nclass AllStates:\n \"\"\"Class to expose all HA states as attributes.\"\"\"\n\n def __init__(self, hass):\n \"\"\"Initialize all states.\"\"\"\n self._hass = hass\n\n def __getattr__(self, name):\n \"\"\"Return the domain state.\"\"\"\n if \".\" in name:\n return _get_state_if_valid(self._hass, name)\n\n if name in _RESERVED_NAMES:\n return None\n\n if not valid_entity_id(f\"{name}.entity\"):\n raise TemplateError(f\"Invalid domain name '{name}'\")\n\n return DomainStates(self._hass, name)\n\n # Jinja will try __getitem__ first and it avoids the need\n # to call is_safe_attribute\n __getitem__ = __getattr__\n\n def _collect_all(self) -> None:\n render_info = self._hass.data.get(_RENDER_INFO)\n if render_info is not None:\n render_info.all_states = True\n\n def _collect_all_lifecycle(self) -> None:\n render_info = self._hass.data.get(_RENDER_INFO)\n if render_info is not None:\n render_info.all_states_lifecycle = True\n\n def __iter__(self):\n \"\"\"Return all states.\"\"\"\n self._collect_all()\n return _state_generator(self._hass, None)\n\n def __len__(self) -> int:\n \"\"\"Return number of states.\"\"\"\n self._collect_all_lifecycle()\n return self._hass.states.async_entity_ids_count()\n\n def __call__(self, entity_id):\n \"\"\"Return the states.\"\"\"\n state = _get_state(self._hass, entity_id)\n return STATE_UNKNOWN if state is None else state.state\n\n def __repr__(self) -> str:\n \"\"\"Representation of All States.\"\"\"\n return \"