Compare commits

...

2 Commits

Author SHA1 Message Date
2d7906f8ee feat: mail 2024-11-28 10:01:55 +01:00
31c54083a9 feat: email client prototype 2024-11-05 15:58:41 +01:00
45 changed files with 2905 additions and 204 deletions

View File

@@ -53,7 +53,7 @@
"@types/geojson": "1.0.6",
"@types/node": "18.15.3",
"@types/node-cron": "3.0.7",
"@types/nodemailer": "6.4.7",
"@types/nodemailer": "6.4.15",
"@types/promise-queue": "2.2.0",
"@types/uuid": "8.3.4",
"body-parser": "1.20.2",
@@ -69,7 +69,7 @@
"nock": "13.3.1",
"node-cache": "5.1.2",
"node-cron": "3.0.2",
"nodemailer": "6.9.1",
"nodemailer": "6.9.14",
"prom-client": "14.1.1",
"promise-queue": "2.2.5",
"uuid": "8.3.2"

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
import './lib/cli.js';

View File

@@ -0,0 +1,70 @@
{
"name": "@openstapps/mail-plugin",
"description": "Mail Plugin",
"version": "3.2.0",
"private": true,
"type": "module",
"license": "GPL-3.0-only",
"author": "Thea Schöbl",
"bin": "app.js",
"files": [
"app.js",
"lib",
"README.md",
"CHANGELOG.md",
"Dockerfile"
],
"scripts": {
"build": "tsup-node --dts",
"deploy": "pnpm --prod --filter=@openstapps/minimal-plugin deploy ../../.deploy/minimal-plugin",
"dev": "tsup-node --watch --onSuccess \"pnpm run start\"",
"format": "prettier . -c --ignore-path ../../.gitignore",
"format:fix": "prettier --write . --ignore-path ../../.gitignore",
"lint": "eslint --ext .ts src/",
"lint:fix": "eslint --fix --ext .ts src/",
"start": "node app.js"
},
"dependencies": {
"@openstapps/core": "workspace:*",
"@openstapps/core-tools": "workspace:*",
"@openstapps/logger": "workspace:*",
"commander": "10.0.0",
"cors": "2.8.5",
"dotenv": "16.4.5",
"express": "4.18.2",
"imapflow": "1.0.162",
"mailparser": "3.7.1",
"node-forge": "1.3.1",
"nodemailer": "6.9.14",
"ts-node": "10.9.2"
},
"devDependencies": {
"@openstapps/eslint-config": "workspace:*",
"@openstapps/prettier-config": "workspace:*",
"@openstapps/tsconfig": "workspace:*",
"@types/cors": "2.8.13",
"@types/express": "4.17.17",
"@types/imapflow": "1.0.18",
"@types/mailparser": "3.4.4",
"@types/node": "18.15.3",
"@types/node-forge": "1.3.11",
"@types/nodemailer": "6.4.15",
"tsup": "6.7.0",
"typescript": "5.4.2"
},
"tsup": {
"entry": [
"src/cli.ts"
],
"sourcemap": true,
"clean": true,
"format": "esm",
"outDir": "lib"
},
"prettier": "@openstapps/prettier-config",
"eslintConfig": {
"extends": [
"@openstapps"
]
}
}

View File

@@ -0,0 +1,176 @@
import {config} from 'dotenv';
import {ImapFlow} from 'imapflow';
import {Logger} from '@openstapps/logger';
import {createHash} from 'node:crypto';
import express from 'express';
import cors from 'cors';
config({path: '.env.local'});
const app = express();
const port = process.env.PORT || 4000;
const maxClientAge = 10_000; // 10 seconds
const clients = new Map<string, {destroyRef: NodeJS.Timeout; client: Promise<ImapFlow>}>();
/**
*
*/
async function destroyClient(clientUid: string) {
const client = clients.get(clientUid);
if (!client) return;
clients.delete(clientUid);
clearTimeout(client.destroyRef);
try {
await client.client.then(it => it.logout());
} catch (error) {
await Logger.error(error);
}
}
app.use(cors());
app.use(async (request, response, next) => {
try {
const authorization = request.headers['authorization'];
if (!authorization) {
response.status(401).send();
return;
}
const clientUid = createHash('sha256').update(authorization).digest('hex');
let client = clients.get(clientUid);
if (client === undefined) {
const [user, pass] = Buffer.from(authorization.replace(/^Basic /, ''), 'base64')
.toString('utf8')
.split(':');
const imapClient = new ImapFlow({
host: 'imap.server.uni-frankfurt.de',
port: 993,
secure: true,
emitLogs: false,
auth: {user, pass},
});
client = {
destroyRef: undefined as unknown as NodeJS.Timeout,
client: imapClient.connect().then(() => imapClient),
};
clients.set(clientUid, client);
}
clearTimeout(client.destroyRef);
client.destroyRef = setTimeout(() => destroyClient(clientUid), maxClientAge);
response.locals.client = await client.client;
next();
} catch (error) {
await Logger.error(error);
response.status(500).send();
}
});
app.get('/', async (_request, response) => {
const result = await response.locals.client.listTree();
response.json(result);
});
app.get('/:mailbox', async (request, response) => {
try {
const preData = await response.locals.client.status(request.params.mailbox, {messages: true});
response.json({messages: preData.messages});
} catch (error) {
await Logger.error(error);
response.status(404).send();
}
});
app.get('/:mailbox/:id', async (request, response) => {
try {
await response.locals.client.mailboxOpen(request.params.mailbox, {readOnly: true});
const message = await response.locals.client.fetchOne(request.params.id, {
envelope: true,
labels: true,
flags: true,
bodyStructure: request.query.partial ? false : true,
});
response.json({
bodyStructure: request.query.partial ? undefined : message.bodyStructure,
labels: [...(message.labels ?? [])],
flags: [...(message.flags ?? [])],
envelope: message.envelope,
seq: message.seq,
});
} catch (error) {
await Logger.error(error);
response.status(404).send();
}
});
/**
*
*/
function parseFlags(query: Record<string, unknown>): string[] {
const rawFlags = query['flags'] ?? [];
const flagArray = Array.isArray(rawFlags) ? rawFlags : [rawFlags];
return flagArray.filter(it => typeof it === 'string');
}
app.post('/:mailbox/:id', async (request, response) => {
try {
await response.locals.client.mailboxOpen(request.params.mailbox, {readOnly: false});
response.json(await response.locals.client.messageFlagsAdd(request.params.id, parseFlags(request.query)));
} catch (error) {
await Logger.error(error);
response.status(404).send();
}
});
app.delete('/:mailbox/:id', async (request, response) => {
try {
await response.locals.client.mailboxOpen(request.params.mailbox, {readOnly: false});
if ('flags' in request.query) {
response.json(
await response.locals.client.messageFlagsRemove(request.params.id, parseFlags(request.query)),
);
} else {
response.json(await response.locals.client.messageDelete(request.params.id));
}
} catch (error) {
await Logger.error(error);
response.status(404).send();
}
});
app.get('/:mailbox/:id/:part', async (request, response) => {
try {
await response.locals.client.mailboxOpen(request.params.mailbox, {readOnly: true});
if (request.query.raw) {
const message = await response.locals.client.fetchOne(request.params.id, {
bodyParts: [`${request.params.part}.mime`, request.params.part],
});
response.write(message.bodyParts.get(`${request.params.part}.mime`));
response.write(message.bodyParts.get(request.params.part));
response.end();
} else {
const message = await response.locals.client.download(request.params.id, request.params.part);
message.content.on('data', chunk => {
response.write(chunk);
});
message.content.on('end', () => {
response.end();
});
}
} catch (error) {
await Logger.error(error);
response.status(404).send();
}
});
app.listen(port, () => {
Logger.info(`Server listening on port ${port}`);
});

9
backend/mail-plugin/src/types.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
import {ImapFlow} from 'imapflow';
declare global {
namespace Express {
interface Locals {
client: ImapFlow;
}
}
}

View File

@@ -0,0 +1,4 @@
{
"extends": "@openstapps/tsconfig",
"exclude": ["lib", "app.js"]
}

View File

@@ -32,6 +32,7 @@ platforms/
/plugins/
$RECYCLE.BIN/
dist/
.nx/
# ignore generated resources
resources/*/icon/
resources/*/splash/

View File

