Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd54b5f06a | ||
|
|
e22af6a0ec | ||
|
|
541c2bd069 |
No files matched your search
+2
-2
@@ -18,8 +18,8 @@ rpm/debは初期配布の必須条件にせず、LinuxはELFを提供する。Py
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
# ダウンロード先で実行。手元にあるファイルをチェックする。
|
# ダウンロード先で実行。手元にあるファイルをチェックする。
|
||||||
sha256sum --ignore-missing -c pages-cli-v0.3.0-linux-amd64-SHA256SUMS
|
sha256sum --ignore-missing -c pages-cli-v0.4.1-linux-amd64-SHA256SUMS
|
||||||
tar -xzf pages-cli-v0.3.0-linux-amd64.tar.gz
|
tar -xzf pages-cli-v0.4.1-linux-amd64.tar.gz
|
||||||
mkdir -p ~/.local/bin
|
mkdir -p ~/.local/bin
|
||||||
install -m 755 pages ~/.local/bin/pages
|
install -m 755 pages ~/.local/bin/pages
|
||||||
pages --version
|
pages --version
|
||||||
|
|||||||
@@ -175,6 +175,8 @@ python3 -m unittest test_pages test_productivity test_distribution test_tls
|
|||||||
合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。
|
合成サーバーと一時ディレクトリのみを使用します。TLS試験には一時証明書を生成するOpenSSLコマンドが必要です。本番資格情報や外部カレンダーは不要です。Goサーバーとの結合テストはサーバーリポジトリ側で実行します。
|
||||||
## タスクと連絡先
|
## タスクと連絡先
|
||||||
|
|
||||||
|
v0.4.0のメール保存先はML連番があれば `親Path/リスト名/連番`、なければ `親Path/YYYY/MM/識別子` です。この方式にはサーバーv0.9.0以降が必要です。年月・衝突・旧版からの再送の規則は下記NeoMuttガイドを参照してください。
|
||||||
|
|
||||||
v0.3.0の `pages task from-mail` は本文を関連Wikiへ保存します(サーバーv0.8.0以降)。先に `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で閲覧制限済みの親Pathを指定してください。タスクの公開範囲とは独立して、本文はWikiの権限に従います。本文を送信しない場合は `--metadata-only` を指定します。
|
v0.3.0の `pages task from-mail` は本文を関連Wikiへ保存します(サーバーv0.8.0以降)。先に `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で閲覧制限済みの親Pathを指定してください。タスクの公開範囲とは独立して、本文はWikiの権限に従います。本文を送信しない場合は `--metadata-only` を指定します。
|
||||||
|
|
||||||
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
||||||
|
|||||||
+23
-3
@@ -26,9 +26,23 @@ v0.3.0からは件名をタスク名、From・Date・Message-IDをメモにし
|
|||||||
|
|
||||||
本文の公開範囲は保存先Wikiの権限に従う。タスクが個人用でも、公開Pathに保存した本文は公開され得るため、メール用には閲覧者を制限したPathを指定する。設定例の `/private/mail` という名前自体が非公開を保証するものではない。
|
本文の公開範囲は保存先Wikiの権限に従う。タスクが個人用でも、公開Pathに保存した本文は公開され得るため、メール用には閲覧者を制限したPathを指定する。設定例の `/private/mail` という名前自体が非公開を保証するものではない。
|
||||||
|
|
||||||
作成Pathは `親Path/安全化した件名--request_id`。同名件名を区別し、既存ページを上書きしない。タスクのメモ閲覧・編集ボタンから本文ページを開ける。タスク・Wiki・再送receiptは同一トランザクションで保存し、途中失敗で片方だけを残さない。UUIDで紐づくので、その後Wikiを移動しても追従する。
|
CLI v0.4.0のメール取り込みにはPagesWiki v0.9.0以降が必要。保存先は次の優先順で決める。
|
||||||
|
|
||||||
plain textを優先し、HTMLしかない場合はテキストを抽出する。添付・外部画像・CSS・JS・外部URLは取得せず、本文中のHTMLやWikiマクロも実行しない。原文EMLやHTMLレイアウトの保存機能ではない。入力1通2 MiB、Wiki本文(メタデータ込み)256 KiB、タスクメモ16 KiBまで。上限超過は切り捨てず拒否する。件名300 UTF-8 bytes超は `--title '短い件名'` を指定する。旧 `--include-body` は既定動作の別名として残す。以前の本文非送信動作には `--metadata-only` を使う。
|
| メール | 保存先 |
|
||||||
|
| --- | --- |
|
||||||
|
| 先頭にML連番がある | `親Path/リスト名/連番`(例:`/mail/hogehoge/123`) |
|
||||||
|
| ML連番なし、Message-IDあり | `親Path/YYYY/MM/UUID` |
|
||||||
|
| 両方なし | `親Path/YYYY/MM/原文SHA-256` |
|
||||||
|
|
||||||
|
リスト名はASCII英数字で始まり、英数字・ピリオド・ハイフン・アンダースコアの100文字以内。連番は最大20桁で、先頭ゼロを除去する。Re:/Fw:/Fwd:の直後も認識し、先頭のML表記を使う。安全なリスト名・連番として解釈できない場合は年月方式へフォールバックする。表示件名の `--title` は保存先の判定を変えない。
|
||||||
|
|
||||||
|
年月はDateヘッダに記載されたタイムゾーンの年月。Dateが欠落・不正なら最初の取り込み時点のUTC年月を使い、未送信outboxに確定値を保持する。UUIDは接続先・本人・Message-IDから生成し、Message-ID自体をURLへ露出しない。同じML名・連番に異なるメールが来た場合は409で停止し、既存本文を上書きしない。
|
||||||
|
|
||||||
|
既存ページは移動・上書きせず、従来形式で保存済みの要求をretryしても元のページを返す。タスクのメモ閲覧・編集ボタンから本文ページを開ける。タスク・Wiki・再送receiptは同一トランザクションで保存し、途中失敗で片方だけを残さない。UUIDで紐づくので、その後Wikiを移動しても追従する。
|
||||||
|
|
||||||
|
CLI v0.3.1ではMIMEヘッダを復号した件名の先頭から `[list 123]`・`[list:123]`・`[list#123]` のような連番を除去する。Re:/Fwd:は維持し、その後の連番も除去する。`[重要]`、件名の途中の括弧、`--title` で明示した件名は変更しない。自動件名が300 UTF-8 bytesを超える場合は文字境界で省略して末尾に「…」を付ける。除去・省略・手動指定で変わった元のSubjectはWiki本文に残す。手動件名の上限超過は拒否する。
|
||||||
|
|
||||||
|
plain textを優先し、HTMLしかない場合はテキストを抽出する。添付・外部画像・CSS・JS・外部URLは取得せず、本文中のHTMLやWikiマクロも実行しない。原文EMLやHTMLレイアウトの保存機能ではない。入力1通2 MiB、Wiki本文(メタデータ込み)256 KiB、タスクメモ16 KiBまで。本文・メモの上限超過は切り捨てず拒否する。旧 `--include-body` は既定動作の別名として残す。以前の本文非送信動作には `--metadata-only` を使う。
|
||||||
|
|
||||||
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じIDで本文・指定Path・オプションを変えると412となり、以前のページを上書きしない。旧版でメタデータのみ取り込み済みのメールに本文を追加する場合は、既存の関連Wikiを編集する。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じIDで本文・指定Path・オプションを変えると412となり、以前のページを上書きしない。旧版でメタデータのみ取り込み済みのメールに本文を追加する場合は、既存の関連Wikiを編集する。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
||||||
|
|
||||||
@@ -52,7 +66,13 @@ pages task retry REQUEST_UUID
|
|||||||
|
|
||||||
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
||||||
|
|
||||||
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンと保留中のメール本文があるため、デバッグ目的で内容を貼り付けない。保存先未設定で失敗した場合は `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で設定してからretryする。
|
CLI v0.4.1以降では、同一内容の保留メールを再入力した場合は、確定済みの保存先を維持する。同じrequest_idで本文・件名・オプションを変更して再入力した場合は、ローカルの保留下書きを新しい内容で上書きしてから1回送信する。送信失敗時も新しい内容を保持する。`task add --request-id` も同じ動作。新しいrequest_idを発行して重複タスクを作る処理ではない。
|
||||||
|
|
||||||
|
`task retry` は、その時点で保持されている下書きを変更せずに送信する。下書きを上書きするには、NeoMuttから同じメールを改めて取り込むか、同じrequest_idを指定した `task add` を実行する。旧版で保留していた下書きも対象となる。
|
||||||
|
|
||||||
|
サーバーにすでに保存済みの同じ要求に対して本文・保存先・オプションが異なる場合は、従来どおり412で停止する。ローカル下書きの上書きは、保存済みタスクやWikiの強制上書きではない。保存済みの内容を変更する場合は通常のタスク/Wiki編集を使う。
|
||||||
|
|
||||||
|
サーバーで保存された直後に応答が失われても、同じrequest_id・同じ内容で再送すれば既存タスクが返る。サーバー保存済みの要求と異なる内容で再送すると412になる。セッションファイルにはトークンと保留中のメール本文があるため、デバッグ目的で内容を貼り付けない。保存先未設定で失敗した場合は `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で設定してからretryする。
|
||||||
|
|
||||||
## 計画と実績
|
## 計画と実績
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import email.policy
|
import email.policy
|
||||||
import email.parser
|
import email.parser
|
||||||
|
import email.utils
|
||||||
|
import datetime
|
||||||
import uuid
|
import uuid
|
||||||
import base64
|
import base64
|
||||||
import contextlib
|
import contextlib
|
||||||
@@ -30,7 +32,7 @@ import urllib.parse as url
|
|||||||
import urllib.request as http
|
import urllib.request as http
|
||||||
import webbrowser
|
import webbrowser
|
||||||
|
|
||||||
VERSION = '0.3.0'
|
VERSION = '0.4.1'
|
||||||
|
|
||||||
class Failure(Exception):
|
class Failure(Exception):
|
||||||
def __init__(self, message, status=0, payload=None):
|
def __init__(self, message, status=0, payload=None):
|
||||||
@@ -496,11 +498,37 @@ class MailText(HTMLParser):
|
|||||||
if not self.hidden: self.parts.append(data)
|
if not self.hidden: self.parts.append(data)
|
||||||
|
|
||||||
|
|
||||||
|
def mail_subject(value):
|
||||||
|
# Remove only leading mailing-list sequence markers, preserving meaningful
|
||||||
|
# tags such as [Important], and any Re:/Fwd: prefix before the marker.
|
||||||
|
marker = re.compile(r'^(?P<reply>(?:(?:re|fw|fwd)\s*:\s*)*)\[[^\[\]\r\n]+[\s:#]\s*[0-9]+\]\s*', re.IGNORECASE)
|
||||||
|
while True:
|
||||||
|
match = marker.match(value)
|
||||||
|
if not match: return value.strip()
|
||||||
|
value = match.group('reply') + value[match.end():]
|
||||||
|
|
||||||
|
|
||||||
|
def task_mail_suffix(raw, request_id, now=None):
|
||||||
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
|
subject = ' '.join(safe_text(str(message.get('Subject') or '')).split())
|
||||||
|
marker = re.match(r'^(?:(?:re|fw|fwd)\s*:\s*)*\[([A-Za-z0-9][A-Za-z0-9._-]{0,99})[\s:#]+([0-9]{1,20})\]',subject,re.IGNORECASE)
|
||||||
|
if marker:
|
||||||
|
return marker[1]+'/'+str(int(marker[2]))
|
||||||
|
try: date = email.utils.parsedate_to_datetime(str(message.get('Date') or ''))
|
||||||
|
except (ValueError, TypeError, OverflowError): date = now or datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
# Preserve the month in the sender's Date timezone, not the receiving host's.
|
||||||
|
ident = request_id if ' '.join(safe_text(str(message.get('Message-ID') or '')).split()) else hashlib.sha256(raw).hexdigest()
|
||||||
|
return f'{date.year:04d}/{date.month:02d}/{ident}'
|
||||||
|
|
||||||
|
|
||||||
def task_mail(raw, include_body=True, override_title=None):
|
def task_mail(raw, include_body=True, override_title=None):
|
||||||
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
if len(raw) > 2 << 20: raise Failure('Mail input exceeds 2 MiB; pipe one message at a time.')
|
||||||
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
message = email.parser.BytesParser(policy=email.policy.default).parsebytes(raw)
|
||||||
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
clean = lambda value: ' '.join(safe_text(str(value or '')).split())
|
||||||
title = override_title or clean(message.get('Subject')) or '(No subject)'
|
subject = clean(message.get('Subject'))
|
||||||
|
title = override_title or mail_subject(subject) or '(No subject)'
|
||||||
|
if not override_title and len(title.encode()) > 300:
|
||||||
|
title = title.encode()[:297].decode('utf-8',errors='ignore').rstrip() + '…'
|
||||||
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
if len(title.encode()) > 300: raise Failure('Mail subject exceeds 300 UTF-8 bytes; use --title.')
|
||||||
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
notes = '\n'.join(key+': '+clean(message.get(key)) for key in ('From','Date','Message-ID') if message.get(key))
|
||||||
wiki_body = None
|
wiki_body = None
|
||||||
@@ -513,7 +541,8 @@ def task_mail(raw, include_body=True, override_title=None):
|
|||||||
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
if not isinstance(content,str): raise Failure('Mail body is not readable text.')
|
||||||
if part.get_content_type() == 'text/html':
|
if part.get_content_type() == 'text/html':
|
||||||
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
||||||
wiki_body = notes + '\n\n' + content
|
# Retain the original subject when its mailing-list marker was removed.
|
||||||
|
wiki_body = (('Subject: '+subject+'\n') if title != subject else '') + notes + '\n\n' + content
|
||||||
if '\0' in wiki_body or len(wiki_body.encode()) > 256 << 10: raise Failure('Mail Wiki body must be valid text of at most 256 KiB; nothing was uploaded.')
|
if '\0' in wiki_body or len(wiki_body.encode()) > 256 << 10: raise Failure('Mail Wiki body must be valid text of at most 256 KiB; nothing was uploaded.')
|
||||||
if len(notes.encode()) > 16384: raise Failure('Mail metadata exceeds 16 KiB.')
|
if len(notes.encode()) > 16384: raise Failure('Mail metadata exceeds 16 KiB.')
|
||||||
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest(), wiki_body
|
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest(), wiki_body
|
||||||
@@ -549,7 +578,9 @@ def tasks(client, profile, words):
|
|||||||
def capture(payload):
|
def capture(payload):
|
||||||
pending=profile.data.setdefault('task_outbox',{})
|
pending=profile.data.setdefault('task_outbox',{})
|
||||||
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
if len(pending)>=20 and payload['request_id'] not in pending:raise Failure('20 pending captures retained. Retry them before adding more.')
|
||||||
|
replaced=payload['request_id'] in pending and pending[payload['request_id']] != payload
|
||||||
pending[payload['request_id']]=payload;profile.save()
|
pending[payload['request_id']]=payload;profile.save()
|
||||||
|
if replaced:print('Replaced the retained draft with the current input.',file=sys.stderr)
|
||||||
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||||
except Failure as e:
|
except Failure as e:
|
||||||
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr)
|
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr)
|
||||||
@@ -581,13 +612,21 @@ def tasks(client, profile, words):
|
|||||||
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
payload={'request_id':getattr(a,'request_id',None) or str(uuid.uuid4()),'title':a.title,'notes':a.notes or ''}
|
||||||
if action=='from-mail':
|
if action=='from-mail':
|
||||||
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
||||||
title,notes,message_id,wiki_body=task_mail(sys.stdin.buffer.read((2<<20)+1),not a.metadata_only,a.title)
|
raw=sys.stdin.buffer.read((2<<20)+1)
|
||||||
|
title,notes,message_id,wiki_body=task_mail(raw,not a.metadata_only,a.title)
|
||||||
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
payload.update(title=a.title or title,notes=a.notes if a.notes is not None else notes,request_id=str(uuid.uuid5(uuid.NAMESPACE_URL,client.base+'\n'+profile.data.get('username','')+'\n'+message_id)))
|
||||||
if wiki_body is not None: payload['wiki_body']=wiki_body
|
if wiki_body is not None:
|
||||||
|
payload['wiki_body']=wiki_body
|
||||||
|
payload['wiki_suffix']=task_mail_suffix(raw,payload['request_id'])
|
||||||
if a.wiki_prefix is not None: payload['wiki_prefix']=a.wiki_prefix
|
if a.wiki_prefix is not None: payload['wiki_prefix']=a.wiki_prefix
|
||||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due','due_on'),('start_on','start_on'),('planned','planned_on'),('review','review_on'),('estimate','estimate_minutes'),('complexity','complexity')]:
|
||||||
value=getattr(a,attr)
|
value=getattr(a,attr)
|
||||||
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
if value is not None:payload[key]=task_project(client,value) if attr=='project' else value
|
||||||
|
# A retry of the same pending mail must not drift across a month boundary
|
||||||
|
# when Date was missing. Changed input replaces the pending draft below.
|
||||||
|
old=profile.data.get('task_outbox',{}).get(payload['request_id'])
|
||||||
|
if action=='from-mail' and old and {k:v for k,v in old.items() if k!='wiki_suffix'}=={k:v for k,v in payload.items() if k!='wiki_suffix'}:
|
||||||
|
payload=old.copy()
|
||||||
emit(capture(payload));return
|
emit(capture(payload));return
|
||||||
if action=='project-add':
|
if action=='project-add':
|
||||||
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
emit(client.json(TASK_API+'items',method='POST',data={'uuid':str(uuid.uuid4()),'kind':'project','title':a.title,'notes':a.notes,'status':'todo','bucket':'inbox','priority':1}));return
|
||||||
|
|||||||
+128
-1
@@ -9,6 +9,115 @@ import unittest
|
|||||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
|
|
||||||
class ProductivityTests(unittest.TestCase):
|
class ProductivityTests(unittest.TestCase):
|
||||||
|
def test_mail_path_priority_and_dates(self):
|
||||||
|
import datetime,hashlib
|
||||||
|
ident='06cb3a24-61f8-4a9f-a0bf-89eea9632f25'
|
||||||
|
suffix=m['task_mail_suffix'];now=datetime.datetime(2030,2,1,tzinfo=datetime.timezone.utc)
|
||||||
|
for marker in ('[hogehoge 00123]','Re: [hogehoge:123]','Fwd: [hogehoge#123]'):
|
||||||
|
raw=('Subject: '+marker+' Title\r\n\r\nbody').encode()
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'hogehoge/123')
|
||||||
|
raw=b'Subject: Plain\r\nDate: Sat, 31 Jan 2026 23:30:00 -0800\r\nMessage-ID: <id@example.invalid>\r\n\r\nbody'
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'2026/01/'+ident)
|
||||||
|
noid=raw.replace(b'Message-ID: <id@example.invalid>\r\n',b'')
|
||||||
|
self.assertEqual(suffix(noid,ident,now),'2026/01/'+hashlib.sha256(noid).hexdigest())
|
||||||
|
for date in (b'',b'Date: broken\r\n'):
|
||||||
|
raw=b'Subject: [../unsafe 123] Title\r\n'+date+b'\r\nbody'
|
||||||
|
self.assertEqual(suffix(raw,ident,now),'2030/02/'+hashlib.sha256(raw).hexdigest())
|
||||||
|
|
||||||
|
def test_pending_mail_keeps_month_but_replaces_changed_options(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody'
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=send)
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
for month in ('2030/01','2030/02'):
|
||||||
|
with patch.dict(m['tasks'].__globals__,task_mail_suffix=lambda raw,ident:month+'/'+ident),patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail'])
|
||||||
|
self.assertEqual(calls[0],calls[1])
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail','--wiki-prefix','/changed'])
|
||||||
|
self.assertEqual(len(calls),3)
|
||||||
|
self.assertEqual(calls[2]['request_id'],calls[0]['request_id'])
|
||||||
|
self.assertEqual(calls[2]['wiki_prefix'],'/changed')
|
||||||
|
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[2])
|
||||||
|
|
||||||
|
def test_changed_capture_is_saved_before_send_and_retained_on_conflict(self):
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
saved,calls=[],[]
|
||||||
|
old={'request_id':ident,'title':'Old draft','notes':'Old private notes'}
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:old}})
|
||||||
|
profile.save=lambda:saved.append(json.loads(json.dumps(profile.data)))
|
||||||
|
def send(route,**kw):
|
||||||
|
payload=kw['data'].copy();calls.append(payload)
|
||||||
|
self.assertEqual(saved[-1]['task_outbox'][ident],payload)
|
||||||
|
if len(calls)==1:raise m['Failure']('conflict',412,{'error':'conflict'})
|
||||||
|
return {'item':{'uuid':ident}}
|
||||||
|
client=SimpleNamespace(json=send)
|
||||||
|
out,err=io.StringIO(),io.StringIO()
|
||||||
|
with contextlib.redirect_stdout(out),contextlib.redirect_stderr(err):
|
||||||
|
with self.assertRaises(m['Failure']) as failure:
|
||||||
|
m['tasks'](client,profile,['add','New draft','--request-id',ident,'--notes','New private notes'])
|
||||||
|
self.assertEqual(failure.exception.status,412)
|
||||||
|
self.assertEqual(profile.data['task_outbox'][ident],calls[0])
|
||||||
|
self.assertEqual(len(calls),1) # No automatic server overwrite/retry.
|
||||||
|
m['tasks'](client,profile,['retry',ident])
|
||||||
|
self.assertEqual(calls[0],calls[1])
|
||||||
|
self.assertEqual(calls[0]['title'],'New draft')
|
||||||
|
self.assertEqual(profile.data['task_outbox'],{})
|
||||||
|
self.assertIn('Replaced the retained draft',err.getvalue())
|
||||||
|
self.assertNotIn('private notes',err.getvalue())
|
||||||
|
self.assertEqual(json.loads(out.getvalue())['item']['uuid'],ident)
|
||||||
|
|
||||||
|
def test_replacing_draft_does_not_send_when_local_save_fails(self):
|
||||||
|
ident='b5550cab-22d4-54eb-b06d-3b432d3f5101'
|
||||||
|
def fail_save():raise m['Failure']('local write failed')
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':{ident:{'request_id':ident,'title':'Old','notes':''}}},save=fail_save)
|
||||||
|
calls=[]
|
||||||
|
client=SimpleNamespace(json=lambda *a,**kw:calls.append(kw))
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','New','--request-id',ident])
|
||||||
|
self.assertEqual(calls,[])
|
||||||
|
|
||||||
|
def test_full_outbox_allows_replacement_but_not_new_id(self):
|
||||||
|
import uuid
|
||||||
|
pending={str(uuid.uuid4()):{'title':'Old'} for _ in range(20)}
|
||||||
|
ident=next(iter(pending))
|
||||||
|
profile=SimpleNamespace(data={'task_outbox':pending},save=lambda:None)
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(json=send)
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['add','Replacement','--request-id',ident])
|
||||||
|
self.assertEqual(len(calls),1)
|
||||||
|
self.assertEqual(pending[ident]['title'],'Replacement')
|
||||||
|
with self.assertRaises(m['Failure']):m['tasks'](client,profile,['add','Another'])
|
||||||
|
self.assertEqual(len(calls),1)
|
||||||
|
self.assertEqual(len(pending),20)
|
||||||
|
|
||||||
|
def test_reimported_mail_replaces_body_and_removes_obsolete_options(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Old\r\nMessage-ID: <same@example.invalid>\r\n\r\nOLD BODY'
|
||||||
|
calls=[]
|
||||||
|
def send(route,**kw):
|
||||||
|
calls.append(kw['data'].copy())
|
||||||
|
raise m['Failure']('offline')
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=send)
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
changed=raw.replace(b'Subject: Old',b'Subject: New').replace(b'OLD BODY',b'NEW BODY')
|
||||||
|
for mail,args in [(raw,['--wiki-prefix','/old']),(changed,['--wiki-prefix','/new']),(changed,['--metadata-only'])]:
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(mail))),contextlib.redirect_stderr(io.StringIO()),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail',*args])
|
||||||
|
self.assertEqual(len({c['request_id'] for c in calls}),1)
|
||||||
|
self.assertEqual(calls[1]['title'],'New')
|
||||||
|
self.assertIn('NEW BODY',calls[1]['wiki_body'])
|
||||||
|
self.assertNotIn('OLD BODY',calls[1]['wiki_body'])
|
||||||
|
for key in ('wiki_body','wiki_prefix','wiki_suffix'):self.assertNotIn(key,calls[2])
|
||||||
|
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[2])
|
||||||
|
|
||||||
def test_mail_privacy_and_long_subject_override(self):
|
def test_mail_privacy_and_long_subject_override(self):
|
||||||
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
raw=b'Subject: Test\r\nFrom: Person <person@example.invalid>\r\nMessage-ID: <id@example.invalid>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPRIVATE BODY'
|
||||||
title,notes,ident,body=m['task_mail'](raw)
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
@@ -16,9 +125,27 @@ class ProductivityTests(unittest.TestCase):
|
|||||||
self.assertIn('PRIVATE BODY',body)
|
self.assertIn('PRIVATE BODY',body)
|
||||||
self.assertIsNone(m['task_mail'](raw,False)[3])
|
self.assertIsNone(m['task_mail'](raw,False)[3])
|
||||||
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
raw=raw.replace(b'Subject: Test',b'Subject: '+b'a'*301)
|
||||||
with self.assertRaises(m['Failure']):m['task_mail'](raw)
|
self.assertLessEqual(len(m['task_mail'](raw)[0].encode()),300)
|
||||||
|
with self.assertRaises(m['Failure']):m['task_mail'](raw,True,'x'*301)
|
||||||
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
self.assertEqual(m['task_mail'](raw,False,'Override')[0],'Override')
|
||||||
|
|
||||||
|
def test_japanese_subject_and_mailing_list_markers(self):
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.header import Header
|
||||||
|
for encoding in ('utf-8','iso-2022-jp'):
|
||||||
|
subject='Re: [hogehoge 00123] [team:456] 日本語の依頼 [重要]'
|
||||||
|
raw=('Subject: '+Header(subject,encoding).encode()+'\r\nMessage-ID: <same@example.invalid>\r\n\r\nbody').encode('ascii')
|
||||||
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
|
self.assertEqual(title,'Re: 日本語の依頼 [重要]')
|
||||||
|
self.assertEqual(ident,'<same@example.invalid>');self.assertIn('Subject: '+subject,body)
|
||||||
|
for subject in ('[重要] 日本語','報告 [list 123]','[release 1.2] 更新'):
|
||||||
|
self.assertEqual(m['mail_subject'](subject),subject)
|
||||||
|
msg=EmailMessage();msg['Subject']='[list 123] '+('日本語'*100);msg.set_content('Body')
|
||||||
|
title,_,_,body=m['task_mail'](msg.as_bytes())
|
||||||
|
self.assertLessEqual(len(title.encode()),300);self.assertTrue(title.endswith('…'))
|
||||||
|
self.assertIn('日本語'*100,body)
|
||||||
|
self.assertEqual(m['task_mail'](msg.as_bytes(),True,'[list 123] 手動指定')[0],'[list 123] 手動指定')
|
||||||
|
|
||||||
def test_html_mail_and_limits(self):
|
def test_html_mail_and_limits(self):
|
||||||
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
raw=b'Subject: HTML\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<head><style>secret</style></head><p>Hello</p><script>evil()</script><img src="https://example.invalid/image"><p>World & friends</p>'
|
||||||
body=m['task_mail'](raw)[3]
|
body=m['task_mail'](raw)[3]
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import json
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import runpy
|
import runpy
|
||||||
import sys
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
m=runpy.run_path(str(Path(__file__).with_name('pages')))
|
||||||
@@ -36,5 +37,22 @@ def run():
|
|||||||
output=io.StringIO()
|
output=io.StringIO()
|
||||||
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
|
with contextlib.redirect_stdout(output):m['contacts'](client,['export',contact['uuid']])
|
||||||
assert 'UID:urn:test:cli' in output.getvalue()
|
assert 'UID:urn:test:cli' in output.getvalue()
|
||||||
|
# A rejected capture can be corrected under the same request ID.
|
||||||
|
# A committed capture is still protected by the server receipt.
|
||||||
|
request_id=str(uuid.uuid4())
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
try:task('add','Rejected draft','--request-id',request_id,'--estimate','-1')
|
||||||
|
except m['Failure'] as error:assert error.status==422
|
||||||
|
else:raise AssertionError('Invalid estimate accepted')
|
||||||
|
assert profile.data['task_outbox'][request_id]['estimate_minutes']==-1
|
||||||
|
corrected=task('add','Corrected draft','--request-id',request_id,'--estimate','15')['item']
|
||||||
|
assert corrected['uuid']==request_id and corrected['title']=='Corrected draft'
|
||||||
|
assert request_id not in profile.data['task_outbox']
|
||||||
|
try:task('add','Changed after commit','--request-id',request_id,'--estimate','30')
|
||||||
|
except m['Failure'] as error:assert error.status==412
|
||||||
|
else:raise AssertionError('Committed capture silently overwritten')
|
||||||
|
assert profile.data['task_outbox'][request_id]['title']=='Changed after commit'
|
||||||
|
stored=task('show',request_id)['item']
|
||||||
|
assert stored['title']=='Corrected draft' and stored['estimate_minutes']==15
|
||||||
|
|
||||||
if __name__=='__main__':run()
|
if __name__=='__main__':run()
|
||||||
+10
-4
@@ -11,6 +11,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|||||||
binary=str(Path(sys.argv[1]).resolve())
|
binary=str(Path(sys.argv[1]).resolve())
|
||||||
token='synthetic_session_'+('x'*40)
|
token='synthetic_session_'+('x'*40)
|
||||||
seen=[]
|
seen=[]
|
||||||
|
captures=[]
|
||||||
class Handler(BaseHTTPRequestHandler):
|
class Handler(BaseHTTPRequestHandler):
|
||||||
def log_message(self,*args):pass
|
def log_message(self,*args):pass
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
@@ -20,6 +21,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
elif self.path=='/_/api/v1/extension/organizer.tasks/capture':
|
elif self.path=='/_/api/v1/extension/organizer.tasks/capture':
|
||||||
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
||||||
item=json.loads(body)
|
item=json.loads(body)
|
||||||
|
captures.append(item.copy())
|
||||||
|
if item.get('wiki_prefix')=='/rejected':self.reply({'error':'invalid'},422);return
|
||||||
if item.get('wiki_body') != 'Message-ID: <smoke@example.invalid>\n\nPRIVATE BODY':self.send_error(422);return
|
if item.get('wiki_body') != 'Message-ID: <smoke@example.invalid>\n\nPRIVATE BODY':self.send_error(422);return
|
||||||
item.pop('wiki_body');self.reply({'item':item,'page_path':'/private/mail/synthetic'})
|
item.pop('wiki_body');self.reply({'item':item,'page_path':'/private/mail/synthetic'})
|
||||||
else:self.send_error(404)
|
else:self.send_error(404)
|
||||||
@@ -29,8 +32,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'):
|
if self.path.startswith('/_/api/v1/extension/organizer.contacts/items?'):
|
||||||
self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]})
|
self.reply({'items':[{'name':'Synthetic Person','emails':['person@example.invalid'],'organization':'Test'}]})
|
||||||
else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]})
|
else:self.reply({'items':[{'uuid':'synthetic-task','title':'Packaged CLI task','status':'todo'}]})
|
||||||
def reply(self,value):
|
def reply(self,value,status=200):
|
||||||
self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode())
|
self.send_response(status);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps(value).encode())
|
||||||
|
|
||||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||||
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
||||||
@@ -46,15 +49,18 @@ try:
|
|||||||
run('login',stdin='synthetic-password\n')
|
run('login',stdin='synthetic-password\n')
|
||||||
if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing')
|
if 'Packaged CLI task' not in run('task','list'):raise AssertionError('Task missing')
|
||||||
mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY'
|
mail='Subject: Mail task\r\nMessage-ID: <smoke@example.invalid>\r\nContent-Type: text/plain\r\n\r\nPRIVATE BODY'
|
||||||
captured=run('task','from-mail',stdin=mail)
|
run('task','from-mail','--wiki-prefix','/rejected',stdin=mail,success=False)
|
||||||
|
captured=run('task','from-mail','--wiki-prefix','/private/mail',stdin=mail)
|
||||||
|
if len(captures)!=2 or captures[0]['request_id']!=captures[1]['request_id'] or captures[1]['wiki_prefix']!='/private/mail':raise AssertionError('Retained draft was not overwritten under the same request ID')
|
||||||
if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy')
|
if 'Mail task' not in captured or 'PRIVATE BODY' in captured:raise AssertionError('Mail privacy')
|
||||||
contact=run('contacts','query','--neomutt','--','--name')
|
contact=run('contacts','query','--neomutt','--','--name')
|
||||||
if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query')
|
if 'person@example.invalid\tSynthetic Person\tTest' not in contact:raise AssertionError('NeoMutt query')
|
||||||
run('shell',stdin='pwd\nexit\n')
|
run('shell',stdin='pwd\nexit\n')
|
||||||
profile=Path(root)/'pages-cli/sessions/default.json'
|
profile=Path(root)/'pages-cli/sessions/default.json'
|
||||||
|
if json.loads(profile.read_text()).get('task_outbox'):raise AssertionError('Successful replacement remains pending')
|
||||||
if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions')
|
if profile.stat().st_mode&0o077:raise AssertionError('Credential permissions')
|
||||||
profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600)
|
profile.chmod(0o644);run('task','list',success=False);profile.chmod(0o600)
|
||||||
run('logout')
|
run('logout')
|
||||||
if not seen:raise AssertionError('No HTTP request')
|
if not seen:raise AssertionError('No HTTP request')
|
||||||
print('Packaged CLI: configure/login/task-list/mail-capture/neomutt-query/shell/permissions/logout passed')
|
print('Packaged CLI: configure/login/task-list/mail-capture/draft-overwrite/neomutt-query/shell/permissions/logout passed')
|
||||||
finally:server.shutdown();server.server_close();thread.join()
|
finally:server.shutdown();server.server_close();thread.join()
|
||||||
Reference in new issue
Block a user