Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e22af6a0ec | ||
|
|
541c2bd069 | ||
|
|
cde94ed936 |
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.2.0-linux-amd64-SHA256SUMS
|
sha256sum --ignore-missing -c pages-cli-v0.4.0-linux-amd64-SHA256SUMS
|
||||||
tar -xzf pages-cli-v0.2.0-linux-amd64.tar.gz
|
tar -xzf pages-cli-v0.4.0-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,10 @@ 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` を指定します。
|
||||||
|
|
||||||
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
`pages task --help` で作成・計画・開始/終了・レポートを操作できる。
|
||||||
`pages contacts --help` で個人アドレス帳の検索・vCard入出力を行える。
|
`pages contacts --help` で個人アドレス帳の検索・vCard入出力を行える。
|
||||||
[NeoMutt設定とタスク・連絡先の操作例](docs/neomutt.md)、[そのまま調整して使える設定例](examples/neomuttrc)を参照。これらは配布アーカイブにも同梱します。
|
[NeoMutt設定とタスク・連絡先の操作例](docs/neomutt.md)、[そのまま調整して使える設定例](examples/neomuttrc)を参照。これらは配布アーカイブにも同梱します。
|
||||||
+32
-5
@@ -5,6 +5,7 @@
|
|||||||
```sh
|
```sh
|
||||||
pages configure --origin https://pages.example.test --username YOUR_USERNAME
|
pages configure --origin https://pages.example.test --username YOUR_USERNAME
|
||||||
pages login --oidc --no-browser
|
pages login --oidc --no-browser
|
||||||
|
pages task preferences --wiki-prefix /private/mail
|
||||||
pages task --help
|
pages task --help
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -15,13 +16,35 @@ pages task --help
|
|||||||
```sh
|
```sh
|
||||||
pages task from-mail < message.eml
|
pages task from-mail < message.eml
|
||||||
pages task from-mail --project '開発 計画' --due 2026-11-03 < message.eml
|
pages task from-mail --project '開発 計画' --due 2026-11-03 < message.eml
|
||||||
# 本文を保存してよいメールに限り明示する
|
# このメールだけ保存先の親Pathを変更
|
||||||
pages task from-mail --include-body < message.eml
|
pages task from-mail --wiki-prefix /private/work-mail < message.eml
|
||||||
|
# 本文を送らず、件名とメタデータだけタスクにする
|
||||||
|
pages task from-mail --metadata-only < message.eml
|
||||||
```
|
```
|
||||||
|
|
||||||
既定では件名をタスク名、From・Date・Message-IDをメモにする。本文と添付はアップロードしない。include-bodyはplain text本文だけを追加し、HTML画像・添付・外部URLは取得しない。1通2 MiB、メモ16 KiBが上限。件名が300 UTF-8 bytesを超える場合は `--title '短い件名'` で指定する。
|
v0.3.0からは件名をタスク名、From・Date・Message-IDをメモにし、**本文を関連Wikiページに保存する**。PagesWiki v0.8.0以降が必要。保存先は `--wiki-prefix`、個人設定の既定Wiki親Path、選択プロジェクトのWiki配下(メモの階層)の順に決まる。どれも未設定なら保存を中止し、下書きを保持する。Webでは `/-/sys/config?panel=organizer` の「メール本文の既定Wiki親Path」で確認・変更できる。CLIで空文字を設定すると個人の既定Pathを解除できる。
|
||||||
|
|
||||||
同じ接続・本人・Message-IDから同じrequest_idを作るため、同じメールの再取り込みで重複しない。Message-IDなしはメール全体のSHA-256を使う。同じメールを別の独立タスクにもしたい場合は `task add` を使う。
|
本文の公開範囲は保存先Wikiの権限に従う。タスクが個人用でも、公開Pathに保存した本文は公開され得るため、メール用には閲覧者を制限したPathを指定する。設定例の `/private/mail` という名前自体が非公開を保証するものではない。
|
||||||
|
|
||||||
|
CLI v0.4.0のメール取り込みにはPagesWiki v0.9.0以降が必要。保存先は次の優先順で決める。
|
||||||
|
|
||||||
|
| メール | 保存先 |
|
||||||
|
| --- | --- |
|
||||||
|
| 先頭に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` を使う。
|
||||||
|
|
||||||
`~/.config/neomutt/neomuttrc` の例。NeoMuttから実行するPATHに `pages` を含めるか、コマンドをインストール先の絶対パスに置き換える。件名等をシェルコマンド文字列に展開せず、メールを標準入力で渡す。[設定ファイル例](../examples/neomuttrc)も配布アーカイブに同梱する。
|
`~/.config/neomutt/neomuttrc` の例。NeoMuttから実行するPATHに `pages` を含めるか、コマンドをインストール先の絶対パスに置き換える。件名等をシェルコマンド文字列に展開せず、メールを標準入力で渡す。[設定ファイル例](../examples/neomuttrc)も配布アーカイブに同梱する。
|
||||||
|
|
||||||
@@ -43,7 +66,9 @@ pages task retry REQUEST_UUID
|
|||||||
|
|
||||||
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
最大20件を保留でき、成功した要求はローカルから削除する。同じ本人への再ログインで保留分を維持する。別アカウントへ切り替える場合は別プロファイルを使う。認証済みセッションがない状態からの完全オフライン入力受付ではない。
|
||||||
|
|
||||||
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンもあるため、デバッグ目的で内容を貼り付けない。
|
同一の保留メールを再入力しても、確定済みの保存先を維持する。他のオプションを変更して保留要求を上書きすることは拒否する。保存成功後に新しい要求として取り込み直し、本文・保存先・年月などが変わった場合は412になるため、保存済みWikiを暗黙に移動しない。旧版からの保留分も `task retry` で元の要求のまま送る。
|
||||||
|
|
||||||
|
サーバーで保存された直後に応答が失われても、同じrequest_idで再送すれば既存タスクが返る。保留要求を書き換えて再送すると412になる。セッションファイルにはトークンと保留中のメール本文があるため、デバッグ目的で内容を貼り付けない。保存先未設定で失敗した場合は `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` で設定してからretryする。
|
||||||
|
|
||||||
## 計画と実績
|
## 計画と実績
|
||||||
|
|
||||||
@@ -100,6 +125,8 @@ Content-Typeはapplication/json、AuthorizationはBearerセッション。例示
|
|||||||
"request_id": "884587b2-6ae5-4aef-86d0-fd21dac39d1c",
|
"request_id": "884587b2-6ae5-4aef-86d0-fd21dac39d1c",
|
||||||
"title": "メールで依頼された内容を確認",
|
"title": "メールで依頼された内容を確認",
|
||||||
"notes": "Message-ID: <example@example.invalid>",
|
"notes": "Message-ID: <example@example.invalid>",
|
||||||
|
"wiki_body": "メール本文をテキストとして保存",
|
||||||
|
"wiki_prefix": "/private/mail",
|
||||||
"estimate_minutes": 30,
|
"estimate_minutes": 30,
|
||||||
"complexity": 2,
|
"complexity": 2,
|
||||||
"due_on": "2026-11-03"
|
"due_on": "2026-11-03"
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
# Merge into your own NeoMutt configuration; do not replace unrelated settings.
|
# Merge into your own NeoMutt configuration; do not replace unrelated settings.
|
||||||
# Run `pages configure` and `pages login` in a terminal first.
|
# Run `pages configure` and `pages login` in a terminal first.
|
||||||
|
# Configure `pages task preferences --wiki-prefix /YOUR/MAIL/PATH` first.
|
||||||
|
# v0.3.0 uploads the body to Wiki with the destination's visibility/ACL.
|
||||||
|
# Use `from-mail --metadata-only` if the body must not be uploaded.
|
||||||
# `pages` must be on NeoMutt's PATH; otherwise use its absolute install path.
|
# `pages` must be on NeoMutt's PATH; otherwise use its absolute install path.
|
||||||
# For a named connection, use `pages --profile work ...` in BOTH commands.
|
# For a named connection, use `pages --profile work ...` in BOTH commands.
|
||||||
# These pipe settings also affect other pipe-message commands.
|
# These pipe settings also affect other pipe-message commands.
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -10,6 +12,7 @@ import difflib
|
|||||||
import fcntl
|
import fcntl
|
||||||
import getpass
|
import getpass
|
||||||
import hashlib
|
import hashlib
|
||||||
|
from html.parser import HTMLParser
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -29,7 +32,7 @@ import urllib.parse as url
|
|||||||
import urllib.request as http
|
import urllib.request as http
|
||||||
import webbrowser
|
import webbrowser
|
||||||
|
|
||||||
VERSION = '0.2.0'
|
VERSION = '0.4.0'
|
||||||
|
|
||||||
class Failure(Exception):
|
class Failure(Exception):
|
||||||
def __init__(self, message, status=0, payload=None):
|
def __init__(self, message, status=0, payload=None):
|
||||||
@@ -480,21 +483,69 @@ def task_project(client, value):
|
|||||||
return matches[0]
|
return matches[0]
|
||||||
|
|
||||||
|
|
||||||
def task_mail(raw, include_body=False, override_title=None):
|
class MailText(HTMLParser):
|
||||||
|
"""Extract inert text; never load links, images, styles or attachments."""
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts, self.hidden = [], []
|
||||||
|
def handle_starttag(self, tag, attrs):
|
||||||
|
if tag in ('script','style','head'): self.hidden.append(tag)
|
||||||
|
if not self.hidden and tag in ('br','p','div','li','tr','h1','h2','h3','pre'): self.parts.append('\n')
|
||||||
|
def handle_endtag(self, tag):
|
||||||
|
if self.hidden and tag == self.hidden[-1]: self.hidden.pop()
|
||||||
|
if not self.hidden and tag in ('p','div','li','tr','h1','h2','h3','pre'): self.parts.append('\n')
|
||||||
|
def handle_data(self, 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):
|
||||||
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
|
||||||
if include_body:
|
if include_body:
|
||||||
part = message.get_body(preferencelist=('plain',))
|
content = ''
|
||||||
|
part = message.get_body(preferencelist=('plain','html'))
|
||||||
if part:
|
if part:
|
||||||
content = part.get_content()
|
try: content = part.get_content()
|
||||||
|
except (LookupError, UnicodeError, ValueError) as e: raise Failure('Mail body encoding is not supported; convert to UTF-8 first.') from e
|
||||||
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.')
|
||||||
notes += '\n\n' + content
|
if part.get_content_type() == 'text/html':
|
||||||
if len(notes.encode()) > 16384: raise Failure('Mail notes exceed 16 KiB; omit --include-body.')
|
parser = MailText();parser.feed(content);parser.close();content = ''.join(parser.parts).strip()
|
||||||
return title, notes, clean(message.get('Message-ID')) or hashlib.sha256(raw).hexdigest()
|
# 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 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
|
||||||
|
|
||||||
|
|
||||||
def tasks(client, profile, words):
|
def tasks(client, profile, words):
|
||||||
@@ -508,7 +559,9 @@ def tasks(client, profile, words):
|
|||||||
p=sub.add_parser(name)
|
p=sub.add_parser(name)
|
||||||
if name=='add':p.add_argument('title')
|
if name=='add':p.add_argument('title')
|
||||||
elif name=='update':p.add_argument('uuid',type=task_uuid);p.add_argument('--title')
|
elif name=='update':p.add_argument('uuid',type=task_uuid);p.add_argument('--title')
|
||||||
else:p.add_argument('--title');p.add_argument('--include-body',action='store_true')
|
else:
|
||||||
|
p.add_argument('--title');p.add_argument('--wiki-prefix',help='Wiki parent Path (otherwise use personal default or project Wiki subtree)')
|
||||||
|
body=p.add_mutually_exclusive_group();body.add_argument('--include-body',action='store_true',help='Save body to Wiki (default; retained for compatibility)');body.add_argument('--metadata-only',action='store_true',help='Do not upload body or create a Wiki document')
|
||||||
p.add_argument('--notes');p.add_argument('--project');p.add_argument('--assignee')
|
p.add_argument('--notes');p.add_argument('--project');p.add_argument('--assignee')
|
||||||
p.add_argument('--due');p.add_argument('--start-on');p.add_argument('--planned');p.add_argument('--review')
|
p.add_argument('--due');p.add_argument('--start-on');p.add_argument('--planned');p.add_argument('--review')
|
||||||
p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int,choices=range(1,6))
|
p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int,choices=range(1,6))
|
||||||
@@ -518,17 +571,20 @@ def tasks(client, profile, words):
|
|||||||
sub.add_parser('stop');sub.add_parser('status')
|
sub.add_parser('stop');sub.add_parser('status')
|
||||||
p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid)
|
p=sub.add_parser('retry');p.add_argument('request_id',type=task_uuid)
|
||||||
p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
|
p=sub.add_parser('report');p.add_argument('--from',dest='start');p.add_argument('--to',dest='end')
|
||||||
p=sub.add_parser('preferences');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone')
|
p=sub.add_parser('preferences');p.add_argument('--wiki-prefix');p.add_argument('--project');p.add_argument('--assignee');p.add_argument('--due-days',type=int);p.add_argument('--start-days',type=int);p.add_argument('--planned-days',type=int);p.add_argument('--review-days',type=int);p.add_argument('--estimate',type=int);p.add_argument('--complexity',type=int);p.add_argument('--digest',choices=['on','off']);p.add_argument('--at');p.add_argument('--timezone')
|
||||||
for child in sub.choices.values():child.add_argument('--json',action='store_true')
|
for child in sub.choices.values():child.add_argument('--json',action='store_true')
|
||||||
a=parser.parse_args(words);action=a.action
|
a=parser.parse_args(words);action=a.action
|
||||||
def emit(data): print(json.dumps(data,ensure_ascii=False,indent=2))
|
def emit(data): print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||||
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.')
|
||||||
|
if payload['request_id'] in pending and pending[payload['request_id']] != payload:raise Failure('A different draft with this request ID is retained. Use pages task retry '+payload['request_id'])
|
||||||
pending[payload['request_id']]=payload;profile.save()
|
pending[payload['request_id']]=payload;profile.save()
|
||||||
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
try: result=client.json(TASK_API+'capture',method='POST',data=payload)
|
||||||
except Failure:
|
except Failure as e:
|
||||||
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr);raise
|
print('Draft retained; retry with: pages task retry '+payload['request_id'],file=sys.stderr)
|
||||||
|
if e.payload.get('error') == 'wiki_prefix_required': raise Failure('Set a private Wiki destination first: pages task preferences --wiki-prefix /YOUR/MAIL/PATH',e.status) from e
|
||||||
|
raise
|
||||||
del pending[payload['request_id']];profile.save();return result
|
del pending[payload['request_id']];profile.save();return result
|
||||||
if action in ('list','projects'):
|
if action in ('list','projects'):
|
||||||
query={'kind':'project' if action=='projects' else 'task','view':getattr(a,'view','all'),'limit':100,'q':getattr(a,'q',''),'before':getattr(a,'before','')}
|
query={'kind':'project' if action=='projects' else 'task','view':getattr(a,'view','all'),'limit':100,'q':getattr(a,'q',''),'before':getattr(a,'before','')}
|
||||||
@@ -542,7 +598,7 @@ def tasks(client, profile, words):
|
|||||||
if action=='show':emit(client.json(TASK_API+'items/'+a.uuid));return
|
if action=='show':emit(client.json(TASK_API+'items/'+a.uuid));return
|
||||||
if action=='preferences':
|
if action=='preferences':
|
||||||
data=client.json(TASK_API+'preferences');p=data['preferences'];changed=False
|
data=client.json(TASK_API+'preferences');p=data['preferences'];changed=False
|
||||||
for attr,key in [('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
for attr,key in [('wiki_prefix','wiki_prefix'),('project','project_uuid'),('assignee','assignee_uuid'),('due_days','due_days'),('start_days','start_days'),('planned_days','planned_days'),('review_days','review_days'),('estimate','estimate_minutes'),('complexity','complexity'),('at','digest_time'),('timezone','timezone')]:
|
||||||
value=getattr(a,attr)
|
value=getattr(a,attr)
|
||||||
if value is not None:p[key]=task_project(client,value) if attr=='project' else value;changed=True
|
if value is not None:p[key]=task_project(client,value) if attr=='project' else value;changed=True
|
||||||
if a.digest:p['digest_enabled']=a.digest=='on';changed=True
|
if a.digest:p['digest_enabled']=a.digest=='on';changed=True
|
||||||
@@ -554,11 +610,22 @@ def tasks(client, profile, words):
|
|||||||
if action in ('add','from-mail'):
|
if action in ('add','from-mail'):
|
||||||
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':
|
||||||
title,notes,message_id=task_mail(sys.stdin.buffer.read((2<<20)+1),a.include_body,a.title)
|
if a.metadata_only and a.wiki_prefix is not None: raise Failure('--wiki-prefix cannot be combined with --metadata-only.')
|
||||||
|
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
|
||||||
|
payload['wiki_suffix']=task_mail_suffix(raw,payload['request_id'])
|
||||||
|
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. Other changed options still fail closed.
|
||||||
|
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
|
||||||
|
|||||||
+84
-3
@@ -9,15 +9,96 @@ 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_month_and_options_are_preserved(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))),self.assertRaises(m['Failure']):
|
||||||
|
m['tasks'](client,profile,['from-mail','--wiki-prefix','/changed'])
|
||||||
|
self.assertEqual(len(calls),2)
|
||||||
|
self.assertEqual(next(iter(profile.data['task_outbox'].values())),calls[0])
|
||||||
|
|
||||||
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=m['task_mail'](raw)
|
title,notes,ident,body=m['task_mail'](raw)
|
||||||
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
self.assertEqual(title,'Test');self.assertNotIn('PRIVATE BODY',notes);self.assertIn('Message-ID:',notes)
|
||||||
self.assertIn('PRIVATE BODY',m['task_mail'](raw,True)[1])
|
self.assertIn('PRIVATE BODY',body)
|
||||||
|
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):
|
||||||
|
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]
|
||||||
|
self.assertIn('Hello\n',body);self.assertIn('World & friends',body)
|
||||||
|
for value in ('secret','evil','https://'):self.assertNotIn(value,body)
|
||||||
|
for body in (b'a'*(256<<10),b'bad\0text'):
|
||||||
|
with self.assertRaises(m['Failure']):m['task_mail'](b'Subject: Test\r\n\r\n'+body)
|
||||||
|
|
||||||
|
def test_mail_payload_wiki_and_metadata_only(self):
|
||||||
|
from unittest.mock import patch
|
||||||
|
raw=b'Subject: Test\r\nMessage-ID: <same@example.invalid>\r\n\r\nPRIVATE BODY'
|
||||||
|
calls=[]
|
||||||
|
client=SimpleNamespace(base='https://example.invalid',json=lambda route,**kw:calls.append(kw['data'].copy()) or {'item':{'uuid':kw['data']['request_id']}})
|
||||||
|
profile=SimpleNamespace(data={'username':'test'},save=lambda:None)
|
||||||
|
for args in (['--wiki-prefix','/private/mail'],['--metadata-only']):
|
||||||
|
with patch('sys.stdin',SimpleNamespace(buffer=io.BytesIO(raw))),contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
m['tasks'](client,profile,['from-mail',*args])
|
||||||
|
self.assertIn('PRIVATE BODY',calls[0]['wiki_body']);self.assertNotIn('PRIVATE BODY',calls[0]['notes'])
|
||||||
|
self.assertEqual(calls[0]['wiki_prefix'],'/private/mail')
|
||||||
|
self.assertNotIn('wiki_body',calls[1]);self.assertEqual(calls[0]['request_id'],calls[1]['request_id'])
|
||||||
|
|
||||||
|
def test_multipart_prefers_plain_and_skips_attachment(self):
|
||||||
|
from email.message import EmailMessage
|
||||||
|
msg=EmailMessage();msg['Subject']='Mixed';msg.set_content('Plain body')
|
||||||
|
msg.add_alternative('<p>HTML alternate</p>',subtype='html')
|
||||||
|
msg.add_attachment(b'ATTACHMENT',maintype='application',subtype='octet-stream',filename='secret.bin')
|
||||||
|
body=m['task_mail'](msg.as_bytes())[3]
|
||||||
|
self.assertIn('Plain body',body);self.assertNotIn('alternate',body);self.assertNotIn('ATTACHMENT',body)
|
||||||
|
|
||||||
def test_capture_retains_request_until_explicit_retry(self):
|
def test_capture_retains_request_until_explicit_retry(self):
|
||||||
calls=[]
|
calls=[]
|
||||||
def send(route,**kwargs):
|
def send(route,**kwargs):
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
elif self.path=='/_/auth/logout':self.reply({})
|
elif self.path=='/_/auth/logout':self.reply({})
|
||||||
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
|
||||||
self.reply({'item':json.loads(body)})
|
item=json.loads(body)
|
||||||
|
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'})
|
||||||
else:self.send_error(404)
|
else:self.send_error(404)
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
if self.headers.get('Authorization')!='Bearer '+token:self.send_error(401);return
|
||||||
|
|||||||
Reference in new issue
Block a user