@@ -90,6 +90,7 @@
"@openstapps/core": "workspace:*",
"@transistorsoft/capacitor-background-fetch": "5.2.0",
"@types/dom-view-transitions": "1.0.4",
"asn1js": "3.0.5",
"capacitor-secure-storage-plugin": "0.9.0",
"cordova-plugin-calendar": "5.1.6",
"date-fns": "3.6.0",
@@ -98,6 +99,8 @@
"geojson": "0.5.0",
"ionic-appauth": "0.9.0",
"jsonpath-plus": "10.0.6",
"libbase64": "1.3.0",
"libqp": "2.1.0",
"maplibre-gl": "4.0.2",
"material-symbols": "0.17.1",
"moment": "2.30.1",
@@ -106,11 +109,14 @@
"ngx-markdown": "17.1.1",
"ngx-moment": "6.0.2",
"opening_hours": "3.8.0",
"pkijs": "3.1.0",
"pmtiles": "3.0.3",
"postal-mime": "2.2.5",
"rxjs": "7.8.1",
"semver": "7.6.0",
"swiper": "8.4.5",
"tslib": "2.6.2",
"zod": "3.23.8",
"zone.js": "0.14.4"
},
"devDependencies": {
@@ -139,9 +145,11 @@
"@ionic/cli": "7.2.0",
"@openstapps/prettier-config": "workspace:*",
"@openstapps/tsconfig": "workspace:*",
"@types/dompurify": "3.0.5",
"@types/fontkit": "2.0.7",
"@types/geojson": "1.0.6",
"@types/glob": "8.1.0",
"@types/imapflow": "1.0.18",
"@types/jasmine": "5.1.4",
"@types/jasminewd2": "2.0.13",
"@types/jsonpath": "0.2.0",
@@ -154,6 +162,7 @@
"@typescript-eslint/parser": "7.2.0",
"cordova-res": "0.15.4",
"cypress": "13.7.0",
"dompurify": "3.1.6",
"eslint": "8.57.0",
"eslint-plugin-jsdoc": "48.2.1",
"eslint-plugin-prettier": "5.1.3",

View File

@@ -0,0 +1,214 @@
{
"name": "@openstapps/app",
"description": "The generic app tailored to fulfill needs of German universities, written using Ionic Framework.",
"version": "3.3.2",
"private": true,
"license": "GPL-3.0-only",
"author": "Karl-Philipp Wulfert <krlwlfrt@gmail.com>",
"contributors": [
"Frank Nagel <frank.nagel@hrz.uni-marburg.de>",
"Jovan Krunić <jovan.krunic@gmail.com>",
"Michel Jonathan Schmitz <michel.jonathan.schmitz@its.thm.de>",
"Rainer Killinger <mail-openstapps@killinger.co>",
"Sebastian Lange <sebastianlange87@gmail.com>",
"Thea Schöbl <dev@theaninova.de>"
],
"scripts": {
"analyze": "webpack-bundle-analyzer www/stats.json",
"build": "pnpm check-icons && ng build --configuration=production --stats-json && webpack-bundle-analyzer www/stats.json --mode static --report www/bundle-info.html --no-open",
"build:analyze": "npm run build:stats && npm run analyze",
"build:android": "ionic capacitor build android --no-open && cd android && ./gradlew clean assemble && cd ..",
"build:prod": "ng build --configuration=production",
"build:stats": "ng build --configuration=production --stats-json",
"changelog": "conventional-changelog -p angular -i src/assets/about/CHANGELOG.md -s -r 0",
"check-icons": "node scripts/check-icon-correctness.mjs",
"chromium:no-cors": "chromium --disable-web-security --user-data-dir=\".browser-data/chromium\"",
"chromium:virtual-host": "chromium --host-resolver-rules=\"MAP mobile.app.uni-frankfurt.de:* localhost:8100\" --ignore-certificate-errors",
"cypress:open": "cypress open",
"cypress:run": "cypress run",
"docker:build": "sudo docker run -p 8100:8100 -p 35729:35729 -p 53703:53703 -v $PWD:/app -it registry.gitlab.com/openstapps/app bash -c \"npm install && npm run build\"",
"docker:build:android": "sudo docker run -p 8100:8100 -p 35729:35729 -p 53703:53703 -v $PWD:/app -it registry.gitlab.com/openstapps/app bash -c \"npm run build:android\"",
"docker:enter": "sudo docker run -p 8100:8100 -p 35729:35729 -p 53703:53703 -v $PWD:/app -it registry.gitlab.com/openstapps/app bash",
"docker:pull": "sudo docker pull registry.gitlab.com/openstapps/app",
"docker:run:android": "sudo docker run -v $PWD:/app --privileged -v /dev/bus/usb:/dev/bus/usb --net=host -it registry.gitlab.com/openstapps/app bash -c \"npm run run:android\"",
"docker:serve": "sudo docker run -p 8100:8100 -p 35729:35729 -p 53703:53703 -v $PWD:/app -it registry.gitlab.com/openstapps/app bash -c \"npm run start:external\"",
"e2e": "ng e2e",
"format": "prettier . -c",
"format:fix": "prettier --write .",
"licenses": "license-checker --json > src/assets/about/licenses.json && node ./scripts/accumulate-licenses.mjs && git add src/assets/about/licenses.json",
"lint": "ng lint && stylelint \"**/*.scss\"",
"lint:fix": "eslint --fix -c .eslintrc.json --ignore-path .eslintignore --ext .ts,.html src/ && stylelint --fix \"**/*.scss\"",
"minify-icons": "node scripts/minify-icon-font.mjs",
"postinstall": "jetify && echo \"skipping jetify in production mode\"",
"preview": "http-server www --p 8101 -o",
"push": "git push && git push origin \"v$npm_package_version\"",
"resources:ios": "capacitor-assets generate --ios --iconBackgroundColor $(grep -oE \"^@include ion-color\\(primary, #[a-fA-F0-9]{3,6}\" src/theme/colors.scss | grep -oE \"#[a-fA-F0-9]{3,6}\") --splashBackgroundColor $(grep -oE \"^@include ion-color\\(primary, #[a-fA-F0-9]{3,6}\" src/theme/colors.scss | grep -oE \"#[a-fA-F0-9]{3,6}\")",
"run:android": "ionic capacitor run android --livereload --external",
"start": "ionic serve",
"start:external": "ionic serve --external",
"start:prod": "ionic serve --prod",
"start:virtual-host": "ionic serve --public-host=mobile.app.uni-frankfurt.de --ssl=true --open=false",
"test": "ng test --code-coverage",
"test:integration": "sh integration-test.sh"
},
"dependencies": {
"@angular/animations": "17.3.0",
"@angular/cdk": "17.3.0",
"@angular/common": "17.3.0",
"@angular/core": "17.3.0",
"@angular/forms": "17.3.0",
"@angular/platform-browser": "17.3.0",
"@angular/router": "17.3.0",
"@awesome-cordova-plugins/calendar": "6.6.0",
"@awesome-cordova-plugins/core": "6.6.0",
"@capacitor-community/screen-brightness": "6.0.0",
"@capacitor/app": "6.0.0",
"@capacitor/browser": "6.0.1",
"@capacitor/clipboard": "6.0.0",
"@capacitor/core": "6.1.1",
"@capacitor/device": "6.0.0",
"@capacitor/dialog": "6.0.0",
"@capacitor/filesystem": "6.0.0",
"@capacitor/geolocation": "6.0.0",
"@capacitor/haptics": "6.0.0",
"@capacitor/keyboard": "6.0.1",
"@capacitor/local-notifications": "6.0.0",
"@capacitor/network": "6.0.1",
"@capacitor/preferences": "6.0.1",
"@capacitor/screen-orientation": "6.0.1",
"@capacitor/share": "6.0.1",
"@capacitor/splash-screen": "6.0.1",
"@ionic-native/core": "5.36.0",
"@ionic/angular": "7.8.0",
"@ionic/storage-angular": "4.0.0",
"@maplibre/ngx-maplibre-gl": "17.4.1",
"@ngx-translate/core": "15.0.0",
"@ngx-translate/http-loader": "8.0.0",
"@openid/appauth": "1.3.1",
"@openstapps/api": "workspace:*",
"@openstapps/collection-utils": "workspace:*",
"@openstapps/core": "workspace:*",
"@transistorsoft/capacitor-background-fetch": "5.2.0",
"@types/dom-view-transitions": "1.0.4",
"asn1js": "3.0.5",
"capacitor-secure-storage-plugin": "0.9.0",
"cordova-plugin-calendar": "5.1.6",
"date-fns": "3.6.0",
"deepmerge": "4.3.1",
"form-data": "4.0.0",
"geojson": "0.5.0",
"ionic-appauth": "0.9.0",
<<<<<<< HEAD
"jsonpath-plus": "10.0.6",
"libbase64": "1.3.0",
"libqp": "2.1.0",
||||||| parent of cff9b026 (fix: pipeline)
"jsonpath-plus": "6.0.1",
"libbase64": "^1.3.0",
"libqp": "^2.1.0",
=======
"jsonpath-plus": "6.0.1",
"libbase64": "1.3.0",
"libqp": "2.1.0",
>>>>>>> cff9b026 (fix: pipeline)
"maplibre-gl": "4.0.2",
"material-symbols": "0.17.1",
"moment": "2.30.1",
"ngx-date-fns": "11.0.0",
"ngx-logger": "5.0.12",
"ngx-markdown": "17.1.1",
"ngx-moment": "6.0.2",
"opening_hours": "3.8.0",
"pkijs": "3.1.0",
"pmtiles": "3.0.3",
"postal-mime": "2.2.5",
"rxjs": "7.8.1",
"semver": "7.6.0",
"swiper": "8.4.5",
"tslib": "2.6.2",
"zod": "3.23.8",
"zone.js": "0.14.4"
},
"devDependencies": {
"@angular-devkit/architect": "0.1703.0",
"@angular-devkit/build-angular": "17.3.0",
"@angular-devkit/core": "17.3.0",
"@angular-devkit/schematics": "17.3.0",
"@angular-eslint/builder": "17.3.0",
"@angular-eslint/eslint-plugin": "17.3.0",
"@angular-eslint/eslint-plugin-template": "17.3.0",
"@angular-eslint/schematics": "17.3.0",
"@angular-eslint/template-parser": "17.3.0",
"@angular/cli": "17.3.0",
"@angular/compiler": "17.3.0",
"@angular/compiler-cli": "17.3.0",
"@angular/language-server": "17.3.0",
"@angular/language-service": "17.3.0",
"@angular/platform-browser-dynamic": "17.3.0",
"@capacitor/android": "6.1.1",
"@capacitor/assets": "3.0.4",
"@capacitor/cli": "6.1.1",
"@capacitor/ios": "6.1.1",
"@compodoc/compodoc": "1.1.23",
"@cypress/schematic": "2.5.1",
"@ionic/angular-toolkit": "11.0.1",
"@ionic/cli": "7.2.0",
"@openstapps/prettier-config": "workspace:*",
"@openstapps/tsconfig": "workspace:*",
"@types/dompurify": "3.0.5",
"@types/fontkit": "2.0.7",
"@types/geojson": "1.0.6",
"@types/glob": "8.1.0",
"@types/imapflow": "1.0.18",
"@types/jasmine": "5.1.4",
"@types/jasminewd2": "2.0.13",
"@types/jsonpath": "0.2.0",
"@types/karma": "6.3.8",
"@types/karma-coverage": "2.0.3",
"@types/karma-jasmine": "4.0.5",
"@types/node": "18.15.3",
"@types/semver": "7.5.8",
"@typescript-eslint/eslint-plugin": "7.2.0",
"@typescript-eslint/parser": "7.2.0",
"cordova-res": "0.15.4",
"cypress": "13.7.0",
"dompurify": "3.1.6",
"eslint": "8.57.0",
"eslint-plugin-jsdoc": "48.2.1",
"eslint-plugin-prettier": "5.1.3",
"eslint-plugin-unicorn": "51.0.1",
"fast-deep-equal": "3.1.3",
"fontkit": "2.0.2",
"glob": "10.3.10",
"http-server": "14.1.1",
"is-docker": "2.2.1",
"jasmine-core": "5.1.2",
"jasmine-spec-reporter": "7.0.0",
"jetifier": "2.0.0",
"junit-report-merger": "6.0.3",
"karma": "6.4.3",
"karma-chrome-launcher": "3.2.0",
"karma-coverage": "2.2.1",
"karma-jasmine": "5.1.0",
"karma-junit-reporter": "2.0.1",
"karma-mocha-reporter": "2.2.5",
"license-checker": "25.0.1",
"stylelint": "16.3.1",
"stylelint-config-clean-order": "5.4.1",
"stylelint-config-prettier-scss": "1.0.0",
"stylelint-config-recommended-scss": "14.0.0",
"stylelint-config-standard-scss": "13.0.0",
"surge": "0.23.1",
"ts-node": "10.9.2",
"typescript": "5.4.2",
"webpack-bundle-analyzer": "4.10.1"
},
"cordova": {
"plugins": {},
"platforms": [
"ios",
"browser",
"android"
]
}
}

View File

@@ -15,12 +15,11 @@
import {CommonModule, LocationStrategy, PathLocationStrategy, registerLocaleData} from '@angular/common';
import {HTTP_INTERCEPTORS, HttpClient, HttpClientModule} from '@angular/common/http';
import localeDe from '@angular/common/locales/de';
import {APP_INITIALIZER, NgModule} from '@angular/core';
import {APP_INITIALIZER, Injectable, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {RouteReuseStrategy} from '@angular/router';
import {IonicModule, IonicRouteStrategy, Platform} from '@ionic/angular';
import {TranslateLoader, TranslateModule, TranslateService} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import moment from 'moment';
import 'moment/min/locales';
import {LoggerModule, NGXLogger, NgxLoggerLevel} from 'ngx-logger';
@@ -71,6 +70,8 @@ import {Capacitor} from '@capacitor/core';
import {SplashScreen} from '@capacitor/splash-screen';
import maplibregl from 'maplibre-gl';
import {Protocol} from 'pmtiles';
import {MailModule} from './modules/mail/mail.module';
import {Observable, from} from 'rxjs';
registerLocaleData(localeDe);
@@ -129,12 +130,16 @@ export function initializerFactory(
};
}
/**
* TODO
* @param http TODO
*/
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
@Injectable({providedIn: 'root'})
export class ImportTranslateLoader {
static translations: Record<string, () => Promise<{default: object}>> = {
de: () => import('../assets/i18n/de.json'),
en: () => import('../assets/i18n/en.json'),
};
getTranslation(lang: string): Observable<object> {
return from(ImportTranslateLoader.translations[lang]().then(it => it.default));
}
}
/**
@@ -165,6 +170,7 @@ export function createTranslateLoader(http: HttpClient) {
ProfilePageModule,
FeedbackModule,
MapModule,
MailModule,
MenuModule,
NavigationModule,
NewsModule,
@@ -177,7 +183,7 @@ export function createTranslateLoader(http: HttpClient) {
loader: {
deps: [HttpClient],
provide: TranslateLoader,
useFactory: createTranslateLoader,
useClass: ImportTranslateLoader,
},
}),
UtilModule,

View File

@@ -0,0 +1,332 @@
import {HttpClient} from '@angular/common/http';
import {Injectable, inject} from '@angular/core';
import {Observable, map, catchError, tap, mergeMap, forkJoin, of} from 'rxjs';
import {
Email,
EmailWithoutBody,
MailboxTreeRoot,
RawEmail,
RawEmailBodyStructure,
Signature,
SignedValue,
} from './schema';
import {ContentInfo, SignedData} from 'pkijs';
import PostalMime from 'postal-mime';
import {z} from 'zod';
function value(value: undefined): undefined;
function value<T>(value: T): SignedValue<T>;
/**
*
*/
function value<T>(value: T | undefined): SignedValue<T> | undefined {
return value === undefined ? undefined : {value};
}
@Injectable({providedIn: 'root'})
export class MailAdapterService {
httpClient = inject(HttpClient);
request<T>(options: {
method?: string;
path?: string[];
options?: Record<string, string | string[]>;
responseType?: 'json' | 'arraybuffer';
credentials?: string;
}): Observable<T> {
return this.httpClient.request<T>(
options.method ?? 'GET',
`http://localhost:4000/${options.path?.map(encodeURIComponent).join('/') ?? ''}${
options.options
? `?${Object.entries(options.options)
.flatMap(([key, values]) =>
(Array.isArray(values) ? values : [values]).map(
value => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`,
),
)
.join('&')}`
: ''
}`,
{
responseType: options.responseType as 'json',
headers: options.credentials ? {authorization: `Basic ${options.credentials}`} : undefined,
},
);
}
checkCredentials(credentials: string): Observable<boolean> {
return this.request<unknown>({
path: [],
options: {},
responseType: 'json',
credentials,
}).pipe(
map(() => true),
catchError(error => {
if (error.status === 401) {
return of(false);
} else {
throw error;
}
}),
);
}
listMailboxes(credentials: string): Observable<MailboxTreeRoot> {
return this.request<string[]>({credentials}).pipe(mergeMap(it => MailboxTreeRoot.parseAsync(it)));
}
countEmails(credentials: string, mailbox: string, since?: string): Observable<number> {
return this.request<unknown>({
credentials,
path: [mailbox],
options: since === undefined ? undefined : {since},
}).pipe(
mergeMap(it => z.object({messages: z.number()}).parseAsync(it)),
map(it => it.messages),
);
}
private getRawEmail(
credentials: string,
mailbox: string,
id: string,
partial: boolean,
): Observable<RawEmail> {
return this.request<unknown>({
credentials,
path: [mailbox, id],
options: partial ? {raw: 'true', partial: 'true'} : {raw: 'true'},
}).pipe(mergeMap(it => RawEmail.parseAsync(it)));
}
private getPart(credentials: string, mailbox: string, id: string, part: string): Observable<ArrayBuffer> {
return this.request<ArrayBuffer>({path: [mailbox, id, part], credentials, responseType: 'arraybuffer'});
}
getRawPart(credentials: string, mailbox: string, id: string, part: string): Observable<ArrayBuffer> {
return this.request({
path: [mailbox, id, part],
options: {raw: 'true'},
responseType: 'arraybuffer',
credentials,
});
}
private resolveRawEmail(
credentials: string,
mailbox: string,
email: RawEmail,
): Observable<Email | EmailWithoutBody> {
if (
email.bodyStructure?.type === 'application/x-pkcs7-mime' ||
email.bodyStructure?.type === 'application/pkcs7-mime'
) {
return this.getRawPart(credentials, mailbox, email.seq, email.bodyStructure.part ?? 'TEXT').pipe(
mergeMap(async buffer => {
const info = ContentInfo.fromBER(buffer);
const signedData = new SignedData({schema: info.content});
const valid = await signedData
.verify({signer: 0, data: signedData.encapContentInfo.eContent?.valueBeforeDecodeView})
.catch(() => false);
const content = new TextDecoder().decode(
signedData.encapContentInfo.eContent?.valueBeforeDecodeView,
);
const signedEmail = await PostalMime.parse(content);
function signed(value: undefined): undefined;
function signed<T>(value: T): SignedValue<T>;
/**
*
*/
function signed<T>(value: T | undefined): SignedValue<T> | undefined {
return value === undefined
? undefined
: {
value,
signature: {
type: 'pkcs7',
valid,
},
};
}
const result: Email = {
id: email.seq,
mailbox,
subject: signedEmail.subject ? signed(signedEmail.subject) : value(email.envelope.subject),
flags: new Set<string>(), //TODO
from: signed({
name: signedEmail.from.name || undefined,
address: signedEmail.from.address || undefined,
}),
to: signedEmail.to?.map(({name, address}) =>
signed({
name,
address,
}),
),
date: signedEmail.date ? signed(new Date(signedEmail.date)) : value(email.envelope.date),
html: signedEmail.html ? signed(signedEmail.html) : undefined,
text: signedEmail.text ? signed(signedEmail.text) : undefined,
attachments: [],
};
return result;
}),
);
}
const traverse = (
item: RawEmailBodyStructure,
result: Pick<Email, 'attachments' | 'text' | 'html'>,
signature?: Signature,
): Observable<Pick<Email, 'attachments' | 'text' | 'html'>> => {
// https://datatracker.ietf.org/doc/html/rfc1847#section-2.1
if (item.type === 'multipart/signed' && item.parameters?.protocol === 'application/pkcs7-signature') {
return forkJoin({
data: this.getPart(credentials, mailbox, email.seq, item.childNodes![0].part!),
signature: this.getRawPart(credentials, mailbox, email.seq, item.childNodes![1].part!),
}).pipe(
mergeMap(({data, signature}) => {
const info = ContentInfo.fromBER(signature);
const signedData = new SignedData({schema: info.content});
return signedData.verify({signer: 0, data});
}),
catchError(error => {
console.log(error);
return of(false);
}),
mergeMap(valid => traverse(item.childNodes![0], result, {type: 'pkcs7', valid})),
);
} else if (item.type.startsWith('multipart/')) {
return forkJoin(item.childNodes!.map(child => traverse(child, result, signature))).pipe(
map(children => children[0]),
);
} else if (item.type === 'text/plain') {
return this.getPart(credentials, mailbox, email.seq, item.part ?? 'TEXT').pipe(
map(text => {
result.text = {value: new TextDecoder().decode(text), signature};
return result;
}),
);
} else if (item.type === 'text/html') {
return this.getPart(credentials, mailbox, email.seq, item.part ?? 'TEXT').pipe(
map(html => {
result.html = {value: new TextDecoder().decode(html), signature};
return result;
}),
);
} else if (item.part === undefined) {
return of(result);
} else {
result.attachments.push({
value: {
part: item.part,
size: item.size ?? Number.NaN,
filename: item.parameters?.['name'] ?? item.part,
},
});
return of(result);
}
};
const emailWithoutBody: Omit<EmailWithoutBody, 'partial'> = {
id: email.seq,
mailbox,
flags: new Set<string>(email.flags),
subject: value(email.envelope.subject),
from: email.envelope.from[0]
? value({
name: email.envelope.from[0].name,
address: email.envelope.from[0].address,
})
: value({
name: email.envelope.sender[0].name,
address: email.envelope.sender[0].address,
}),
to: email.envelope.to?.map(({name, address}) =>
value({
name,
address,
}),
),
cc: email.envelope.cc?.map(({name, address}) =>
value({
name,
address,
}),
),
bcc: email.envelope.bcc?.map(({name, address}) =>
value({
name,
address,
}),
),
date: value(email.envelope.date),
};
return email.bodyStructure === undefined
? of({...emailWithoutBody, partial: true})
: traverse(email.bodyStructure, {attachments: []}).pipe(
map(
partial =>
({
...partial,
...emailWithoutBody,
}) satisfies Email,
),
tap(console.log),
);
}
getEmail(
credentials: string,
mailbox: string,
id: string,
partial: boolean,
): Observable<Email | EmailWithoutBody> {
return this.getRawEmail(credentials, mailbox, id, partial).pipe(
mergeMap(it => this.resolveRawEmail(credentials, mailbox, it)),
);
}
addFlags(credentials: string, mailbox: string, id: string, flags: string | string[]): Observable<boolean> {
return Array.isArray(flags) && flags.length === 0
? of(true)
: this.request<boolean>({
credentials,
method: 'POST',
path: [mailbox, id],
options: {
flags: flags,
},
});
}
removeFlags(
credentials: string,
mailbox: string,
id: string,
flags: string | string[],
): Observable<boolean> {
return Array.isArray(flags) && flags.length === 0
? of(true)
: this.request<boolean>({
credentials,
method: 'DELETE',
path: [mailbox, id],
options: {
flags: flags,
},
});
}
deleteEmail(credentials: string, mailbox: string, id: string): Observable<boolean> {
return this.request<boolean>({
credentials,
method: 'DELETE',
path: [mailbox, id],
});
}
}

View File

@@ -0,0 +1,102 @@
import {ChangeDetectionStrategy, Component, inject, signal} from '@angular/core';
import {AsyncPipe, TitleCasePipe} from '@angular/common';
import {IonRouterOutlet, IonicModule} from '@ionic/angular';
import {DataModule} from '../data/data.module';
import {IonIconModule} from 'src/app/util/ion-icon/ion-icon.module';
import {UtilModule} from 'src/app/util/util.module';
import {FormatPurePipeModule, ParseIsoPipeModule} from 'ngx-date-fns';
import {ActivatedRoute, RouterModule} from '@angular/router';
import {firstValueFrom, map, mergeMap, take} from 'rxjs';
import {DomSanitizer} from '@angular/platform-browser';
import {materialFade} from 'src/app/animation/material-motion';
import {TranslateModule} from '@ngx-translate/core';
import {ShadowHtmlDirective} from 'src/app/util/shadow-html.directive';
import {MailStorageProvider} from './mail-storage.provider';
import {DataSizePipe} from '../../util/data-size.pipe';
import {EmailAttachment, EmailAttachmentRemote} from './schema';
import {MailService} from './mail.service';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
@Component({
selector: 'stapps-mail-detail',
templateUrl: 'mail-detail.html',
styleUrl: 'mail-detail.scss',
animations: [materialFade],
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
AsyncPipe,
IonicModule,
DataModule,
IonIconModule,
UtilModule,
FormatPurePipeModule,
ParseIsoPipeModule,
RouterModule,
ShadowHtmlDirective,
TranslateModule,
TitleCasePipe,
DataSizePipe,
],
})
export class MailDetailComponent {
readonly activatedRoute = inject(ActivatedRoute);
readonly mailStorage = inject(MailStorageProvider);
readonly mailService = inject(MailService);
readonly sanitizer = inject(DomSanitizer);
readonly router = inject(IonRouterOutlet);
parameters = this.activatedRoute.paramMap.pipe(
map(parameters => ({
mailbox: parameters.get('mailbox')!,
id: parameters.get('id')!,
})),
);
mail = this.parameters.pipe(mergeMap(({mailbox, id}) => this.mailStorage.getEmail(mailbox, id)));
collapse = signal(false);
constructor() {
this.mail.pipe(take(1), takeUntilDestroyed()).subscribe(mail => {
this.mailStorage.addFlags(mail, ['\\Seen']);
});
}
async markUnread() {
await this.mailStorage.removeFlags(await firstValueFrom(this.mail), ['\\Seen']);
await this.router.pop();
}
async delete() {
this.mailStorage.deleteEmail(await firstValueFrom(this.mail));
await this.router.pop();
}
async downloadAttachment(attachment: EmailAttachment) {
const data = await firstValueFrom(
this.mail.pipe(
take(1),
mergeMap(mail =>
this.mailService.downloadAttachment(
mail.mailbox,
mail.id,
(attachment as EmailAttachmentRemote).part,
),
),
),
);
const url = URL.createObjectURL(new Blob([data], {}));
const a = document.createElement('a');
a.href = url;
a.download = attachment.filename;
a.click();
URL.revokeObjectURL(url);
a.remove();
}
}

View File

@@ -0,0 +1,81 @@
<ion-header>
<ion-toolbar color="primary" mode="ios">
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title
[style.opacity]="(collapse() ? '1' : '0') + '!important'"
[style.translate]="collapse() ? '0' : '0 10px'"
>
@if (mail | async; as mail) {
{{ mail.subject?.value }}
} @else {
<ion-skeleton-text animated style="width: 100px; height: 20px"></ion-skeleton-text>
}
</ion-title>
<ion-buttons slot="end">
<ion-button (click)="delete()">
<ion-icon slot="icon-only" name="delete"></ion-icon>
</ion-button>
<ion-button (click)="markUnread()">
<ion-icon slot="icon-only" name="mark_email_unread"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content [scrollEvents]="true" (ionScroll)="collapse.set($any($event).detail.scrollTop > 50)">
@if (mail | async; as mail) {
<h1 @materialFade>{{ mail.subject?.value }}</h1>
<aside @materialFade>
<div class="from">
@if (mail.from.value.name) {
<strong>
{{ mail.from.value.name }}
</strong>
}
{{ mail.from.value.address }}
@if (mail.from.signature?.valid === true) {
<ion-icon name="verified" [fill]="true" @materialFade></ion-icon>
} @else if (mail.from.signature?.valid === false) {
<ion-icon name="gpp_bad" color="danger" [fill]="true" @materialFade></ion-icon>
}
</div>
<div class="to">
<strong>to</strong>
@for (to of mail.to; track to) {
<span>{{ to.value.name || to.value.address }}</span>
}
</div>
@if (mail.cc) {
<div class="cc">
cc
@for (cc of mail.cc; track cc) {
<span>{{ cc.value.name || cc.value.address }}</span>
}
</div>
}
@if (mail.date) {
<time [dateTime]="mail.date">{{ mail.date.value | dfnsFormatPure: 'PPp' }}</time>
}
</aside>
@if (mail.html) {
<main @materialFade>
<div class="html" [shadowHTML]="mail.html.value"></div>
</main>
} @else if (mail.text) {
<main @materialFade>
<pre>{{ mail.text.value }}</pre>
</main>
}
<div class="attachments">
@for (attachment of mail.attachments; track attachment) {
<ion-button class="attachment" fill="outline" (click)="downloadAttachment(attachment.value)">
<ion-icon slot="start" name="download"></ion-icon>
<ion-label>{{ attachment.value.filename }} ({{ attachment.value.size | dataSize }})</ion-label>
</ion-button>
}
</div>
}
</ion-content>

View File

@@ -0,0 +1,118 @@
@import '../../../theme/util/mixins';
ion-item {
margin-block-end: var(--spacing-xl);
}
ion-title {
transition:
opacity 0.2s ease,
translate 0.2s ease;
}
h1 {
margin: var(--spacing-sm) var(--spacing-md);
font-weight: var(--font-weight-bold);
color: var(--ion-color-primary-contrast);
}
aside {
display: flex;
flex-direction: column;
margin: var(--spacing-xs) var(--spacing-md);
color: var(--ion-color-primary-contrast);
}
.to {
display: flex;
gap: var(--spacing-xs);
align-items: center;
justify-content: flex-start;
> span:has(+ span)::after {
content: ',';
}
}
.from {
display: flex;
gap: var(--spacing-xs);
align-items: center;
justify-content: flex-start;
}
main {
@include border-radius-in-parallax(var(--border-radius-default));
margin: var(--spacing-md);
padding: var(--spacing-md);
background: var(--ion-item-background);
}
ion-list {
background: none;
}
ion-card {
ion-card-header {
padding-block: var(--spacing-sm);
padding-inline: var(--spacing-sm);
ion-card-title {
font-size: 1rem;
}
}
ion-card-content {
padding-block: 0;
padding-inline: 0;
}
}
.html {
overflow-x: auto;
}
pre {
font-family: inherit;
word-wrap: break-word;
white-space: pre-wrap;
}
footer {
// css hack to make the element stick to the bottom of the scroll container even
// when the content is not filling it
position: sticky;
top: 100vh;
> div {
margin: var(--spacing-lg);
opacity: 0.8;
}
td {
padding-inline-start: var(--spacing-md);
word-break: break-word;
}
code {
font-size: inherit;
}
}
.attachments {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-md);
margin-block-end: var(--spacing-xl);
margin-inline: var(--spacing-md);
}
.attachment[fill='outline']::part(native) {
border: 1px solid currentcolor;
}
ion-content::part(background) {
background: none;
}

View File

@@ -0,0 +1,65 @@
import {AsyncPipe, TitleCasePipe} from '@angular/common';
import {ChangeDetectionStrategy, Component, WritableSignal, computed, inject, signal} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {IonicModule} from '@ionic/angular';
import {TranslateModule} from '@ngx-translate/core';
import {IonIconModule} from 'src/app/util/ion-icon/ion-icon.module';
import {UtilModule} from 'src/app/util/util.module';
import {MailService} from './mail.service';
import {Observable, of, map, catchError, startWith, shareReplay, tap, take} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
@Component({
selector: 'stapps-mail-login',
templateUrl: 'mail-login.html',
styleUrl: 'mail-login.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [IonicModule, UtilModule, TranslateModule, TitleCasePipe, IonIconModule, FormsModule, AsyncPipe],
})
export class MailLoginComponent {
showPassword = signal(false);
email = signal('');
password = signal('');
// eslint-disable-next-line unicorn/no-useless-undefined
error: WritableSignal<Observable<string | undefined>> = signal(of(undefined));
loading = computed(() =>
this.error().pipe(
map(() => false),
startWith(true),
),
);
mailService = inject(MailService);
router = inject(Router);
activatedRoute = inject(ActivatedRoute);
submit(event: SubmitEvent) {
event.preventDefault();
const form = event.target as HTMLFormElement;
if (form.checkValidity()) {
this.error.set(
this.mailService.login(this.email(), this.password()).pipe(
tap(success => {
if (success) {
this.activatedRoute.data.pipe(take(1)).subscribe(data => {
this.router.navigate(data.redirectTo);
});
}
}),
map(success => (success ? undefined : 'mail.login.error.INVALID_CREDENTIALS')),
catchError(error => of(error.message)),
shareReplay(1),
),
);
} else {
form.reportValidity();
}
}
}

View File

@@ -0,0 +1,67 @@
<ion-header>
<ion-toolbar color="primary" mode="ios">
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content parallax>
<h1>{{ 'mail.login.TITLE' | translate | titlecase }}</h1>
<form (ngSubmit)="submit($event)">
<ion-input
[attr.aria-label]="'mail.login.PLACEHOLDER_USERNAME' | translate | titlecase"
[placeholder]="'mail.login.PLACEHOLDER_USERNAME' | translate | titlecase"
[(ngModel)]="email"
[required]="true"
[disabled]="(error() | async) !== null ? false : true"
autocomplete="username"
enterkeyhint="next"
color="primary"
name="username"
type="text"
>
<ion-icon slot="start" name="account_circle" aria-hiden="true"></ion-icon>
</ion-input>
<ion-input
[attr.aria-label]="'mail.login.PLACEHOLDER_PASSWORD' | translate | titlecase"
[placeholder]="'mail.login.PLACEHOLDER_PASSWORD' | translate | titlecase"
[(ngModel)]="password"
[required]="true"
[disabled]="(error() | async) !== null ? false : true"
autocomplete="current-password"
enterkeyhint="go"
name="password"
[type]="showPassword() ? 'text' : 'password'"
>
<ion-icon slot="start" name="password" aria-hidden="true"></ion-icon>
<ion-button
fill="clear"
slot="end"
color="medium"
aria-label="Show/hide"
(click)="showPassword.set(!showPassword())"
>
<ion-icon
[size]="20"
[fill]="!showPassword()"
slot="icon-only"
name="visibility"
aria-hidden="true"
></ion-icon>
</ion-button>
</ion-input>
@if (error() | async; as error) {
<ion-note color="danger">{{ error | translate | titlecase }}</ion-note>
}
<ion-button
fill="outline"
color="primary"
type="submit"
[disabled]="(error() | async) !== null ? false : true"
>
<ion-icon slot="start" name="login" aria-hidden="true"></ion-icon>
{{ 'mail.login.LOGIN' | translate | titlecase }}
</ion-button>
</form>
</ion-content>

View File

@@ -0,0 +1,17 @@
h1 {
margin-inline: auto;
color: var(--ion-color-primary-contrast);
}
form {
display: flex;
flex-direction: column;
align-items: flex-end;
max-width: 30em;
margin: var(--spacing-xxl) auto;
padding: var(--spacing-xl);
background: var(--ion-item-background);
border-radius: var(--border-radius-default);
}

View File

@@ -0,0 +1,60 @@
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {MailService} from './mail.service';
import {AsyncPipe, TitleCasePipe} from '@angular/common';
import {IonicModule} from '@ionic/angular';
import {DataModule} from '../data/data.module';
import {IonIconModule} from 'src/app/util/ion-icon/ion-icon.module';
import {UtilModule} from 'src/app/util/util.module';
import {FormatPurePipeModule, IsTodayPipeModule} from 'ngx-date-fns';
import {ActivatedRoute, RouterModule} from '@angular/router';
import {map, mergeMap} from 'rxjs';
import {MailStorageProvider} from './mail-storage.provider';
import {MailboxTreeItem} from './schema';
import {SCIcon} from 'src/app/util/ion-icon/icon';
import {TranslateModule} from '@ngx-translate/core';
@Component({
selector: 'stapps-mail-page',
templateUrl: 'mail-page.html',
styleUrl: 'mail-page.scss',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
AsyncPipe,
IonicModule,
DataModule,
IonIconModule,
UtilModule,
FormatPurePipeModule,
IsTodayPipeModule,
RouterModule,
TranslateModule,
TitleCasePipe,
],
})
export class MailPageComponent {
readonly activatedRoute = inject(ActivatedRoute);
readonly mailService = inject(MailService);
readonly mailStorage = inject(MailStorageProvider);
mailIcons: Record<Exclude<MailboxTreeItem['specialUse'], undefined>, keyof typeof SCIcon> = {
'\\Inbox': SCIcon.inbox,
'\\All': SCIcon.all_inbox,
'\\Archive': SCIcon.archive,
'\\Drafts': SCIcon.drafts,
'\\Flagged': SCIcon.flag,
'\\Junk': SCIcon.folder,
'\\Sent': SCIcon.send,
'\\Trash': SCIcon.delete,
};
mailbox = this.activatedRoute.paramMap.pipe(
mergeMap(parameters =>
this.mailStorage.mailboxes.pipe(
map(mailboxes => mailboxes.folders.find(it => it.path === parameters.get('mailbox')!)!),
),
),
);
}

View File

@@ -0,0 +1,45 @@
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
<ion-menu-button menu="mailboxes"></ion-menu-button>
</ion-buttons>
<ion-title>Mail</ion-title>
</ion-toolbar>
</ion-header>
<ion-content parallax>
<ion-split-pane contentId="mailbox-content">
<ion-menu contentId="mailbox-content" menuId="mailboxes">
@if (mailStorage.mailboxes | async; as mailboxes) {
<ion-list>
@for (folder of mailboxes.folders; track folder) {
<ion-item
[routerLink]="['/mail', folder.path]"
[class.active]="folder.path === (mailbox | async)?.path"
>
@if (folder.specialUse) {
<ion-icon
slot="start"
[fill]="folder.path === (mailbox | async)?.path"
[name]="mailIcons[folder.specialUse]"
></ion-icon>
<ion-label>{{ 'mail.mailboxes.' + folder.specialUse | translate | titlecase }}</ion-label>
} @else {
<ion-icon
slot="start"
[fill]="folder.path === (mailbox | async)?.path"
name="folder"
></ion-icon>
<ion-label>{{ folder.name }}</ion-label>
}
</ion-item>
}
</ion-list>
}
</ion-menu>
<ion-router-outlet id="mailbox-content"></ion-router-outlet>
</ion-split-pane>
</ion-content>

View File

@@ -0,0 +1,26 @@
ion-list {
margin: var(--spacing-md);
border-radius: var(--border-radius-default);
}
ion-split-pane {
--border: none;
}
ion-menu,
ion-menu::part(container),
ion-menu::part(backdrop) {
background: none;
}
ion-menu:not(.menu-pane-visible) {
&::part(container) {
box-shadow: none;
}
> ion-list {
height: 100%;
margin-inline-end: var(--spacing-xl);
box-shadow: rgba(0 0 0 / 18%) 4px 0 16px;
}
}

View File

@@ -0,0 +1,309 @@
/* eslint-disable unicorn/no-useless-undefined */
import {Injectable, inject} from '@angular/core';
import {Capacitor} from '@capacitor/core';
import {SecureStoragePlugin} from 'capacitor-secure-storage-plugin';
import {
BehaviorSubject,
Observable,
catchError,
defer,
distinctUntilChanged,
filter,
from,
fromEvent,
map,
merge,
mergeMap,
of,
shareReplay,
startWith,
take,
firstValueFrom,
Subject,
} from 'rxjs';
import {Email, EmailMeta, EmailWithoutBody, MailboxTreeRoot} from './schema';
import equal from 'fast-deep-equal';
import {MailAdapterService} from './mail-adapter.service';
import {StorageProvider} from '../storage/storage.provider';
@Injectable({providedIn: 'root'})
export class MailStorageProvider {
static readonly DB_NAME = 'mail';
static readonly MAILBOX_STORE_NAME = 'mailboxes';
static readonly EMAIL_STORE_NAME = 'emails';
static readonly CREDENTIALS_KEY = 'email-credentials';
static readonly EMAIL_MAILBOX_INDEX = 'email';
static readonly EMAIL_FLAGS_INDEX = 'flags';
static readonly EMAIL_DATE_INDEX = 'date';
storageProvider = inject(StorageProvider);
mailAdapter = inject(MailAdapterService);
database = defer(() => {
const request = indexedDB.open(MailStorageProvider.DB_NAME, 1);
return merge(
fromEvent(request, 'upgradeneeded').pipe(
map(event => {
const database = (event.target as IDBOpenDBRequest).result;
const mailStore = database.createObjectStore(MailStorageProvider.EMAIL_STORE_NAME, {
keyPath: ['id', 'mailbox'],
});
mailStore.createIndex(MailStorageProvider.EMAIL_MAILBOX_INDEX, 'mailbox', {unique: false});
mailStore.createIndex(MailStorageProvider.EMAIL_FLAGS_INDEX, 'flags', {
unique: false,
multiEntry: true,
});
mailStore.createIndex(MailStorageProvider.EMAIL_DATE_INDEX, 'date', {unique: false});
return database;
}),
),
fromEvent(request, 'success').pipe(
take(1),
map(event => (event.target as IDBOpenDBRequest).result),
),
fromEvent(request, 'error').pipe(
take(1),
map(event => {
throw (event.target as IDBOpenDBRequest).error;
}),
),
fromEvent(request, 'blocked').pipe(
take(1),
map(() => {
throw new Error('Database blocked');
}),
),
);
}).pipe(shareReplay(1));
private mailboxesChanged = new BehaviorSubject<void>(undefined);
mailboxes: Observable<MailboxTreeRoot> = this.mailboxesChanged.pipe(
mergeMap(() =>
this.storageProvider
.get<MailboxTreeRoot>(MailStorageProvider.MAILBOX_STORE_NAME)
.catch(() => undefined!),
),
filter(it => it !== undefined),
distinctUntilChanged((a, b) => equal(a, b)),
shareReplay(1),
);
async setMailboxes(root: MailboxTreeRoot | undefined): Promise<void> {
await this.storageProvider.put(MailStorageProvider.MAILBOX_STORE_NAME, root);
this.mailboxesChanged.next();
}
private credentialsChanged = new BehaviorSubject<void>(undefined);
credentials: Observable<string | undefined> = this.credentialsChanged.pipe(
mergeMap(() => {
return Capacitor.isNativePlatform()
? from(SecureStoragePlugin.get({key: MailStorageProvider.CREDENTIALS_KEY})).pipe(
map(({value}) => value),
catchError(() => of(undefined)),
)
: of(localStorage.getItem(MailStorageProvider.CREDENTIALS_KEY) ?? undefined);
}),
);
async setCredentials(credentials: string | undefined): Promise<void> {
if (Capacitor.isNativePlatform()) {
await (credentials === undefined
? SecureStoragePlugin.remove({key: MailStorageProvider.CREDENTIALS_KEY})
: SecureStoragePlugin.set({key: MailStorageProvider.CREDENTIALS_KEY, value: credentials}));
} else {
if (credentials === undefined) {
localStorage.removeItem(MailStorageProvider.CREDENTIALS_KEY);
} else {
localStorage.setItem(MailStorageProvider.CREDENTIALS_KEY, credentials);
}
}
this.credentialsChanged.next();
}
private emailChanged = new Subject<Set<string>>();
private mailboxContentChanged = new Subject<Set<string>>();
getEmails(mailbox: string): Observable<EmailMeta[]> {
return this.mailboxContentChanged.pipe(
filter(it => it.has(mailbox)),
startWith(undefined),
mergeMap(() => this.database),
mergeMap(database => {
return defer(() => {
const transaction = database.transaction([MailStorageProvider.EMAIL_STORE_NAME], 'readonly');
const store = transaction.objectStore(MailStorageProvider.EMAIL_STORE_NAME);
const index = store.index(MailStorageProvider.EMAIL_MAILBOX_INDEX);
const request = index.getAll(IDBKeyRange.only(mailbox));
return merge(
fromEvent(request, 'success').pipe(
map(() => request.result as Array<EmailMeta | EmailWithoutBody | Email>),
),
fromEvent(request, 'error').pipe(
map(event => {
throw (event.target as IDBRequest).error;
}),
),
).pipe(take(1));
});
}),
map<Array<Email | EmailWithoutBody | EmailMeta>, EmailMeta[]>(emails =>
emails
.map(email => ({id: email.id, mailbox: email.mailbox, incomplete: true}) satisfies EmailMeta)
.sort((a, b) => Number(b.id) - Number(a.id)),
),
shareReplay(1),
);
}
getEmail(mailbox: string, id: string): Observable<Email>;
getEmail(mailbox: string, id: string, partial: false): Observable<Email>;
getEmail(mailbox: string, id: string, partial: boolean): Observable<Email | EmailWithoutBody>;
getEmail(mailbox: string, id: string, partial = false): Observable<Email | EmailWithoutBody> {
return this.emailChanged.pipe(
filter(it => it.has(JSON.stringify([id, mailbox]))),
startWith(undefined),
mergeMap(() => this.database),
mergeMap(database => {
return defer(() => {
const transaction = database.transaction([MailStorageProvider.EMAIL_STORE_NAME], 'readonly');
const store = transaction.objectStore(MailStorageProvider.EMAIL_STORE_NAME);
const request = store.get([id, mailbox]);
return merge(
fromEvent(request, 'success').pipe(map(() => request.result as EmailMeta | Email)),
fromEvent(request, 'error').pipe(
map(event => {
throw (event.target as IDBRequest).error;
}),
),
).pipe(take(1));
});
}),
mergeMap(email =>
'incomplete' in email || (!partial && 'partial' in email)
? this.credentials.pipe(
filter(it => it !== undefined),
take(1),
mergeMap(credentials =>
this.mailAdapter.getEmail(credentials!, mailbox, id, partial).pipe(
mergeMap(async email => {
await this.setEmail(email, true);
return email;
}),
),
),
)
: of(email),
),
shareReplay(1),
);
}
async setEmail(
email: Email | EmailMeta | EmailWithoutBody | Array<Email | EmailMeta | EmailWithoutBody>,
quiet = false,
): Promise<void> {
const database = await firstValueFrom(this.database);
const transaction = database.transaction([MailStorageProvider.EMAIL_STORE_NAME], 'readwrite');
const store = transaction.objectStore(MailStorageProvider.EMAIL_STORE_NAME);
const mailboxesAffected = new Set<string>();
const emailsAffected = new Set<string>();
for (const it of Array.isArray(email) ? email : [email]) {
mailboxesAffected.add(it.mailbox);
emailsAffected.add(JSON.stringify([it.id, it.mailbox]));
store.put(it);
}
await firstValueFrom(
merge(
fromEvent(transaction, 'complete').pipe(
map(() => {
if (!quiet) {
this.emailChanged.next(emailsAffected);
}
}),
),
fromEvent(transaction, 'error').pipe(
map(event => {
throw (event.target as IDBRequest).error;
}),
),
),
);
}
async addFlags(email: Email | EmailWithoutBody, flags: string[]): Promise<boolean> {
let hasChanged = false;
for (const flag of flags) {
if (!email.flags.has(flag)) {
hasChanged = true;
email.flags.add(flag);
}
}
if (hasChanged) {
const credentials = await firstValueFrom(this.credentials);
await this.setEmail(email);
return firstValueFrom(this.mailAdapter.addFlags(credentials!, email.mailbox, email.id, flags));
} else {
return false;
}
}
async removeFlags(email: Email | EmailWithoutBody, flags: string[]): Promise<boolean> {
let hasChanged = false;
for (const flag of flags) {
if (email.flags.has(flag)) {
hasChanged = true;
email.flags.delete(flag);
}
}
if (hasChanged) {
const credentials = await firstValueFrom(this.credentials);
await this.setEmail(email);
return firstValueFrom(this.mailAdapter.removeFlags(credentials!, email.mailbox, email.id, flags));
} else {
return false;
}
}
async deleteEmail(email: EmailMeta | Email | EmailWithoutBody): Promise<boolean> {
const credentials = await firstValueFrom(this.credentials);
const result = await firstValueFrom(this.mailAdapter.deleteEmail(credentials!, email.mailbox, email.id));
const database = await firstValueFrom(this.database);
const transaction = database.transaction([MailStorageProvider.EMAIL_STORE_NAME], 'readwrite');
const store = transaction.objectStore(MailStorageProvider.EMAIL_STORE_NAME);
store.delete([email.id, email.mailbox]);
return firstValueFrom(
merge(
fromEvent(transaction, 'complete').pipe(
map(() => {
this.mailboxContentChanged.next(new Set([email.mailbox]));
return result;
}),
),
fromEvent(transaction, 'error').pipe(
map(event => {
throw (event.target as IDBRequest).error;
}),
),
),
);
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (C) 2024 StApps
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Router, RouterModule} from '@angular/router';
import {NgModule, inject} from '@angular/core';
import {MailService} from './mail.service';
import {map, take} from 'rxjs';
/**
*
*/
function mailLoginGuard() {
const router = inject(Router);
return inject(MailService).isLoggedIn.pipe(
map(isLoggedIn => (isLoggedIn ? true : router.createUrlTree(['/mail-login']))),
take(1),
);
}
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'mail-login',
data: {redirectTo: ['/mail']},
loadComponent: () => import('./mail-login.component').then(m => m.MailLoginComponent),
},
{
path: 'mail',
loadComponent: () => import('./mail-page.component').then(m => m.MailPageComponent),
canActivate: [mailLoginGuard],
canActivateChild: [mailLoginGuard],
children: [
{
path: '',
redirectTo: 'INBOX',
pathMatch: 'full',
},
{
path: ':mailbox',
loadComponent: () => import('./mailbox-page.component').then(m => m.MailboxPageComponent),
},
{
path: ':mailbox/:id',
loadComponent: () => import('./mail-detail.component').then(m => m.MailDetailComponent),
},
],
},
]),
],
})
export class MailModule {}

View File

@@ -0,0 +1,30 @@
import {Pipe, PipeTransform, inject} from '@angular/core';
import {Observable} from 'rxjs';
import {MailStorageProvider} from './mail-storage.provider';
import {Email, EmailWithoutBody} from './schema';
@Pipe({
name: 'mail',
pure: true,
standalone: true,
})
export class MailPipe implements PipeTransform {
mailStorage = inject(MailStorageProvider);
transform(value: {mailbox: string; id: string}): Observable<Email> {
return this.mailStorage.getEmail(value.mailbox, value.id, false);
}
}
@Pipe({
name: 'partialMail',
pure: true,
standalone: true,
})
export class PartialMailPipe implements PipeTransform {
mailStorage = inject(MailStorageProvider);
transform(value: {mailbox: string; id: string}): Observable<EmailWithoutBody | Email> {
return this.mailStorage.getEmail(value.mailbox, value.id, true);
}
}

View File

@@ -0,0 +1,98 @@
import {Injectable} from '@angular/core';
import {
Observable,
map,
mergeMap,
filter,
from,
combineLatest,
tap,
of,
catchError,
BehaviorSubject,
take,
} from 'rxjs';
import {MailStorageProvider} from './mail-storage.provider';
import {MailAdapterService} from './mail-adapter.service';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {EmailMeta} from './schema';
@Injectable({providedIn: 'root'})
export class MailService {
isLoggedIn = this.mailStorage.credentials.pipe(map(it => it !== undefined));
manualSync = new BehaviorSubject<void>(undefined);
constructor(
private mailStorage: MailStorageProvider,
private mailAdapter: MailAdapterService,
) {
this.mailStorage.credentials
.pipe(
takeUntilDestroyed(),
mergeMap(credentials => this.manualSync.pipe(map(() => credentials))),
mergeMap(credentials => {
return credentials === undefined
? of()
: this.mailAdapter
.listMailboxes(credentials)
.pipe(mergeMap(mailboxes => this.mailStorage.setMailboxes(mailboxes)));
}),
)
.subscribe(() => {});
combineLatest([
this.mailStorage.credentials.pipe(filter(it => it !== undefined)),
this.mailStorage.mailboxes,
])
.pipe(
takeUntilDestroyed(),
mergeMap(([credentials, mailboxes]) =>
from(mailboxes.folders).pipe(
mergeMap(async mailbox => {
return this.mailAdapter.countEmails(credentials!, mailbox.path).pipe(
map<number, EmailMeta[]>(count =>
Array.from(
{length: count},
(_, i) =>
({id: (i + 1).toString(), mailbox: mailbox.path, incomplete: true}) satisfies EmailMeta,
),
),
tap(emails => console.log(emails)),
catchError(error => {
console.error(error);
return of();
}),
);
}),
mergeMap(emails => emails),
),
),
mergeMap(emails => this.mailStorage.setEmail(emails)),
)
.subscribe(() => {});
}
login(username: string, password: string): Observable<boolean> {
const credentials = btoa(`${username}:${password}`);
return this.mailAdapter.checkCredentials(credentials).pipe(
tap(success => {
if (success) {
this.mailStorage.setCredentials(credentials);
}
}),
);
}
logout() {
this.mailStorage.setCredentials(undefined);
this.mailStorage.setMailboxes(undefined);
}
downloadAttachment(mailbox: string, id: string, part: string): Observable<ArrayBuffer> {
return this.mailStorage.credentials.pipe(
filter(it => it !== undefined),
take(1),
mergeMap(credentials => this.mailAdapter.getRawPart(credentials!, mailbox, id, part)),
);
}
}

View File

@@ -0,0 +1,54 @@
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
import {ActivatedRoute, RouterModule} from '@angular/router';
import {MailService} from './mail.service';
import {MailStorageProvider} from './mail-storage.provider';
import {mergeMap, map, filter} from 'rxjs';
import {IonicModule} from '@ionic/angular';
import {IonIconModule} from 'src/app/util/ion-icon/ion-icon.module';
import {TranslateModule} from '@ngx-translate/core';
import {AsyncPipe, TitleCasePipe} from '@angular/common';
import {LazyComponent} from 'src/app/util/lazy.component';
import {PartialMailPipe} from './mail.pipe';
import {FormatPurePipeModule, IsTodayPipeModule} from 'ngx-date-fns';
import {LazyLoadPipe} from 'src/app/util/lazy-load.pipe';
@Component({
selector: 'stapps-mailbox-page',
templateUrl: 'mailbox-page.html',
styleUrl: 'mailbox-page.scss',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
IonicModule,
IonIconModule,
TranslateModule,
AsyncPipe,
LazyComponent,
PartialMailPipe,
IsTodayPipeModule,
FormatPurePipeModule,
RouterModule,
LazyLoadPipe,
TitleCasePipe,
],
})
export class MailboxPageComponent {
readonly activatedRoute = inject(ActivatedRoute);
readonly mailService = inject(MailService);
readonly mailStorage = inject(MailStorageProvider);
mailbox = this.activatedRoute.paramMap.pipe(
mergeMap(parameters =>
this.mailStorage.mailboxes.pipe(
map(mailboxes => mailboxes.folders.find(it => it.path === parameters.get('mailbox')!)!),
),
),
);
mails = this.mailbox.pipe(
filter(mailbox => mailbox !== undefined),
mergeMap(mailbox => this.mailStorage.getEmails(mailbox.path)),
);
}

View File

@@ -0,0 +1,54 @@
<ion-content>
<h1>
@if (mailbox | async; as mailbox) {
@if (mailbox.specialUse) {
{{ 'mail.mailboxes.' + mailbox.specialUse | translate | titlecase }}
} @else {
{{ mailbox.name }}
}
} @else {
<ion-skeleton-text animated style="width: 100px; height: 20px"></ion-skeleton-text>
}
</h1>
@if (mails | async; as mails) {
<ion-list>
@for (mail of mails; track mail.id) {
<ion-item #item [routerLink]="['/mail', mail.mailbox, mail.id]">
@if (mail | partialMail | lazyLoad: item | async; as mail) {
<div slot="start" class="avatar">
@if (mail.from; as from) {
<div>
{{ (from.value.name || from.value.address)?.charAt(0)?.toUpperCase() }}
</div>
}
</div>
<ion-label>
<h2 [class.unread]="!mail.flags.has('\\Seen')">
{{ mail.from.value.name || mail.from.value.address }}
</h2>
@if (mail.subject) {
<p>{{ mail.subject.value }}</p>
}
</ion-label>
<ion-note slot="end">
@if (mail.date.value | dfnsIsToday) {
{{ mail.date.value | dfnsFormatPure: 'p' }}
} @else {
{{ mail.date.value | dfnsFormatPure: 'P' }}
}
</ion-note>
} @else {
<div slot="start" class="avatar">
<ion-skeleton-text animated></ion-skeleton-text>
</div>
<ion-label>
<h2><ion-skeleton-text animated></ion-skeleton-text></h2>
<p><ion-skeleton-text animated></ion-skeleton-text></p>
</ion-label>
}
</ion-item>
}
</ion-list>
}
</ion-content>

View File

@@ -0,0 +1,44 @@
.avatar {
display: flex;
align-items: center;
justify-content: center;
width: 2em;
height: 2em;
color: var(--ion-color-light-contrast);
background: var(--ion-color-light);
border-radius: 50%;
}
h1 {
margin-inline: var(--spacing-md);
color: var(--ion-color-primary-contrast);
}
h2 > ion-skeleton-text {
width: min(60%, 20em);
}
p > ion-skeleton-text {
width: min(80%, 20em);
}
.avatar > ion-skeleton-text {
border-radius: 50%;
}
h2.unread {
font-weight: bold;
}
ion-item p {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
ion-content::part(background) {
background: none;
}

View File

@@ -0,0 +1,130 @@
import {z} from 'zod';
export const RawEmailAddress = z.object({
name: z.optional(z.string()),
address: z.optional(z.string()),
});
export type RawEmailAddress = z.infer<typeof RawEmailAddress>;
export const RawEmailEnvelope = z.object({
date: z.coerce.date(),
subject: z.string(),
messageId: z.string(),
inReplyTo: z.optional(z.string()),
from: z.array(RawEmailAddress),
sender: z.array(RawEmailAddress),
replyTo: z.array(RawEmailAddress),
to: z.array(RawEmailAddress),
cc: z.optional(z.array(RawEmailAddress)),
bcc: z.optional(z.array(RawEmailAddress)),
});
export type RawEmailEnvelope = z.infer<typeof RawEmailEnvelope>;
const RawEmailBodyStructureBase = z.object({
part: z.optional(z.string()),
type: z.string(),
parameters: z.optional(z.record(z.string(), z.string())),
encoding: z.optional(z.enum(['7bit', '8bit', 'binary', 'base64', 'quoted-printable'])),
size: z.optional(z.number()),
envelope: z.optional(RawEmailEnvelope),
disposition: z.optional(z.string()),
dispositionParameters: z.optional(z.record(z.string(), z.string())),
});
export type RawEmailBodyStructure = z.infer<typeof RawEmailBodyStructureBase> & {
childNodes?: RawEmailBodyStructure[];
};
export const RawEmailBodyStructure: z.ZodType<RawEmailBodyStructure> = RawEmailBodyStructureBase.extend({
childNodes: z.optional(z.lazy(() => z.array(RawEmailBodyStructure))),
});
export const RawEmail = z.object({
bodyStructure: z.optional(RawEmailBodyStructure),
labels: z.array(z.string()).transform(it => new Set(it)),
flags: z.array(z.string()).transform(it => new Set(it)),
envelope: RawEmailEnvelope,
seq: z.coerce.string(),
});
export type RawEmail = z.infer<typeof RawEmail>;
const MailboxTreeItemBase = z.object({
path: z.string(),
name: z.string(),
delimiter: z.string(),
flags: z.array(z.string()).or(z.object({})),
specialUse: z.optional(
z.enum(['\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash', '\\Inbox']),
),
listed: z.boolean(),
subscribed: z.boolean(),
disabled: z.boolean().optional(),
});
export type MailboxTreeItem = z.infer<typeof MailboxTreeItemBase> & {
folders?: MailboxTreeItem[];
};
export const MailboxTreeItem: z.ZodType<MailboxTreeItem> = MailboxTreeItemBase.extend({
folders: z.optional(z.lazy(() => z.array(MailboxTreeItem))),
});
export const MailboxTreeRoot = z.object({
path: z.literal('').default(''),
root: z.literal(true),
folders: z.array(MailboxTreeItem),
});
export type MailboxTreeRoot = z.infer<typeof MailboxTreeRoot>;
export interface Signature {
type: 'pkcs7';
valid: boolean;
}
export interface SignedValue<T> {
value: T;
signature?: Signature;
}
export interface EmailAddress {
name?: string;
address?: string;
}
export interface EmailAttachmentBase {
filename: string;
size: number;
}
export interface EmailAttachmentRemote extends EmailAttachmentBase {
part: string;
}
export interface EmailAttachmentLocal extends EmailAttachmentBase {
content: ArrayBuffer;
}
export type EmailAttachment = EmailAttachmentRemote | EmailAttachmentLocal;
export interface Email {
id: string;
mailbox: string;
flags: Set<string>;
subject?: SignedValue<string>;
date: SignedValue<Date>;
from: SignedValue<EmailAddress>;
to?: SignedValue<EmailAddress>[];
cc?: SignedValue<EmailAddress>[];
bcc?: SignedValue<EmailAddress>[];
html?: SignedValue<string>;
text?: SignedValue<string>;
attachments: SignedValue<EmailAttachment>[];
}
export type EmailWithoutBody = Omit<Email, 'html' | 'text' | 'attachments'> & {partial: true};
export type EmailMeta = Pick<Email, 'id' | 'mailbox'> & {incomplete: true};

View File

@@ -39,6 +39,11 @@
}
<ion-label>{{ 'name' | translateSimple: link }}</ion-label>
</div>
@if (link.beta) {
<ion-note>
<ion-badge color="warning">{{ 'beta' | translate }}</ion-badge>
</ion-note>
}
</ion-item>
}
</simple-swiper>

View File

@@ -50,6 +50,13 @@ ion-item {
}
}
ion-note {
position: absolute;
top: 0;
right: 0;
padding: var(--spacing-xs);
}
simple-swiper {
--swiper-slide-width: #{$width};

View File

@@ -19,6 +19,7 @@ import german from '../../assets/i18n/de.json';
const exceptions = new Set(
[
'ID',
'login',
'ok',
'protein',

View File

@@ -0,0 +1,25 @@
import {Pipe, PipeTransform} from '@angular/core';
/**
* Format a data size in bytes to a human readable string
*/
export function formatDataSize(value: number, precision = 2): string {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${value.toFixed(precision)} ${units[unit]}`;
}
@Pipe({
name: 'dataSize',
pure: true,
standalone: true,
})
export class DataSizePipe implements PipeTransform {
transform(value: number, precision = 2): string {
return formatDataSize(value, precision);
}
}

View File

@@ -0,0 +1,36 @@
import {OnDestroy, Pipe, PipeTransform} from '@angular/core';
import {Observable, Subject, mergeMap} from 'rxjs';
@Pipe({
name: 'lazyLoad',
pure: true,
standalone: true,
})
export class LazyLoadPipe implements PipeTransform, OnDestroy {
intersectionObserver?: IntersectionObserver;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
transform<T>(value: Observable<T>, element: any): Observable<T> {
if (element.el instanceof Element) {
const isInView = new Subject<void>();
this.intersectionObserver?.disconnect();
this.intersectionObserver = new IntersectionObserver(entries => {
if (entries.some(it => it.isIntersecting)) {
this.intersectionObserver?.disconnect();
delete this.intersectionObserver;
isInView.next();
isInView.complete();
}
});
this.intersectionObserver.observe(element.el);
return isInView.pipe(mergeMap(() => value));
} else {
console.error('LazyLoadPipe: not an element', element);
return value;
}
}
ngOnDestroy() {
this.intersectionObserver?.disconnect();
}
}

View File

@@ -0,0 +1,46 @@
import {NgTemplateOutlet} from '@angular/common';
import {
ChangeDetectionStrategy,
Component,
ContentChild,
ElementRef,
OnDestroy,
OnInit,
Renderer2,
TemplateRef,
signal,
} from '@angular/core';
@Component({
selector: 'stapps-lazy',
templateUrl: 'lazy.html',
styleUrl: 'lazy.scss',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgTemplateOutlet],
})
export class LazyComponent implements OnInit, OnDestroy {
@ContentChild(TemplateRef) template!: TemplateRef<void>;
isIntersecting = signal(false);
intersectionObserver = new IntersectionObserver(entries => {
this.isIntersecting.set(this.isIntersecting() || entries.some(entry => entry.isIntersecting));
if (this.isIntersecting()) {
this.intersectionObserver.disconnect();
}
});
constructor(
readonly element: ElementRef,
readonly renderer: Renderer2,
) {}
ngOnInit() {
this.intersectionObserver.observe(this.element.nativeElement);
}
ngOnDestroy() {
this.intersectionObserver.disconnect();
}
}

View File

@@ -0,0 +1,3 @@
@if (isIntersecting()) {
<ng-container *ngTemplateOutlet="template"></ng-container>
}

View File

View File

@@ -0,0 +1,22 @@
import {EMPTY, Observable, concat, defer, of} from 'rxjs';
/**
* Turns an IDBCursorWithValue into an Observable of values.
*
* Values are emitted lazily, i.e. the next value is only emitted when the
* previous one has been consumed.
* @example fromCursor(cursor).pipe(take(10)).subscribe(console.log);
*/
export function fromCursor<T>(cursor: IDBCursorWithValue): Observable<T> {
if (cursor.key === null) {
return EMPTY;
}
const value = cursor.value as T;
cursor.continue();
return concat(
of(value),
defer(() => fromCursor<T>(cursor)),
);
}

View File

@@ -0,0 +1,18 @@
import {Directive, ElementRef, Host, Input} from '@angular/core';
import {sanitize} from 'dompurify';
@Directive({
selector: '[shadowHTML]',
standalone: true,
})
export class ShadowHtmlDirective {
@Input({required: true})
set shadowHTML(content: string) {
this.shadowRoot.innerHTML = '';
this.shadowRoot.append(sanitize(content, {RETURN_DOM_FRAGMENT: true, USE_PROFILES: {html: true}}));
}
shadowRoot = (this.elementRef.nativeElement as HTMLElement).attachShadow({mode: 'open'});
constructor(@Host() readonly elementRef: ElementRef) {}
}

View File

@@ -8,6 +8,7 @@
"export": "Exportieren",
"share": "Teilen",
"timeSuffix": "Uhr",
"beta": "Beta",
"ratings": {
"thank_you": "Vielen Dank für die Bewertung!"
},
@@ -389,6 +390,35 @@
}
}
},
"mail": {
"SIGNATURE_VALID": "Signatur gültig",
"SIGNATURE_INVALID": "Signatur ungültig",
"SIGNATURE_UNSUPPORTED": "Signatur nicht unterstützt",
"ID": "ID",
"FROM": "von",
"SENDER": "Absender",
"TO": "an",
"DATE": "Datum",
"login": {
"TITLE": "E-Mail Login",
"LOGIN": "Login",
"PLACEHOLDER_USERNAME": "Nutzername",
"PLACEHOLDER_PASSWORD": "Passwort",
"error": {
"INVALID_CREDENTIALS": "ungültige Zugangsdaten"
}
},
"mailboxes": {
"\\Inbox": "Posteingang",
"\\All": "Alle",
"\\Archive": "Archiv",
"\\Drafts": "Entwürfe",
"\\Flagged": "Markiert",
"\\Junk": "Spam",
"\\Sent": "Gesendet",
"\\Trash": "Papierkorb"
}
},
"menu": {
"context": {
"title": "Kontext Menü",

View File

@@ -7,6 +7,7 @@
"back": "back",
"export": "Export",
"share": "Share",
"beta": "beta",
"timeSuffix": "",
"ratings": {
"thank_you": "Thank you for your feedback!"
@@ -389,6 +390,35 @@
}
}
},
"mail": {
"SIGNATURE_VALID": "signature valid",
"SIGNATURE_INVALID": "signature invalid",
"SIGNATURE_UNSUPPORTED": "signature unsupported",
"ID": "ID",
"FROM": "from",
"SENDER": "sender",
"TO": "to",
"DATE": "date",
"login": {
"TITLE": "email login",
"LOGIN": "login",
"PLACEHOLDER_USERNAME": "username",
"PLACEHOLDER_PASSWORD": "password",
"error": {
"INVALID_CREDENTIALS": "invalid credentials"
}
},
"mailboxes": {
"\\Inbox": "inbox",
"\\All": "all inboxes",
"\\Archive": "archive",
"\\Drafts": "drafts",
"\\Flagged": "flagged",
"\\Junk": "spam",
"\\Sent": "sent",
"\\Trash": "trash"
}
},
"menu": {
"context": {
"title": "context menu",

View File

@@ -49,6 +49,7 @@ export interface SCSectionLink extends SCThing {
link: string[];
needsAuth?: true;
icon?: string;
beta?: true;
}
export interface SCSection extends SCThing {
@@ -150,6 +151,18 @@ export const profilePageSections: SCSection[] = [
},
...SCSectionLinkConstantValues,
},
{
name: 'Mail',
icon: SCIcon.mail,
link: ['/mail'],
beta: true,
translations: {
de: {
name: 'Email',
},
},
...SCSectionLinkConstantValues,
},
],
translations: {
de: {

View File

@@ -18,7 +18,7 @@
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<link rel="icon" type="image/png" href="assets/icon/favicon.png" />
<link rel="icon" type="image/png" href="./assets/icon/favicon.png" />
<!-- add to homescreen for ios -->
<meta name="apple-mobile-web-app-capable" content="yes" />

View File

@@ -28,10 +28,10 @@
"test": "c8 mocha"
},
"dependencies": {
"@types/nodemailer": "6.4.7",
"@types/nodemailer": "6.4.15",
"chalk": "5.2.0",
"flatted": "3.2.7",
"nodemailer": "6.9.1"
"nodemailer": "6.9.14"
},
"devDependencies": {
"@openstapps/eslint-config": "workspace:*",

659
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff