Compare commits

..

6 Commits

Author SHA1 Message Date
holger krekel
677ba61b12 factor out imex tracking 2020-02-21 19:37:52 +01:00
holger krekel
932b8687de move towards pluggy 2020-02-21 18:59:17 +01:00
holger krekel
3da2e143b5 strike get_infostring 2020-02-21 18:12:46 +01:00
holger krekel
2f3b194288 move eventlogging to own module, start distinguishing ll events 2020-02-21 17:21:46 +01:00
holger krekel
ff4032dcf8 strike footer and refine index page 2020-02-21 16:55:47 +01:00
holger krekel
0f34bfa5a4 strike one Account parameter, always do eventlogging 2020-02-21 16:40:22 +01:00
49 changed files with 803 additions and 2811 deletions

View File

@@ -1,33 +1,5 @@
# Changelog
## 1.28.0
- new flag DC_GCL_FOR_FORWARDING for dc_get_chatlist()
that will sort the "saved messages" chat to the top of the chatlist #1336
- mark mails as being deleted from server in dc_empty_server() #1333
- fix interaction with servers that do not allow folder creation on root-level;
use path separator as defined by the email server #1359
- fix group creation if group was created by non-delta clients #1357
- fix showing replies from non-delta clients #1353
- fix member list on rejoining left groups #1343
- fix crash when using empty groups #1354
- fix potential crash on special names #1350
## 1.27.0
- handle keys reliably on armv7 #1327
## 1.26.0
- change generated key type back to RSA as shipped versions
have problems to encrypt to Ed25519 keys
- update rPGP to encrypt reliably to Ed25519 keys;
one of the next versions can finally use Ed25519 keys then
## 1.25.0
- save traffic by downloading only messages that are really displayed #1236

568
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package]
name = "deltachat"
version = "1.28.0"
version = "1.25.0"
authors = ["Delta Chat Developers (ML) <delta@codespeak.net>"]
edition = "2018"
license = "MPL-2.0"
@@ -12,7 +12,7 @@ lto = true
deltachat_derive = { path = "./deltachat_derive" }
libc = "0.2.51"
pgp = { version = "0.5.1", default-features = false }
pgp = { version = "0.4.0", default-features = false }
hex = "0.4.0"
sha2 = "0.8.0"
rand = "0.7.0"
@@ -53,12 +53,11 @@ bitflags = "1.1.0"
debug_stub_derive = "0.3.0"
sanitize-filename = "0.2.1"
stop-token = { version = "0.1.1", features = ["unstable"] }
mailparse = "0.12.0"
mailparse = "0.10.2"
encoded-words = { git = "https://github.com/async-email/encoded-words", branch="master" }
native-tls = "0.2.3"
image = { version = "0.22.4", default-features=false, features = ["gif_codec", "jpeg", "ico", "png_codec", "pnm", "webp", "bmp"] }
pretty_env_logger = "0.3.1"
zip = "0.5"
rustyline = { version = "4.1.0", optional = true }
@@ -85,7 +84,7 @@ required-features = ["rustyline"]
[features]
default = ["nightly"]
default = ["nightly", "ringbuf"]
vendored = ["async-native-tls/vendored", "reqwest/native-tls-vendored", "async-smtp/native-tls-vendored"]
nightly = ["pgp/nightly"]
ringbuf = ["pgp/ringbuf"]

View File

@@ -108,6 +108,7 @@ $ cargo test -- --ignored
- `vendored`: When using Openssl for TLS, this bundles a vendored version.
- `nightly`: Enable nightly only performance and security related features.
- `ringbuf`: Enable the use of [`slice_deque`](https://github.com/gnzlbg/slice_deque) in pgp.
[circle-shield]: https://img.shields.io/circleci/project/github/deltachat/deltachat-core-rust/master.svg?style=flat-square
[circle]: https://circleci.com/gh/deltachat/deltachat-core-rust/

View File

@@ -1,788 +0,0 @@
/* TODO inlcude the referenced svgs as base64 data uris */
.header {
background-color: #415e6b;
color: #fff;
position: absolute;
height: 52px;
width: 100%;
z-index: 5;
display:flex;
}
.header .avatar {
height: 36px;
width: 36px;
border-radius: 100%;
user-select: none;
margin: 8px;
}
.header .avatar.text-avatar {
background-color: #505050;
color: white;
font-size: 26px;
line-height: 36px;
text-align: center;
}
.header .name {
height: 52px;
line-height: 52px;
margin-left: 3px;
font-size: 20px;
}
.message.outgoing .author-avatar, .message.outgoing .author {
display: none!important;
}
:root {--colorPrimary: #42A5F5;--colorDanger: #f96856;--colorNone: #a0a0a0;--ovalButtonBg: #415e6b;--ovalButtonBgHover: rgb(120, 156, 173);--ovalButtonText: #fff;--ovalButtonTextHover: rgb(0, 0, 0);--navBarBackground: #415e6b;--navBarText: #fff;--navBarSearchPlaceholder: rgb(186, 186, 186);--navBarGroupSubtitle: rgb(186, 186, 186);--chatViewBg: #e6dcd4;--chatViewBgImgPath: url(../images/background_light.svg);--composerBg: #fff;--composerText: #010101;--composerPlaceholderText: rgba(1, 1, 1, 0.5);--composerBtnColor: rgba(1, 1, 1, 0.9);--composerSendButton: #415e6b;--emojiSelectorSelectionColor: #2090ea;--chatListItemSelectedBg: #4c6e7d;--chatListItemSelectedBgHover: #5E889B;--chatListItemSelectedText: #fff;--chatListItemBgHover: rgb(228, 228, 228);--chatListBorderColor: #b9b9b9;--chatListBorder: 1px solid undefined;--messageText: #010101;--messageTextLink: #010101;--setupMessageText: #ed824e;--infoMessageBubbleBg: #0000008c;--infoMessageBubbleText: white;--messageIncommingBg: #fff;--messageIncommingDate: #010101;--messageOutgoingBg: #efffde;--messageOutgoingStatusColor: #4caf50;--messageButtons: #8b8e91;--messageButtonsHover: #070c14;--messageStatusIcon: #4caf50;--messageStatusIconSending: #62656a;--messagePadlockOutgoing: #4caf50;--messagePadlockIncomming: #a4a6a9;--messageMetadataDate: #62656a;--messageMetadataIncomming: rgba(#ffffff, 0.7);--messageAuthor: #ffffff;--messageAttachmentIconExtentionColor: #070c14;--messageAttachmentIconBg: transparent;--messageAttachmentFileInfo: #010101;--loginInputFocusColor: #42A5F5;--loginButtonText: #42A5F5;--deltaChatPrimaryFg: #010101;--deltaChatPrimaryFgLight: #62656a;--contextMenuBg: #fff;--contextMenuBorder: rgb(221, 221, 221);--contextMenuText: #62656a;--contextMenuSelected: #f5f5f5;--contextMenuSelectedBg: #a4a6a9;--bp3DialogHeaderBg: #fff;--bp3DialogHeaderIcon: #666666;--bp3DialogBgSecondary: #ececec;--bp3DialogBgPrimary: #fff;--bp3Heading: #010101;--bp3ButtonText: #010101;--bp3ButtonBg: #fff;--bp3ButtonGradientTop: rgba(255,255,255,0.8);--bp3ButtonGradientBottom: rgba(255,255,255,0);--bp3ButtonHoverBg: #ebf1f5;--bp3InputText: #010101;--bp3InputBg: #fff;--bp3InputPlaceholder: lightgray;--bp3MenuText: #010101;--bp3MenuBg: #fff;--bp3Switch: #7a8084;--bp3SwitchShadow: unset;--bp3SwitchChecked: #acd4e8;--bp3SwitchShadowChecked: unset;--bp3SwitchKnob: #f5f5f5;--bp3SwitchKnobShadow: 0px 2px 0 0px #d2cfcfad;--bp3SwitchKnobChecked: #42A5F5;--bp3SwitchKnobShadowChecked: 0px 1px 0 0px #c9d4d2d1;--bp3SpinnerTrack: #acd4e8;--bp3SpinnerHead: #42a5f5;--bp3SelectorTop: rgba(255, 255, 255, 0.8);--bp3SelectorBottom: rgba(255, 255, 255, 0.0);--outlineProperties: 1px solid transparent;--outlineColor: b9b9b9;--emojiMartText: #010101;--emojiMartSearchBorder: lightgrey;--emojiMartBg: #fff;--emojiMartOutsideRadius: 5px;--emojiMartCategoryIcons: rgb(99, 99, 99);--emojiMartInputBg: #f5f5f5;--emojiMartInputText: #010101;--emojiMartInputPlaceholder: rgb(74, 74, 74);--emojiMartSelect: rgb(198, 198, 198);--galleryBg: #fff;--avatarLabelColor: #ffffff;--brokenMediaText: #070c14;--brokenMediaBg: #ffffff;--unreadCountBg: #2090ea;--unreadCountLabel: #ffffff;--contactListItemBg: #62656a;--contactListInitalColor: #62656a;--contactEmailColor: #62656a;--errorColor: #f44336;--globalLinkColor: #2090ea;--globalBackground: #fff;--globalText: #010101;--mapOverlayBg: #fff;--videoPlayBtnIcon: #2090ea;--videoPlayBtnBg: #ffffff;--scrollbarThumb: #666666;--scrollbarThumbHover: #606060;}
* {
box-sizing: border-box;
}
html {
height: 100%;
--messageIncommingBg: rgb(232, 232, 232);
}
body {
position: relative;
height: 100%;
width: 100%;
margin: 0;
font-family: Roboto, "Apple Color Emoji", NotoEmoji, "Helvetica Neue", Arial,
Helvetica, NotoMono, sans-serif !important;
font-size: 14px;
color: black;
background-color: white;
}
ul {
list-style: none;
padding-left: 0;
}
input:focus {
outline: 0 !important;
}
button:focus {
outline: none;
}
button:focus {
outline: none;
}
::-webkit-scrollbar {
width: 6px;
height: 0;
}
::-webkit-scrollbar-track {
background: white;
}
::-webkit-scrollbar-thumb {
background: var(--scrollbarThumb);
}
::-webkit-scrollbar-thumb:hover {
background: var(--scrollbarThumbHover);
}
::-webkit-scrollbar-corner {
background: transparent;
}
span.module-contact-name {
font-weight: 200;
font-size: medium;
}
.module-contact-name__profile-name {
font-style: italic;
}
.AvatarBubble {
position: relative;
z-index: 2;
object-fit: cover;
height: 48px;
width: 48px;
margin-top: 8px;
margin-bottom: 8px;
border-radius: 100%;
background-color: #505050;
color: var(--avatarLabelColor);
font-size: 26px;
line-height: 48px;
text-align: center;
user-select: none;
}
.AvatarBubble.large {
height: 64px;
width: 64px;
line-height: 64px;
font-size: 39px;
}
.AvatarBubble--NoSearchResults {
transform: rotate(45deg);
line-height: 46px;
letter-spacing: 1px;
}
.AvatarBubble--NoSearchResults::after {
content: ":-(";
}
.AvatarImage {
position: relative;
z-index: 2;
object-fit: cover;
height: 48px;
width: 48px;
margin-top: 8px;
margin-bottom: 8px;
border-radius: 100%;
user-select: none;
}
.AvatarImage.large {
height: 64px;
width: 64px;
}
.attachment-overlay .attachment-view {
height: 100%;
padding: 0;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: #313131;
}
.attachment-overlay .attachment-view img,
.attachment-overlay .attachment-view video {
width: 100vw;
max-height: 100vh;
object-fit: contain;
}
.attachment-overlay .attachment-view video {
width: 95vw;
}
.attachment-overlay .render-media-wrapper {
width: 100vw;
height: 100vh;
}
.attachment-overlay .btn-wrapper {
float: right;
position: absolute;
z-index: 10;
cursor: pointer;
}
.attachment-overlay .download-btn {
height: 36px;
width: 36px;
display: inline-block;
-webkit-mask: url("../images/download.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageButtons);
}
.attachment-overlay .download-btn:hover {
background-color: var(--messageButtons);
}
.message-attachment-media {
text-align: center;
position: relative;
cursor: pointer;
margin-left: -12px;
margin-right: -12px;
margin-top: -10px;
margin-bottom: -10px;
border-radius: 16px;
overflow: hidden;
background-color: var(--messageAttachmentIconBg);
}
.message-attachment-media > .attachment-content {
object-fit: scale-down;
object-position: center;
min-height: 150px;
max-height: 300px;
max-width: 40vw;
margin-bottom: -4px;
cursor: pointer;
}
.message-attachment-media > .video-play-btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 48px;
height: 48px;
background-color: var(--videoPlayBtnBg);
border-radius: 24px;
}
.message-attachment-media > .video-play-btn > .video-play-btn-icon {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 36px;
width: 36px;
-webkit-mask: url("../images/play.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--videoPlayBtnIcon);
}
.message-attachment-media.content-below {
margin-bottom: 7px;
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
}
.message-attachment-media.content-above {
margin-top: 4px;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
}
.message-attachment-broken-media {
font-size: 11px;
line-height: 16px;
letter-spacing: 0.3px;
padding: 10px;
text-align: center;
text-transform: uppercase;
color: var(--brokenMediaBg);
}
.message-attachment-broken-media.incoming {
color: var(--brokenMediaText);
}
.message-attachment-audio {
margin-top: 2px;
display: block;
margin-right: 30px;
}
.message-attachment-audio.content-below {
margin-bottom: 5px;
}
.message-attachment-audio.content-above {
margin-top: 6px;
}
.message-attachment-generic {
display: flex;
flex-direction: row;
}
.message-attachment-generic.content-below {
padding-bottom: 6px;
}
.message-attachment-generic.content-above {
padding-top: 4px;
}
.message-attachment-generic > .file-icon {
background: url("../images/file-gradient.svg") no-repeat center;
height: 44px;
width: 56px;
margin-left: -13px;
margin-right: -14px;
margin-bottom: -4px;
display: flex;
flex-direction: row;
align-items: center;
}
.message-attachment-generic > .file-icon > .file-extension {
font-size: 10px;
line-height: 13px;
letter-spacing: 0.1px;
text-transform: uppercase;
text-align: center;
width: 25px;
margin-left: auto;
margin-right: auto;
overflow-x: hidden;
white-space: nowrap;
text-overflow: clip;
color: var(--messageAttachmentIconExtentionColor);
font-family: monospace;
}
.message-attachment-generic > .text-part {
flex-grow: 1;
margin-left: 8px;
max-width: calc(100% - 37px);
}
.message-attachment-generic > .text-part > .name {
color: var(--messageAttachmentFileInfo);
font-size: 14px;
line-height: 18px;
font-weight: 300;
margin-top: 2px;
overflow-x: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.message-attachment-generic > .text-part > .size {
color: var(--messageAttachmentFileInfo);
font-size: 11px;
line-height: 16px;
letter-spacing: 0.3px;
margin-top: 3px;
}
.module-message-detail {
margin-top: -20px;
}
.module-message-detail .bp3-callout {
max-height: 50vh;
overflow: auto;
}
.module-message-detail p {
white-space: pre-line;
user-select: text;
}
.module-message-detail__message-container {
padding-top: 20px;
padding-bottom: 20px;
}
.module-message-detail__message-container:after {
content: ".";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
.module-message-detail__label {
font-weight: 300;
padding-right: 5px;
}
.module-message-detail__unix-timestamp {
color: #eeefef;
}
.module-message-detail__delete-button-container {
text-align: center;
margin-top: 10px;
}
.module-message-detail__delete-button {
background: none;
color: inherit;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
background-color: #f44336;
color: #fff;
box-shadow: 0 0 10px -3px rgba(97, 97, 97, 0.7);
border-radius: 5px;
border: solid 1px #a4a6a9;
cursor: pointer;
margin: 1em auto;
padding: 1em;
}
.module-message-detail .message-content * {
background-color: lightgrey;
width: 100%;
resize: none;
padding: 1rem;
}
.message-list-and-composer {
width: 70%;
float: right;
display: grid;
grid-template-columns: auto;
height: calc(100vh - 50px);
margin-top: 50px;
background-image: var(--chatViewBgImgPath);
background-size: cover;
background-color: var(--chatViewBg);
}
.message-list-and-composer__message-list #message-list {
background: #dbdbdb;
position: absolute;
bottom: 0;
overflow: scroll;
max-height: 100%;
width: 100%;
padding: 0 0.5em;
top: 52px;
}
.message-list-and-composer__message-list
#message-list::-webkit-scrollbar-track {
background: transparent;
}
.message-list-and-composer__message-list ul {
list-style: none;
min-width: 200px;
}
.message-list-and-composer__message-list ul li {
margin-bottom: 10px;
min-width: 200px;
}
.message-list-and-composer__message-list ul li::after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.message-list-and-composer__message-list ul li .info-message {
max-width: 550px;
font-size: 1rem;
padding: 2rem;
font-style: normal;
white-space: pre-wrap;
text-align: left;
}
.message {
position: relative;
display: inline-flex;
flex-direction: row;
align-items: stretch;
}
.message:hover .message-buttons {
opacity: 1;
}
.message > .author-avatar {
align-self: flex-end;
bottom: 0px;
position: static;
margin-right: 8px;
user-select: none;
}
.message > .author-avatar img {
height: 36px;
width: 36px;
border-radius: 18px;
object-fit: cover;
}
.message > .author-avatar.default {
text-align: center;
}
.message > .author-avatar.default > .label {
user-select: none;
color: var(--avatarLabelColor);
top: -121px;
left: -10px;
border-radius: 50%;
width: 36px;
height: 36px;
font-size: 25px;
line-height: 36px;
}
.message .message-buttons {
position: absolute;
top: 5px;
right: -4px;
display: inline-flex;
flex-direction: row;
align-items: center;
opacity: 0;
z-index: 10;
user-select: text;
}
.message .message-buttons .msg-button {
height: 24px;
width: 24px;
display: inline-block;
cursor: pointer;
}
.message .message-buttons .msg-button:hover {
background-color: var(--messageButtons);
}
.message .message-buttons .msg-button.download {
-webkit-mask: url("../images/download.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageButtons);
}
.message .message-buttons .msg-button.reply {
display: none;
-webkit-mask: url("../images/reply.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageButtons);
user-select: none;
}
.message .message-buttons .msg-button.menu {
-webkit-mask: url("../images/ellipsis.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageButtons);
transform: rotate(90deg);
-webkit-mask-position-y: 4px;
user-select: none;
}
.message .msg-container {
position: relative;
display: inline-block;
border-radius: 16px;
padding-right: 12px;
padding-left: 12px;
padding-top: 10px;
padding-bottom: 10px;
}
.message .msg-container > .author {
display: inline-block;
max-width: 40vw;
font-size: 13px;
font-weight: 300;
line-height: 18px;
height: 18px;
overflow-x: hidden;
overflow-y: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.message .msg-container .msg-body.msg-body--clickable {
cursor: pointer;
}
.message .msg-container .msg-body > .text {
color: var(--messageText);
font-size: 14px;
line-height: 18px;
text-align: start;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
white-space: pre-wrap;
margin-right: 10px;
}
.message .msg-container .msg-body > .text a {
text-decoration: underline;
color: var(--messageTextLink);
}
.message .msg-container .msg-body > .text .double-line-break {
height: 28px;
}
.message .msg-container .msg-body > .text .line-break {
height: 14px;
}
.message .msg-container .msg-body > .text .line-break:last-child {
height: 0px;
}
.message .metadata {
margin-top: 10px;
margin-bottom: -7px;
float: right;
}
.message .module-message__img-attachment {
object-fit: cover;
width: auto;
max-width: 100%;
min-height: unset;
}
.message.incoming {
margin-left: 0;
margin-right: 32px;
}
.message.incoming .metadata:not(.with-image-no-caption) > .padlock-icon {
-webkit-mask: url("../images/padlock.svg") no-repeat center;
-webkit-mask-size: 125%;
background-color: var(--messagePadlockIncomming);
}
.message.incoming .metadata:not(.with-image-no-caption) > .location-icon {
-webkit-mask: url("../images/map-marker.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messagePadlockIncomming);
}
.message.incoming .metadata:not(.with-image-no-caption) > .date {
color: var(--messageMetadataIncomming);
}
.message.incoming .msg-container {
background-color: var(--messageIncommingBg);
}
.message.incoming .msg-container,
.message.incoming .msg-container .message-attachment-media {
border-bottom-left-radius: 1px;
}
.message.outgoing {
float: right;
margin-right: 0;
margin-left: 32px;
}
.message.outgoing .metadata > .date {
color: var(--messageOutgoingStatusColor);
}
.message.outgoing .metadata > .padlock-icon {
-webkit-mask: url("../images/padlock.svg") no-repeat center;
-webkit-mask-size: 125%;
background-color: var(--messagePadlockOutgoing);
}
.message.outgoing .metadata > .location-icon {
-webkit-mask: url("../images/map-marker.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messagePadlockOutgoing);
}
.message.outgoing .metadata > .status-icon.read,
.message.outgoing .metadata > .status-icon.delivered {
background-color: var(--messageOutgoingStatusColor);
}
.message.outgoing .msg-container {
background-color: var(--messageOutgoingBg);
}
.message.outgoing .msg-container,
.message.outgoing .msg-container .message-attachment-media {
border-bottom-right-radius: 1px;
}
.message.type-sticker .msg-container {
background-color: transparent !important;
}
.message.type-sticker .message-attachment-media {
background-color: transparent;
}
.message.type-sticker .message-attachment-media > .attachment-content {
margin-bottom: 20px;
}
.message.type-sticker .metadata {
float: right;
padding: 4px 10px 1px 10px;
margin-bottom: -7px;
background-color: #01010159;
border-radius: 4px;
color: black;
font-weight: bold;
}
.message.type-sticker .metadata > .date {
font-size: 11px;
color: white;
}
.message.type-sticker .metadata > .padlock-icon {
-webkit-mask: url("../images/padlock.svg") no-repeat center;
-webkit-mask-size: 125%;
background-color: #fff;
}
.message.type-sticker .metadata > .location-icon {
-webkit-mask: url("../images/map-marker.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: #fff;
}
.message.type-sticker .status-icon.read,
.message.type-sticker .status-icon.delivered {
background-color: white;
}
.message.type-sticker:hover .msg-button.menu {
background-color: white;
}
.message.type-sticker:hover .react-contextmenu-wrapper {
background-color: #2525258f;
border-radius: 4px;
}
.message.error.incoming .text {
font-style: italic;
}
.message.forwarded .forwarded-indicator {
font-weight: bold;
font-size: 0.9em;
margin-bottom: 3px;
opacity: 0.86;
}
.message.forwarded .message-attachment-media {
border-top-left-radius: 0;
border-top-right-radius: 0;
margin-top: 0;
}
.setupMessage .message .text {
color: var(--setupMessageText);
}
.hide-on-small {
display: initial;
}
@media (max-width: 800px) {
.hide-on-small {
display: none;
}
}
@media (min-width: 800px) and (max-width: 925px) {
.message {
max-width: 374px;
}
.message.incoming {
margin-right: auto;
}
.message.outgoing {
margin-left: auto;
}
}
@media (min-width: 926px) {
.message {
max-width: 66%;
}
.message.incoming {
margin-right: auto;
}
.message.outgoing {
margin-left: auto;
}
}
.metadata {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 3px;
margin-bottom: -3px;
}
.metadata.with-image-no-caption {
position: absolute;
right: 5px;
bottom: 5px;
float: right;
padding: 4px 10px 1px 10px;
margin: 0;
background-color: #0000008f;
border-radius: 4px;
font-weight: bold;
}
.metadata.with-image-no-caption > .date {
color: white;
}
.metadata.with-image-no-caption > .padlock-icon {
-webkit-mask: url("../images/padlock.svg") no-repeat center;
-webkit-mask-size: 125%;
background-color: #fff;
}
.metadata.with-image-no-caption .status-icon.sending {
background-color: white;
}
.metadata > .status-icon {
margin-bottom: 2px;
}
.metadata > .username {
margin-right: 10px;
}
.metadata > .date {
font-size: 11.5px;
line-height: 16px;
letter-spacing: 0.3px;
color: var(--messageMetadataDate);
text-transform: uppercase;
}
.metadata > .spacer {
flex-grow: 1;
}
.metadata > .padlock-icon,
.metadata > .location-icon {
width: 12px;
height: 12px;
display: inline-block;
margin-right: 2px;
margin-bottom: 3px;
}
.metadata > .location-icon {
margin-bottom: 0;
}
@keyframes __status-icon--spinning {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.status-icon {
width: 18px;
height: 12px;
display: inline-block;
margin-left: 2px;
}
.status-icon.sending {
-webkit-mask: url("../images/sending.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageStatusIconSending);
animation: __status-icon--spinning 4s linear infinite;
width: 12px;
margin-left: 8px;
}
.status-icon.delivered {
-webkit-mask: url("../images/sent.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageStatusIcon);
}
.status-icon.read {
-webkit-mask: url("../images/read.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--messageStatusIcon);
}
.status-icon.error {
-webkit-mask: url("../images/error.svg") no-repeat center;
-webkit-mask-size: 100%;
background-color: var(--errorColor);
width: 12px;
margin-left: 8px;
}

View File

@@ -46,7 +46,6 @@ if [ -n "$TESTS" ]; then
tox --workdir "$TOXWORKDIR" -e py37 -- --reruns 3 -k "not qr"
tox --workdir "$TOXWORKDIR" -e py37 -- --reruns 3 -k "qr"
unset DCC_PY_LIVECONFIG
unset DCC_NEW_TMP_EMAIL
tox --workdir "$TOXWORKDIR" -p4 -e lint,py35,py36,doc
tox --workdir "$TOXWORKDIR" -e auditwheels
popd

View File

@@ -32,11 +32,11 @@ ssh $SSHTARGET bash -c "cat >$BUILDDIR/exec_docker_run" <<_HERE
set +x -e
cd $BUILDDIR
export DCC_PY_LIVECONFIG=$DCC_PY_LIVECONFIG
export DCC_NEW_TMP_EMAIL=$DCC_NEW_TMP_EMAIL
set -x
# run everything else inside docker
docker run -e DCC_NEW_TMP_EMAIL -e DCC_PY_LIVECONFIG \
docker run -e DCC_PY_LIVECONFIG \
--rm -it -v \$(pwd):/mnt -w /mnt \
deltachat/coredeps ci_scripts/run_all.sh

View File

@@ -30,7 +30,6 @@ ssh $SSHTARGET <<_HERE
export CARGO_TARGET_DIR=\`pwd\`/../target
export TARGET=release
export DCC_PY_LIVECONFIG=$DCC_PY_LIVECONFIG
export DCC_NEW_TMP_EMAIL=$DCC_NEW_TMP_EMAIL
#we rely on tox/virtualenv being available in the host
#rm -rf virtualenv venv

View File

@@ -37,8 +37,7 @@ mkdir -p $TOXWORKDIR
# XXX we may switch on some live-tests on for better ensurances
# Note that the independent remote_tests_python step does all kinds of
# live-testing already.
unset DCC_PY_LIVECONFIG
unset DCC_NEW_TMP_EMAIL
unset DCC_PY_LIVECONFIG
tox --workdir "$TOXWORKDIR" -e py35,py36,py37,py38,auditwheels
popd

View File

@@ -1,6 +1,6 @@
[package]
name = "deltachat_ffi"
version = "1.28.0"
version = "1.25.0"
description = "Deltachat FFI"
authors = ["Delta Chat Developers (ML) <delta@codespeak.net>"]
edition = "2018"
@@ -23,6 +23,7 @@ failure = "0.1.6"
serde_json = "1.0"
[features]
default = ["vendored", "nightly"]
default = ["vendored", "nightly", "ringbuf"]
vendored = ["deltachat/vendored"]
nightly = ["deltachat/nightly"]
ringbuf = ["deltachat/ringbuf"]

View File

@@ -373,14 +373,6 @@ char* dc_get_blobdir (const dc_context_t* context);
* - `save_mime_headers` = 1=save mime headers
* and make dc_get_mime_headers() work for subsequent calls,
* 0=do not save mime headers (default)
* - `delete_device_after` = 0=do not delete messages from device automatically (default),
* >=1=seconds, after which messages are deleted automatically from the device.
* Messages in the "saved messages" chat (see dc_chat_is_self_talk()) are skipped.
* Messages are deleted whether they were seen or not, the UI should clearly point that out.
* - `delete_server_after` = 0=do not delete messages from server automatically (default),
* >=1=seconds, after which messages are deleted automatically from the server.
* "Saved messages" are deleted from the server as well as
* emails matching the `show_emails` settings above, the UI should clearly point that out.
*
* If you want to retrieve a value, use dc_get_config().
*
@@ -909,7 +901,6 @@ int dc_preconfigure_keypair (dc_context_t* context, const cha
#define DC_GCL_ARCHIVED_ONLY 0x01
#define DC_GCL_NO_SPECIALS 0x02
#define DC_GCL_ADD_ALLDONE_HINT 0x04
#define DC_GCL_FOR_FORWARDING 0x08
/**
@@ -948,8 +939,6 @@ int dc_preconfigure_keypair (dc_context_t* context, const cha
* if DC_GCL_ARCHIVED_ONLY is not set, only unarchived chats are returned and
* the pseudo-chat DC_CHAT_ID_ARCHIVED_LINK is added if there are _any_ archived
* chats
* - the flag DC_GCL_FOR_FORWARDING sorts "Saved messages" to the top of the chatlist,
* typically used on forwarding, may be combined with DC_GCL_NO_SPECIALS
* - if the flag DC_GCL_NO_SPECIALS is set, deaddrop and archive link are not added
* to the list (may be used eg. for selecting chats on forwarding, the flag is
* not needed when DC_GCL_ARCHIVED_ONLY is already set)
@@ -1303,21 +1292,6 @@ int dc_get_msg_cnt (dc_context_t* context, uint32_t ch
int dc_get_fresh_msg_cnt (dc_context_t* context, uint32_t chat_id);
/**
* Estimate the number of messages that will be deleted
* by the dc_set_config()-options `delete_device_after` or `delete_server_after`.
* This is typically used to show the estimated impact to the user before actually enabling ephemeral messages.
*
* @param context The context object as returned from dc_context_new().
* @param from_server 1=Estimate deletion count for server, 0=Estimate deletion count for device
* @param seconds Count messages older than the given number of seconds.
* @return Number of messages that are older than the given number of seconds.
* This includes emails downloaded due to the `show_emails` option.
* Messages in the "saved messages" folder are not counted as they will not be deleted automatically.
*/
int dc_estimate_deletion_cnt (dc_context_t* context, int from_server, int64_t seconds);
/**
* Returns the message IDs of all _fresh_ messages of any chat.
* Typically used for implementing notification summaries.
@@ -1681,9 +1655,8 @@ char* dc_get_mime_headers (dc_context_t* context, uint32_t ms
*/
void dc_delete_msgs (dc_context_t* context, const uint32_t* msg_ids, int msg_cnt);
/*
/**
* Empty IMAP server folder: delete all messages.
* Deprecated, use dc_set_config() with the key "delete_server_after" instead.
*
* @memberof dc_context_t
* @param context The context object as created by dc_context_new()
@@ -4151,8 +4124,28 @@ int64_t dc_lot_get_timestamp (const dc_lot_t* lot);
*/
#define DC_EMPTY_MVBOX 0x01 // Deprecated, flag for dc_empty_server(): Clear all mvbox messages
#define DC_EMPTY_INBOX 0x02 // Deprecated, flag for dc_empty_server(): Clear all INBOX messages
/**
* @defgroup DC_EMPTY DC_EMPTY
*
* These constants configure emptying imap folders with dc_empty_server()
*
* @addtogroup DC_EMPTY
* @{
*/
/**
* Clear all mvbox messages.
*/
#define DC_EMPTY_MVBOX 0x01
/**
* Clear all INBOX messages.
*/
#define DC_EMPTY_INBOX 0x02
/**
* @}
*/
/**

View File

@@ -433,7 +433,7 @@ pub unsafe extern "C" fn dc_set_config_from_qr(
pub unsafe extern "C" fn dc_get_info(context: *mut dc_context_t) -> *mut libc::c_char {
if context.is_null() {
eprintln!("ignoring careless call to dc_get_info()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_context = &*context;
let guard = ffi_context.inner.read().unwrap();
@@ -1045,25 +1045,6 @@ pub unsafe extern "C" fn dc_get_fresh_msg_cnt(
.unwrap_or(0)
}
#[no_mangle]
pub unsafe extern "C" fn dc_estimate_deletion_cnt(
context: *mut dc_context_t,
from_server: libc::c_int,
seconds: i64,
) -> libc::c_int {
if context.is_null() || seconds < 0 {
eprintln!("ignoring careless call to dc_estimate_deletion_cnt()");
return 0;
}
let ffi_context = &*context;
ffi_context
.with_inner(|ctx| {
message::estimate_deletion_cnt(ctx, from_server != 0, seconds).unwrap_or(0)
as libc::c_int
})
.unwrap_or(0)
}
#[no_mangle]
pub unsafe extern "C" fn dc_get_fresh_msgs(
context: *mut dc_context_t,
@@ -1474,7 +1455,7 @@ pub unsafe extern "C" fn dc_get_msg_info(
) -> *mut libc::c_char {
if context.is_null() {
eprintln!("ignoring careless call to dc_get_msg_info()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_context = &*context;
ffi_context
@@ -2425,7 +2406,7 @@ pub unsafe extern "C" fn dc_chat_get_type(chat: *mut dc_chat_t) -> libc::c_int {
pub unsafe extern "C" fn dc_chat_get_name(chat: *mut dc_chat_t) -> *mut libc::c_char {
if chat.is_null() {
eprintln!("ignoring careless call to dc_chat_get_name()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_chat = &*chat;
ffi_chat.chat.get_name().strdup()
@@ -2747,7 +2728,7 @@ pub unsafe extern "C" fn dc_msg_get_sort_timestamp(msg: *mut dc_msg_t) -> i64 {
pub unsafe extern "C" fn dc_msg_get_text(msg: *mut dc_msg_t) -> *mut libc::c_char {
if msg.is_null() {
eprintln!("ignoring careless call to dc_msg_get_text()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_msg = &*msg;
ffi_msg.message.get_text().unwrap_or_default().strdup()
@@ -2766,7 +2747,8 @@ pub unsafe extern "C" fn dc_msg_get_file(msg: *mut dc_msg_t) -> *mut libc::c_cha
ffi_msg
.message
.get_file(ctx)
.map(|p| p.strdup())
.and_then(|p| p.to_c_string().ok())
.map(|cs| dc_strdup(cs.as_ptr()))
.unwrap_or_else(|| "".strdup())
})
.unwrap_or_else(|_| "".strdup())
@@ -2776,7 +2758,7 @@ pub unsafe extern "C" fn dc_msg_get_file(msg: *mut dc_msg_t) -> *mut libc::c_cha
pub unsafe extern "C" fn dc_msg_get_filename(msg: *mut dc_msg_t) -> *mut libc::c_char {
if msg.is_null() {
eprintln!("ignoring careless call to dc_msg_get_filename()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_msg = &*msg;
ffi_msg.message.get_filename().unwrap_or_default().strdup()
@@ -2786,13 +2768,13 @@ pub unsafe extern "C" fn dc_msg_get_filename(msg: *mut dc_msg_t) -> *mut libc::c
pub unsafe extern "C" fn dc_msg_get_filemime(msg: *mut dc_msg_t) -> *mut libc::c_char {
if msg.is_null() {
eprintln!("ignoring careless call to dc_msg_get_filemime()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_msg = &*msg;
if let Some(x) = ffi_msg.message.get_filemime() {
x.strdup()
} else {
"".strdup()
dc_strdup(ptr::null())
}
}
@@ -3116,7 +3098,7 @@ pub unsafe extern "C" fn dc_contact_get_id(contact: *mut dc_contact_t) -> u32 {
pub unsafe extern "C" fn dc_contact_get_addr(contact: *mut dc_contact_t) -> *mut libc::c_char {
if contact.is_null() {
eprintln!("ignoring careless call to dc_contact_get_addr()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_contact = &*contact;
ffi_contact.contact.get_addr().strdup()
@@ -3126,7 +3108,7 @@ pub unsafe extern "C" fn dc_contact_get_addr(contact: *mut dc_contact_t) -> *mut
pub unsafe extern "C" fn dc_contact_get_name(contact: *mut dc_contact_t) -> *mut libc::c_char {
if contact.is_null() {
eprintln!("ignoring careless call to dc_contact_get_name()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_contact = &*contact;
ffi_contact.contact.get_name().strdup()
@@ -3138,7 +3120,7 @@ pub unsafe extern "C" fn dc_contact_get_display_name(
) -> *mut libc::c_char {
if contact.is_null() {
eprintln!("ignoring careless call to dc_contact_get_display_name()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_contact = &*contact;
ffi_contact.contact.get_display_name().strdup()
@@ -3150,7 +3132,7 @@ pub unsafe extern "C" fn dc_contact_get_name_n_addr(
) -> *mut libc::c_char {
if contact.is_null() {
eprintln!("ignoring careless call to dc_contact_get_name_n_addr()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_contact = &*contact;
ffi_contact.contact.get_name_n_addr().strdup()
@@ -3162,7 +3144,7 @@ pub unsafe extern "C" fn dc_contact_get_first_name(
) -> *mut libc::c_char {
if contact.is_null() {
eprintln!("ignoring careless call to dc_contact_get_first_name()");
return "".strdup();
return dc_strdup(ptr::null());
}
let ffi_contact = &*contact;
ffi_contact.contact.get_first_name().strdup()

View File

@@ -9,7 +9,7 @@ use std::ptr;
/// # Examples
///
/// ```rust,norun
/// use crate::string::{dc_strdup, to_string_lossy};
/// use deltachat::dc_tools::{dc_strdup, to_string_lossy};
/// unsafe {
/// let str_a = b"foobar\x00" as *const u8 as *const libc::c_char;
/// let str_a_copy = dc_strdup(str_a);
@@ -17,7 +17,7 @@ use std::ptr;
/// assert_ne!(str_a, str_a_copy);
/// }
/// ```
unsafe fn dc_strdup(s: *const libc::c_char) -> *mut libc::c_char {
pub unsafe fn dc_strdup(s: *const libc::c_char) -> *mut libc::c_char {
let ret: *mut libc::c_char;
if !s.is_null() {
ret = libc::strdup(s);
@@ -32,7 +32,7 @@ unsafe fn dc_strdup(s: *const libc::c_char) -> *mut libc::c_char {
/// Error type for the [OsStrExt] trait
#[derive(Debug, Fail, PartialEq)]
pub(crate) enum CStringError {
pub enum CStringError {
/// The string contains an interior null byte
#[fail(display = "String contains an interior null byte")]
InteriorNullByte,
@@ -66,7 +66,7 @@ pub(crate) enum CStringError {
/// let mut c_ptr: *mut libc::c_char = dc_strdup(path_c.as_ptr());
/// }
/// ```
pub(crate) trait OsStrExt {
pub trait OsStrExt {
/// Convert a [std::ffi::OsStr] to an [std::ffi::CString]
///
/// This is useful to convert e.g. a [std::path::Path] to
@@ -131,16 +131,15 @@ fn os_str_to_c_string_unicode(
}
/// Convenience methods/associated functions for working with [CString]
trait CStringExt {
/// Create a new [CString], best effort
///
/// This is helps transitioning from unsafe code.
pub trait CStringExt {
/// Create a new [CString], yolo style
///
/// Like the [to_string_lossy] this doesn't give up in the face of
/// bad input (embedded null bytes in this case) instead it does
/// the best it can by stripping the embedded null bytes.
fn new_lossy<T: Into<Vec<u8>>>(t: T) -> CString {
let mut s = t.into();
s.retain(|&c| c != 0);
CString::new(s).unwrap_or_default()
/// This unwrap the result, panicking when there are embedded NULL
/// bytes.
fn yolo<T: Into<Vec<u8>>>(t: T) -> CString {
CString::new(t).expect("String contains null byte, can not be CString")
}
}
@@ -152,7 +151,7 @@ impl CStringExt for CString {}
/// Rust strings to raw C strings. This can be clumsy to do correctly
/// and the compiler sometimes allows it in an unsafe way. These
/// methods make it more succinct and help you get it right.
pub(crate) trait Strdup {
pub trait StrExt {
/// Allocate a new raw C `*char` version of this string.
///
/// This allocates a new raw C string which must be freed using
@@ -169,44 +168,35 @@ pub(crate) trait Strdup {
unsafe fn strdup(&self) -> *mut libc::c_char;
}
impl<T: AsRef<str>> Strdup for T {
impl<T: AsRef<str>> StrExt for T {
unsafe fn strdup(&self) -> *mut libc::c_char {
let tmp = CString::new_lossy(self.as_ref());
dc_strdup(tmp.as_ptr())
}
}
// We can not implement for AsRef<OsStr> because we already implement
// AsRev<str> and this conflicts. So implement for Path directly.
impl Strdup for std::path::Path {
unsafe fn strdup(&self) -> *mut libc::c_char {
let tmp = self.to_c_string().unwrap_or_else(|_| CString::default());
let tmp = CString::yolo(self.as_ref());
dc_strdup(tmp.as_ptr())
}
}
/// Convenience methods to turn optional strings into C strings.
///
/// This is the same as the [Strdup] trait but a different trait name
/// to work around the type system not allowing to implement [Strdup]
/// for `Option<impl Strdup>` When we already have an [Strdup] impl
/// This is the same as the [StrExt] trait but a different trait name
/// to work around the type system not allowing to implement [StrExt]
/// for `Option<impl StrExt>` When we already have an [StrExt] impl
/// for `AsRef<&str>`.
///
/// When the [Option] is [Option::Some] this behaves just like
/// [Strdup::strdup], when it is [Option::None] a null pointer is
/// [StrExt::strdup], when it is [Option::None] a null pointer is
/// returned.
pub(crate) trait OptStrdup {
pub trait OptStrExt {
/// Allocate a new raw C `*char` version of this string, or NULL.
///
/// See [Strdup::strdup] for details.
/// See [StrExt::strdup] for details.
unsafe fn strdup(&self) -> *mut libc::c_char;
}
impl<T: AsRef<str>> OptStrdup for Option<T> {
impl<T: AsRef<str>> OptStrExt for Option<T> {
unsafe fn strdup(&self) -> *mut libc::c_char {
match self {
Some(s) => {
let tmp = CString::new_lossy(s.as_ref());
let tmp = CString::yolo(s.as_ref());
dc_strdup(tmp.as_ptr())
}
None => ptr::null_mut(),
@@ -214,7 +204,7 @@ impl<T: AsRef<str>> OptStrdup for Option<T> {
}
}
pub(crate) fn to_string_lossy(s: *const libc::c_char) -> String {
pub fn to_string_lossy(s: *const libc::c_char) -> String {
if s.is_null() {
return "".into();
}
@@ -224,7 +214,7 @@ pub(crate) fn to_string_lossy(s: *const libc::c_char) -> String {
cstr.to_string_lossy().to_string()
}
pub(crate) fn to_opt_string_lossy(s: *const libc::c_char) -> Option<String> {
pub fn to_opt_string_lossy(s: *const libc::c_char) -> Option<String> {
if s.is_null() {
return None;
}
@@ -245,7 +235,7 @@ pub(crate) fn to_opt_string_lossy(s: *const libc::c_char) -> Option<String> {
///
/// [Path]: std::path::Path
#[cfg(not(target_os = "windows"))]
pub(crate) fn as_path<'a>(s: *const libc::c_char) -> &'a std::path::Path {
pub fn as_path<'a>(s: *const libc::c_char) -> &'a std::path::Path {
assert!(!s.is_null(), "cannot be used on null pointers");
use std::os::unix::ffi::OsStrExt;
unsafe {
@@ -257,7 +247,7 @@ pub(crate) fn as_path<'a>(s: *const libc::c_char) -> &'a std::path::Path {
// as_path() implementation for windows, documented above.
#[cfg(target_os = "windows")]
pub(crate) fn as_path<'a>(s: *const libc::c_char) -> &'a std::path::Path {
pub fn as_path<'a>(s: *const libc::c_char) -> &'a std::path::Path {
as_path_unicode(s)
}
@@ -364,14 +354,8 @@ mod tests {
}
#[test]
fn test_cstring_new_lossy() {
assert!(CString::new("hel\x00lo").is_err());
assert!(CString::new(String::from("hel\x00o")).is_err());
let r = CString::new("hello").unwrap();
assert_eq!(CString::new_lossy("hello"), r);
assert_eq!(CString::new_lossy("hel\x00lo"), r);
assert_eq!(CString::new_lossy(String::from("hello")), r);
assert_eq!(CString::new_lossy(String::from("hel\x00lo")), r);
fn test_cstring_yolo() {
assert_eq!(CString::new("hello").unwrap(), CString::yolo("hello"));
}
#[test]

View File

@@ -1,126 +0,0 @@
Problem: missing eventual group consistency
--------------------------------------------
If group members are concurrently adding new members,
the new members will miss each other's additions, example:
- Alice and Bob are in a two-member group
- Alice adds Carol, concurrently Bob adds Doris
- Carol will see a three-member group (Alice, Bob, Carol),
Doris will see a different three-member group (Alice, Bob, Doris),
and only Alice and Bob will have all four members.
Note that for verified groups any mitigation mechanism likely
needs to make all clients to know who originally added a member.
solution: memorize+attach (possible encrypted) chat-meta mime messages
----------------------------------------------------------------------
For reference, please see https://github.com/deltachat/deltachat-core-rust/blob/master/spec.md#add-and-remove-members how MemberAdded/Removed messages are shaped.
- All Chat-Group-Member-Added/Removed messages are recorded in their
full raw (signed and encrypted) mime-format in the DB
- If an incoming member-add/member-delete messages has a member list
which is, apart from the added/removed member, not consistent
with our own view, broadcast a "Chat-Group-Member-Correction" message to
all members, attaching the original added/removed mime-message for all mismatching
contacts. If we have no relevant add/del information, don't send a
correction message out.
- Upong receiving added/removed attachments we don't do the
check_consistency+correction message dance.
This avoids recursion problems and hard-to-reason-about chatter.
Notes:
- mechanism works for both encrypted and unencrypted add/del messages
- we already have a "mime_headers" column in the DB for each incoming message.
We could extend it to also include the payload and store mime unconditionally
for member-added/removed messages.
- multiple member-added/removed messages can be attached in a single
correction message
- it is minimal on the number of overall messages to reach group consistency
(best-case: no extra messages, the ABCD case above: max two extra messages)
- somewhat backward compatible: older clients will probably ignore
messages which are signed by someone who is not the outer From-address.
- the correction-protocol also helps with dropped messages. If a member
did not see a member-added/removed message, the next member add/removed
message in the group will likely heal group consistency for this member.
- we can quite easily extend the mechanism to also provide the group-avatar or
other meta-information.
Discussions of variants
++++++++++++++++++++++++
- instead of acting on MemberAdded/Removed message we could send
corrections for any received message that addresses inconsistent group members but
a) this would delay group-membership healing
b) could lead to a lot of members sending corrections
- instead of broadcasting correction messages we could only send it to
the sender of the inconsistent member-added/removed message.
A receiver of such a correction message would then need to forward
the message to the members it thinks also have an inconsistent view.
This sounds complicated and error-prone. Concretely, if Alice
receives Bob's "Member-added: Doris" message, then Alice
broadcasting the correction message with "Member-added: Carol"
would reach all four members, healing group consistency in one step.
If Bob meanwhile receives Alice's "Member-Added: Carol" message,
Bob would broadcast a correction message to all four members as well.
(Imagine a situation where Alice/Bob added Carol/Doris
while both being in an offline or bad-connection situation).
solution2: repeat member-added/removed messages
---------------------------------------------------
Introduce a new Chat-Group-Member-Changed header and deprecate Chat-Group-Member-Added/Removed
but keep sending out the old headers until the new protocol is sufficiently deployed.
The new Chat-Group-Member-Changed header contains a Time-to-Live number (TTL)
which controls repetition of the signed "add/del e-mail address" payload.
Example::
Chat-Group-Member-Changed: TTL add "somedisplayname" someone@example.org
owEBYQGe/pANAwACAY47A6J5t3LWAcsxYgBeTQypYWRkICJzb21lZGlzcGxheW5h
bWUiIHNvbWVvbmVAZXhhbXBsZS5vcmcgCokBHAQAAQIABgUCXk0MqQAKCRCOOwOi
ebdy1hfRB/wJ74tgFQulicthcv9n+ZsqzwOtBKMEVIHqJCzzDB/Hg/2z8ogYoZNR
iUKKrv3Y1XuFvdKyOC+wC/unXAWKFHYzY6Tv6qDp6r+amt+ad+8Z02q53h9E55IP
FUBdq2rbS8hLGjQB+mVRowYrUACrOqGgNbXMZjQfuV7fSc7y813OsCQgi3tjstup
b+uduVzxCp3PChGhcZPs3iOGCnQvSB8VAaLGMWE2d7nTo/yMQ0Jx69x5qwfXogTk
mTt5rOJyrosbtf09TMKFzGgtqBcEqHLp3+mQpZQ+WHUKAbsRa8Jc9DOUOSKJ8SNM
clKdskprY+4LY0EBwLD3SQ7dPkTITCRD
=P6GG
TTL is set to "2" on an initial Chat-Group-Member-Changed add/del message.
Receivers will apply the add/del change to the group-membership,
decrease the TTL by 1, and if TTL>0 re-sent the header.
The "add|del e-mail address" payload is pgp-signed and repeated verbatim.
This allows to propagate, in a cryptographically secured way,
who added a member. This is particularly important for allowing
to show in verified groups who added a member (planned).
Disadvantage to solution 1:
- requires to specify encoding and precise rules for what/how is signed.
- causes O(N^2) extra messages
- Not easily extendable for other things (without introducing a new
header / encoding)

View File

@@ -1,6 +1,5 @@
use std::path::Path;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
use deltachat::chat::{self, Chat, ChatId, ChatVisibility};
use deltachat::chatlist::*;
@@ -10,7 +9,6 @@ use deltachat::context::*;
use deltachat::dc_receive_imf::*;
use deltachat::dc_tools::*;
use deltachat::error::Error;
use deltachat::export_chat::{export_chat, pack_exported_chat};
use deltachat::imex::*;
use deltachat::job::*;
use deltachat::location;
@@ -376,7 +374,6 @@ pub fn dc_cmdline(context: &Context, line: &str) -> Result<(), failure::Error> {
pin <chat-id>\n\
unpin <chat-id>\n\
delchat <chat-id>\n\
export-chat <chat-id>\n\
===========================Message commands==\n\
listmsgs <query>\n\
msginfo <msg-id>\n\
@@ -400,7 +397,6 @@ pub fn dc_cmdline(context: &Context, line: &str) -> Result<(), failure::Error> {
providerinfo <addr>\n\
event <event-id to test>\n\
fileinfo <file>\n\
estimatedeletion <seconds>\n\
emptyserver <flags> (1=MVBOX 2=INBOX)\n\
clear -- clear screen\n\
exit or quit\n\
@@ -871,24 +867,6 @@ pub fn dc_cmdline(context: &Context, line: &str) -> Result<(), failure::Error> {
let chat_id = ChatId::new(arg1.parse()?);
chat_id.delete(context)?;
}
"export-chat" => {
ensure!(!arg1.is_empty(), "Argument <chat-id> missing.");
let chat_id = ChatId::new(arg1.parse()?);
let res = export_chat(context, chat_id);
println!("{:?}", res);
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let destination_raw = context.get_blobdir().join(format!(
"exported_{}_{}.zip",
chat_id.to_u32(),
timestamp
));
let destination = destination_raw.to_str().unwrap();
let pack_res = pack_exported_chat(context, res, destination);
println!("{:?} - destination: {}", pack_res, destination);
}
"msginfo" => {
ensure!(!arg1.is_empty(), "Argument <msg-id> missing.");
let id = MsgId::new(arg1.parse()?);
@@ -1050,16 +1028,6 @@ pub fn dc_cmdline(context: &Context, line: &str) -> Result<(), failure::Error> {
bail!("Command failed.");
}
}
"estimatedeletion" => {
ensure!(!arg1.is_empty(), "Argument <seconds> missing");
let seconds = arg1.parse()?;
let device_cnt = message::estimate_deletion_cnt(context, false, seconds)?;
let server_cnt = message::estimate_deletion_cnt(context, true, seconds)?;
println!(
"estimated count of messages older than {} seconds:\non device: {}\non server: {}",
seconds, device_cnt, server_cnt
);
}
"emptyserver" => {
ensure!(!arg1.is_empty(), "Argument <flags> missing");

View File

@@ -262,7 +262,7 @@ const DB_COMMANDS: [&str; 11] = [
"housekeeping",
];
const CHAT_COMMANDS: [&str; 27] = [
const CHAT_COMMANDS: [&str; 26] = [
"listchats",
"listarchived",
"chat",
@@ -289,7 +289,6 @@ const CHAT_COMMANDS: [&str; 27] = [
"pin",
"unpin",
"delchat",
"export-chat",
];
const MESSAGE_COMMANDS: [&str; 8] = [
"listmsgs",
@@ -309,17 +308,8 @@ const CONTACT_COMMANDS: [&str; 6] = [
"delcontact",
"cleanupcontacts",
];
const MISC_COMMANDS: [&str; 10] = [
"getqr",
"getbadqr",
"checkqr",
"event",
"fileinfo",
"clear",
"exit",
"quit",
"help",
"estimatedeletion",
const MISC_COMMANDS: [&str; 9] = [
"getqr", "getbadqr", "checkqr", "event", "fileinfo", "clear", "exit", "quit", "help",
];
impl Hinter for DcHelper {

View File

@@ -38,7 +38,7 @@ class Account(object):
lib.dc_context_new(lib.py_dc_callback, ffi.NULL, as_dc_charpointer(os_name)),
_destroy_dc_context,
)
self._evlogger = EventLogger(self, logid, debug)
self._evlogger = EventLogger(self._dc_context, logid, debug)
self._threads = IOThreads(self._dc_context, self._evlogger._log_event)
# register event call back and initialize plugin system
@@ -386,7 +386,15 @@ class Account(object):
lib.dc_imex(self._dc_context, imex_cmd, as_dc_charpointer(path), ffi.NULL)
if not self._threads.is_started():
lib.dc_perform_imap_jobs(self._dc_context)
return imex_tracker.wait_finish()
files_written = []
while True:
ev = imex_tracker.get()
if isinstance(ev, str):
files_written.append(ev)
elif isinstance(ev, bool):
if not ev:
raise ValueError("export failed, exp-files: {}".format(files_written))
return files_written
def import_self_keys(self, path):
""" Import private keys found in the `path` directory.
@@ -408,7 +416,8 @@ class Account(object):
lib.dc_imex(self._dc_context, imex_cmd, as_dc_charpointer(path), ffi.NULL)
if not self._threads.is_started():
lib.dc_perform_imap_jobs(self._dc_context)
imex_tracker.wait_finish()
if not imex_tracker.get():
raise ValueError("import from path '{}' failed".format(path))
def initiate_key_transfer(self):
"""return setup code after a Autocrypt setup message
@@ -511,7 +520,7 @@ class Account(object):
deltachat.clear_context_callback(self._dc_context)
del self._dc_context
atexit.unregister(self.shutdown)
self.pluggy.unregister(self._evlogger)
self.pluggy.unregister(self)
def set_location(self, latitude=0.0, longitude=0.0, accuracy=0.0):
"""set a new location. It effects all chats where we currently
@@ -533,6 +542,16 @@ class ImexTracker:
self._imex_events = Queue()
self.account = account
@hookimpl
def process_low_level_event(self, account, event_name, data1, data2):
# there could be multiple accounts instantiated
if self.account is not account:
return
method = getattr(self, "on_" + event_name.lower(), None)
if method is not None:
print("*** on_ -> ", event_name.lower())
method(data1, data2)
def __enter__(self):
self.account.pluggy.register(self)
return self
@@ -540,27 +559,17 @@ class ImexTracker:
def __exit__(self, *args):
self.account.pluggy.unregister(self)
@hookimpl
def process_low_level_event(self, account, event_name, data1, data2):
# there could be multiple accounts instantiated
if self.account is not account:
return
if event_name == "DC_EVENT_IMEX_PROGRESS":
self._imex_events.put(data1)
elif event_name == "DC_EVENT_IMEX_FILE_WRITTEN":
self._imex_events.put(data1)
def get(self, timeout=60):
return self._imex_events.get(timeout=timeout)
def wait_finish(self, progress_timeout=60):
""" Return list of written files, raise ValueError if ExportFailed. """
files_written = []
while True:
ev = self._imex_events.get(timeout=progress_timeout)
if isinstance(ev, str):
files_written.append(ev)
elif ev == 0:
raise ValueError("export failed, exp-files: {}".format(files_written))
elif ev == 1000:
return files_written
def on_dc_event_imex_progress(self, data1, data2):
if data1 == 1000:
self._imex_events.put(True)
elif data1 == 0:
self._imex_events.put(False)
def on_dc_event_imex_file_written(self, data1, data2):
self._imex_events.put(data1)
class IOThreads:

View File

@@ -8,28 +8,27 @@ from .hookspec import hookimpl
class EventLogger:
_loglock = threading.RLock()
def __init__(self, account, logid=None, debug=True):
self.account = account
def __init__(self, dc_context, logid=None, debug=True):
self._dc_context = dc_context
self._event_queue = Queue()
self._debug = debug
if logid is None:
logid = str(self.account._dc_context).strip(">").split()[-1]
logid = str(self._dc_context).strip(">").split()[-1]
self.logid = logid
self._timeout = None
self.init_time = time.time()
@hookimpl
def process_low_level_event(self, account, event_name, data1, data2):
if self.account == account:
self._log_event(event_name, data1, data2)
self._event_queue.put((event_name, data1, data2))
def process_low_level_event(self, event_name, data1, data2):
self._log_event(event_name, data1, data2)
self._event_queue.put((event_name, data1, data2))
def set_timeout(self, timeout):
self._timeout = timeout
def consume_events(self, check_error=True):
while not self._event_queue.empty():
self.get(check_error=check_error)
self.get()
def get(self, timeout=None, check_error=True):
timeout = timeout or self._timeout

View File

@@ -1,25 +0,0 @@
""" Hooks for python bindings """
import pluggy
name = "deltachat"
hookspec = pluggy.HookspecMarker(name)
hookimpl = pluggy.HookimplMarker(name)
_plugin_manager = None
def get_plugin_manager():
global _plugin_manager
if _plugin_manager is None:
_plugin_manager = pluggy.PluginManager(name)
_plugin_manager.add_hookspecs(DeltaChatHookSpecs)
return _plugin_manager
class DeltaChatHookSpecs:
""" Plugin Hook specifications for Python bindings to Delta Chat CFFI. """
@hookspec
def process_low_level_event(self, account, event_name, data1, data2):
""" process a CFFI low level events for a given account. """

View File

@@ -76,20 +76,6 @@ class TestOfflineAccountBasic:
with pytest.raises(KeyError):
ac1.get_config("123123")
def test_empty_group_bcc_self_enabled(self, acfactory):
ac1 = acfactory.get_configured_offline_account()
ac1.set_config("bcc_self", "1")
chat = ac1.create_group_chat(name="group1")
msg = chat.send_text("msg1")
assert msg in chat.get_messages()
def test_empty_group_bcc_self_disabled(self, acfactory):
ac1 = acfactory.get_configured_offline_account()
ac1.set_config("bcc_self", "0")
chat = ac1.create_group_chat(name="group1")
msg = chat.send_text("msg1")
assert msg in chat.get_messages()
class TestOfflineContact:
def test_contact_attr(self, acfactory):
@@ -1380,80 +1366,6 @@ class TestGroupStressTests:
# Message should be encrypted because keys of other members are gossiped
assert msg.is_encrypted()
def test_synchronize_member_list_on_group_rejoin(self, acfactory, lp):
"""
Test that user recreates group member list when it joins the group again.
ac1 creates a group with two other accounts: ac2 and ac3
Then it removes ac2, removes ac3 and adds ac2 back.
ac2 did not see that ac3 is removed, so it should rebuild member list from scratch.
"""
lp.sec("creating and configuring five accounts")
accounts = [acfactory.get_online_configuring_account() for i in range(3)]
for acc in accounts:
wait_configuration_progress(acc, 1000)
ac1 = accounts.pop()
lp.sec("ac1: setting up contacts with 2 other members")
contacts = []
for acc, name in zip(accounts, ["ac2", "ac3"]):
contact = ac1.create_contact(acc.get_config("addr"), name=name)
contacts.append(contact)
# make sure we accept the "hi" message
ac1.create_chat_by_contact(contact)
# make sure the other side accepts our messages
c1 = acc.create_contact(ac1.get_config("addr"), "a member")
chat1 = acc.create_chat_by_contact(c1)
# send a message to get the contact key via autocrypt header
chat1.send_text("hi")
msg = ac1.wait_next_incoming_message()
assert msg.text == "hi"
ac2, ac3 = accounts
lp.sec("ac1: creating group chat with 2 other members")
chat = ac1.create_group_chat("title1")
for contact in contacts:
chat.add_contact(contact)
assert not chat.is_promoted()
lp.sec("ac1: send mesage to new group chat")
msg = chat.send_text("hello")
assert chat.is_promoted()
assert msg.is_encrypted()
num_contacts = len(chat.get_contacts())
assert num_contacts == 3
lp.sec("checking that the chat arrived correctly")
for ac in accounts:
msg = ac.wait_next_incoming_message()
assert msg.text == "hello"
print("chat is", msg.chat)
assert len(msg.chat.get_contacts()) == 3
lp.sec("ac1: removing ac2")
chat.remove_contact(contacts[0])
lp.sec("ac2: wait for a message about removal from the chat")
msg = ac2.wait_next_incoming_message()
lp.sec("ac1: removing ac3")
chat.remove_contact(contacts[1])
lp.sec("ac1: adding ac2 back")
# Group is promoted, message is sent automatically
assert chat.is_promoted()
chat.add_contact(contacts[0])
lp.sec("ac2: check that ac3 is removed")
msg = ac2.wait_next_incoming_message()
assert len(msg.chat.get_contacts()) == len(chat.get_contacts())
class TestOnlineConfigureFails:
def test_invalid_password(self, acfactory):

View File

@@ -2,6 +2,7 @@ from __future__ import print_function
from deltachat import capi, cutil, const, set_context_callback, clear_context_callback
from deltachat.capi import ffi
from deltachat.capi import lib
from deltachat.account import EventLogger
def test_empty_context():
@@ -17,13 +18,21 @@ def test_callback_None2int():
def test_dc_close_events(tmpdir):
from deltachat.account import Account
ctx = ffi.gc(
capi.lib.dc_context_new(capi.lib.py_dc_callback, ffi.NULL, ffi.NULL),
lib.dc_context_unref,
)
evlog = EventLogger(ctx)
evlog.set_timeout(5)
set_context_callback(
ctx,
lambda ctx, evt_name, data1, data2: evlog(evt_name, data1, data2)
)
p = tmpdir.join("hello.db")
ac1 = Account(p.strpath)
ac1.shutdown()
lib.dc_open(ctx, p.strpath.encode("ascii"), ffi.NULL)
capi.lib.dc_close(ctx)
def find(info_string):
evlog = ac1._evlogger
while 1:
ev = evlog.get_matching("DC_EVENT_INFO", check_error=False)
data2 = ev[2]

View File

@@ -14,7 +14,6 @@ passenv =
DCC_RS_DEV
DCC_RS_TARGET
DCC_PY_LIVECONFIG
DCC_NEW_TMP_EMAIL
CARGO_TARGET_DIR
RUSTC_WRAPPER
deps =

View File

@@ -75,7 +75,7 @@ impl Aheader {
wanted_from: &str,
headers: &[mailparse::MailHeader<'_>],
) -> Option<Self> {
if let Some(value) = headers.get_header_value(HeaderDef::Autocrypt) {
if let Ok(Some(value)) = headers.get_header_value(HeaderDef::Autocrypt) {
match Self::from_str(&value) {
Ok(header) => {
if addr_cmp(&header.addr, wanted_from) {

View File

@@ -286,7 +286,10 @@ impl ChatId {
/// Returns `true`, if message was deleted, `false` otherwise.
fn maybe_delete_draft(self, context: &Context) -> bool {
match self.get_draft_msg_id(context) {
Some(msg_id) => msg_id.delete_from_db(context).is_ok(),
Some(msg_id) => {
Message::delete_from_db(context, msg_id);
true
}
None => false,
}
}
@@ -359,25 +362,6 @@ impl ChatId {
.unwrap_or_default() as usize
}
pub(crate) fn get_param(self, context: &Context) -> Result<Params, Error> {
let res: Option<String> = context
.sql
.query_get_value_result("SELECT param FROM chats WHERE id=?", params![self])?;
Ok(res
.map(|s| s.parse().unwrap_or_default())
.unwrap_or_default())
}
// Returns true if chat is a saved messages chat.
pub fn is_self_talk(self, context: &Context) -> Result<bool, Error> {
Ok(self.get_param(context)?.exists(Param::Selftalk))
}
/// Returns true if chat is a device chat.
pub fn is_device_talk(self, context: &Context) -> Result<bool, Error> {
Ok(self.get_param(context)?.exists(Param::Devicetalk))
}
/// Bad evil escape hatch.
///
/// Avoid using this, eventually types should be cleaned up enough
@@ -1466,18 +1450,6 @@ pub fn get_chat_msgs(
flags: u32,
marker1before: Option<MsgId>,
) -> Vec<MsgId> {
match hide_device_expired_messages(context) {
Err(err) => warn!(context, "Failed to delete expired messages: {}", err),
Ok(messages_deleted) => {
if messages_deleted {
context.call_cb(Event::MsgsChanged {
msg_id: MsgId::new(0),
chat_id: ChatId::new(0),
})
}
}
}
let process_row =
|row: &rusqlite::Row| Ok((row.get::<_, MsgId>("id")?, row.get::<_, i64>("timestamp")?));
let process_rows = |rows: rusqlite::MappedRows<_>| {
@@ -1612,47 +1584,6 @@ pub fn marknoticed_all_chats(context: &Context) -> Result<(), Error> {
Ok(())
}
/// Hides messages which are expired according to "delete_device_after" setting.
///
/// Returns true if any message is hidden, so event can be emitted. If nothing
/// has been hidden, returns false.
pub fn hide_device_expired_messages(context: &Context) -> Result<bool, Error> {
if let Some(delete_device_after) = context.get_config_delete_device_after() {
let threshold_timestamp = time() - delete_device_after;
let self_chat_id = lookup_by_contact_id(context, DC_CONTACT_ID_SELF)
.unwrap_or_default()
.0;
let device_chat_id = lookup_by_contact_id(context, DC_CONTACT_ID_DEVICE)
.unwrap_or_default()
.0;
// Hide expired messages
//
// Only update the rows that have to be updated, to avoid emitting
// unnecessary "chat modified" events.
let rows_modified = context.sql.execute(
"UPDATE msgs \
SET txt = 'DELETED', hidden = 1 \
WHERE timestamp < ? \
AND chat_id > ? \
AND chat_id != ? \
AND chat_id != ? \
AND NOT hidden",
params![
threshold_timestamp,
DC_CHAT_ID_LAST_SPECIAL,
self_chat_id,
device_chat_id
],
)?;
Ok(rows_modified > 0)
} else {
Ok(false)
}
}
pub fn get_chat_media(
context: &Context,
chat_id: ChatId,
@@ -2132,7 +2063,7 @@ pub fn remove_contact_from_chat(
"Cannot remove contact from chat; self not in group.".into()
)
);
} else if remove_from_chat_contacts_table(context, chat_id, contact_id) {
} else {
/* we should respect this - whatever we send to the group, it gets discarded anyway! */
if let Ok(contact) = Contact::get_by_id(context, contact_id) {
if chat.is_promoted() {
@@ -2162,9 +2093,10 @@ pub fn remove_contact_from_chat(
});
}
}
context.call_cb(Event::ChatModified(chat_id));
success = true;
if remove_from_chat_contacts_table(context, chat_id, contact_id) {
context.call_cb(Event::ChatModified(chat_id));
success = true;
}
}
}
}

View File

@@ -1,6 +1,5 @@
//! # Chat list module
use crate::chat;
use crate::chat::*;
use crate::constants::*;
use crate::contact::*;
@@ -74,9 +73,6 @@ impl Chatlist {
/// if DC_GCL_ARCHIVED_ONLY is not set, only unarchived chats are returned and
/// the pseudo-chat DC_CHAT_ID_ARCHIVED_LINK is added if there are *any* archived
/// chats
/// - the flag DC_GCL_FOR_FORWARDING sorts "Saved messages" to the top of the chatlist
/// and hides the device-chat,
// typically used on forwarding, may be combined with DC_GCL_NO_SPECIALS
/// - if the flag DC_GCL_NO_SPECIALS is set, deaddrop and archive link are not added
/// to the list (may be used eg. for selecting chats on forwarding, the flag is
/// not needed when DC_GCL_ARCHIVED_ONLY is already set)
@@ -92,12 +88,6 @@ impl Chatlist {
query: Option<&str>,
query_contact_id: Option<u32>,
) -> Result<Self> {
// Note that we do not emit DC_EVENT_MSGS_MODIFIED here even if some
// messages get hidden to avoid reloading the same chatlist.
if let Err(err) = hide_device_expired_messages(context) {
warn!(context, "Failed to hide expired messages: {}", err);
}
let mut add_archived_link_item = false;
let process_row = |row: &rusqlite::Row| {
@@ -111,14 +101,6 @@ impl Chatlist {
.map_err(Into::into)
};
let skip_id = if 0 != listflags & DC_GCL_FOR_FORWARDING {
chat::lookup_by_contact_id(context, DC_CONTACT_ID_DEVICE)
.unwrap_or_default()
.0
} else {
ChatId::new(0)
};
// select with left join and minimum:
//
// - the inner select must use `hidden` and _not_ `m.hidden`
@@ -157,9 +139,6 @@ impl Chatlist {
)?
} else if 0 != listflags & DC_GCL_ARCHIVED_ONLY {
// show archived chats
// (this includes the archived device-chat; we could skip it,
// however, then the number of archived chats do not match, which might be even more irritating.
// and adapting the number requires larger refactorings and seems not to be worth the effort)
context.sql.query_map(
"SELECT c.id, m.id
FROM chats c
@@ -199,25 +178,18 @@ impl Chatlist {
SELECT MAX(timestamp)
FROM msgs
WHERE chat_id=c.id
AND (hidden=0 OR state=?1))
WHERE c.id>9 AND c.id!=?2
AND (hidden=0 OR state=?))
WHERE c.id>9
AND c.blocked=0
AND c.name LIKE ?3
AND c.name LIKE ?
GROUP BY c.id
ORDER BY IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
params![MessageState::OutDraft, skip_id, str_like_cmd],
params![MessageState::OutDraft, str_like_cmd],
process_row,
process_rows,
)?
} else {
// show normal chatlist
let sort_id_up = if 0 != listflags & DC_GCL_FOR_FORWARDING {
chat::lookup_by_contact_id(context, DC_CONTACT_ID_SELF)
.unwrap_or_default()
.0
} else {
ChatId::new(0)
};
let mut ids = context.sql.query_map(
"SELECT c.id, m.id
FROM chats c
@@ -228,23 +200,21 @@ impl Chatlist {
FROM msgs
WHERE chat_id=c.id
AND (hidden=0 OR state=?1))
WHERE c.id>9 AND c.id!=?2
WHERE c.id>9
AND c.blocked=0
AND NOT c.archived=?3
AND NOT c.archived=?2
GROUP BY c.id
ORDER BY c.id=?4 DESC, c.archived=?5 DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
params![MessageState::OutDraft, skip_id, ChatVisibility::Archived, sort_id_up, ChatVisibility::Pinned],
ORDER BY c.archived=?3 DESC, IFNULL(m.timestamp,c.created_timestamp) DESC, m.id DESC;",
params![MessageState::OutDraft, ChatVisibility::Archived, ChatVisibility::Pinned],
process_row,
process_rows,
)?;
if 0 == listflags & DC_GCL_NO_SPECIALS {
if let Some(last_deaddrop_fresh_msg_id) = get_last_deaddrop_fresh_msg(context) {
if 0 == listflags & DC_GCL_FOR_FORWARDING {
ids.insert(
0,
(ChatId::new(DC_CHAT_ID_DEADDROP), last_deaddrop_fresh_msg_id),
);
}
ids.insert(
0,
(ChatId::new(DC_CHAT_ID_DEADDROP), last_deaddrop_fresh_msg_id),
);
}
add_archived_link_item = true;
}
@@ -429,25 +399,6 @@ mod tests {
assert_eq!(chats.len(), 1);
}
#[test]
fn test_sort_self_talk_up_on_forward() {
let t = dummy_context();
t.ctx.update_device_chats().unwrap();
create_group_chat(&t.ctx, VerifiedStatus::Unverified, "a chat").unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert!(chats.len() == 3);
assert!(!Chat::load_from_db(&t.ctx, chats.get_chat_id(0))
.unwrap()
.is_self_talk());
let chats = Chatlist::try_load(&t.ctx, DC_GCL_FOR_FORWARDING, None, None).unwrap();
assert!(chats.len() == 2); // device chat cannot be written and is skipped on forwarding
assert!(Chat::load_from_db(&t.ctx, chats.get_chat_id(0))
.unwrap()
.is_self_talk());
}
#[test]
fn test_search_special_chat_names() {
let t = dummy_context();
@@ -470,18 +421,4 @@ mod tests {
let chats = Chatlist::try_load(&t.ctx, 0, Some("t-5678-b"), None).unwrap();
assert_eq!(chats.len(), 1);
}
#[test]
fn test_get_summary_unwrap() {
let t = dummy_context();
let chat_id1 = create_group_chat(&t.ctx, VerifiedStatus::Unverified, "a chat").unwrap();
let mut msg = Message::new(Viewtype::Text);
msg.set_text(Some("foo:\nbar \r\n test".to_string()));
chat_id1.set_draft(&t.ctx, Some(&mut msg));
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
let summary = chats.get_summary(&t.ctx, 0, None);
assert_eq!(summary.get_text2().unwrap(), "foo: bar test"); // the linebreak should be removed from summary
}
}

View File

@@ -4,13 +4,10 @@ use strum::{EnumProperty, IntoEnumIterator};
use strum_macros::{AsRefStr, Display, EnumIter, EnumProperty, EnumString};
use crate::blob::BlobObject;
use crate::chat::ChatId;
use crate::constants::DC_VERSION_STR;
use crate::context::Context;
use crate::dc_tools::*;
use crate::events::Event;
use crate::job::*;
use crate::message::MsgId;
use crate::mimefactory::RECOMMENDED_FILE_SIZE;
use crate::stock::StockMessage;
use rusqlite::NO_PARAMS;
@@ -68,25 +65,6 @@ pub enum Config {
#[strum(props(default = "0"))]
KeyGenType,
/// Timer in seconds after which the message is deleted from the
/// server.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
///
/// Value 1 is treated as "delete at once": messages are deleted
/// immediately, without moving to DeltaChat folder.
#[strum(props(default = "0"))]
DeleteServerAfter,
/// Timer in seconds after which the message is deleted from the
/// device.
///
/// Equals to 0 by default, which means the message is never
/// deleted.
#[strum(props(default = "0"))]
DeleteDeviceAfter,
SaveMimeHeaders,
ConfiguredAddr,
ConfiguredMailServer,
@@ -150,29 +128,6 @@ impl Context {
self.get_config_int(key) != 0
}
/// Gets configured "delete_server_after" value.
///
/// `None` means never delete the message, `Some(0)` means delete
/// at once, `Some(x)` means delete after `x` seconds.
pub fn get_config_delete_server_after(&self) -> Option<i64> {
match self.get_config_int(Config::DeleteServerAfter) {
0 => None,
1 => Some(0),
x => Some(x as i64),
}
}
/// Gets configured "delete_device_after" value.
///
/// `None` means never delete the message, `Some(x)` means delete
/// after `x` seconds.
pub fn get_config_delete_device_after(&self) -> Option<i64> {
match self.get_config_int(Config::DeleteDeviceAfter) {
0 => None,
x => Some(x as i64),
}
}
/// Set the given config key.
/// If `None` is passed as a value the value is cleared and set to the default if there is one.
pub fn set_config(&self, key: Config, value: Option<&str>) -> crate::sql::Result<()> {
@@ -216,15 +171,6 @@ impl Context {
self.sql.set_raw_config(self, key, val)
}
Config::DeleteDeviceAfter => {
let ret = self.sql.set_raw_config(self, key, value);
// Force chatlist reload to delete old messages immediately.
self.call_cb(Event::MsgsChanged {
msg_id: MsgId::new(0),
chat_id: ChatId::new(0),
});
ret
}
_ => self.sql.set_raw_config(self, key, value),
}
}

View File

@@ -371,7 +371,7 @@ pub(crate) fn JobConfigureImap(context: &Context) -> job::Status {
let create_mvbox = context.get_config_bool(Config::MvboxWatch)
|| context.get_config_bool(Config::MvboxMove);
let imap = &context.inbox_thread.read().unwrap().imap;
if let Err(err) = imap.configure_folders(context, create_mvbox) {
if let Err(err) = imap.ensure_configured_folders(context, create_mvbox) {
warn!(context, "configuring folders failed: {:?}", err);
false
} else {

View File

@@ -80,7 +80,6 @@ pub(crate) const DC_FROM_HANDSHAKE: i32 = 0x01;
pub const DC_GCL_ARCHIVED_ONLY: usize = 0x01;
pub const DC_GCL_NO_SPECIALS: usize = 0x02;
pub const DC_GCL_ADD_ALLDONE_HINT: usize = 0x04;
pub const DC_GCL_FOR_FORWARDING: usize = 0x08;
pub const DC_GCM_ADDDAYMARKER: u32 = 0x01;
@@ -214,9 +213,6 @@ pub const DC_BOB_SUCCESS: i32 = 1;
// max. width/height of an avatar
pub const AVATAR_SIZE: u32 = 192;
// this value can be increased if the folder configuration is changed and must be redone on next program start
pub const DC_FOLDERS_CONFIGURED_VERSION: i32 = 3;
#[derive(
Debug,
Display,

View File

@@ -118,7 +118,7 @@ pub enum Origin {
Internal = 0x40000,
/// address is in our address book
AddressBook = 0x80000,
AdressBook = 0x80000,
/// set on Alice's side for contacts like Bob that have scanned the QR code offered by her. Only means the contact has once been established using the "securejoin" procedure in the past, getting the current key verification status requires calling dc_contact_is_verified() !
SecurejoinInvited = 0x0100_0000,
@@ -497,18 +497,9 @@ impl Contact {
for (name, addr) in split_address_book(addr_book.as_ref()).into_iter() {
let name = normalize_name(name);
match Contact::add_or_lookup(context, name, addr, Origin::AddressBook) {
Err(err) => {
warn!(
context,
"Failed to add address {} from address book: {}", addr, err
);
}
Ok((_, modified)) => {
if modified != Modifier::None {
modify_cnt += 1
}
}
let (_, modified) = Contact::add_or_lookup(context, name, addr, Origin::AdressBook)?;
if modified != Modifier::None {
modify_cnt += 1
}
}
if modify_cnt > 0 {
@@ -1067,7 +1058,7 @@ pub fn normalize_name(full_name: impl AsRef<str>) -> String {
}
let len = full_name.len();
if len > 1 {
if len > 0 {
let firstchar = full_name.as_bytes()[0];
let lastchar = full_name.as_bytes()[len - 1];
if firstchar == b'\'' && lastchar == b'\''
@@ -1176,10 +1167,6 @@ mod tests {
fn test_normalize_name() {
assert_eq!(&normalize_name("Doe, John"), "John Doe");
assert_eq!(&normalize_name(" hello world "), "hello world");
assert_eq!(&normalize_name("<"), "<");
assert_eq!(&normalize_name(">"), ">");
assert_eq!(&normalize_name("'"), "'");
assert_eq!(&normalize_name("\""), "\"");
}
#[test]
@@ -1242,7 +1229,6 @@ mod tests {
let book = concat!(
" Name one \n one@eins.org \n",
"Name two\ntwo@deux.net\n",
"Invalid\n+1234567890\n", // invalid, should be ignored
"\nthree@drei.sam\n",
"Name two\ntwo@deux.net\n" // should not be added again
);

View File

@@ -17,7 +17,7 @@ use crate::message::{self, MessageState, MessengerMessage, MsgId};
use crate::mimeparser::*;
use crate::param::*;
use crate::peerstate::*;
use crate::securejoin::{self, handle_securejoin_handshake, observe_securejoin_on_other_device};
use crate::securejoin::{self, handle_securejoin_handshake};
use crate::sql;
use crate::stock::StockMessage;
use crate::{contact, location};
@@ -192,24 +192,17 @@ pub fn dc_receive_imf(
};
}
// Get user-configured server deletion
let delete_server_after = context.get_config_delete_server_after();
if !created_db_entries.is_empty() {
if needs_delete_job || delete_server_after == Some(0) {
for db_entry in &created_db_entries {
job_add(
context,
Action::DeleteMsgOnImap,
db_entry.1.to_u32() as i32,
Params::new(),
0,
);
}
} else {
// Move message if we don't delete it immediately.
context.do_heuristics_moves(server_folder.as_ref(), insert_msg_id);
}
// if we delete we don't need to try moving messages
if needs_delete_job && !created_db_entries.is_empty() {
job_add(
context,
Action::DeleteMsgOnImap,
created_db_entries[0].1.to_u32() as i32,
Params::new(),
0,
);
} else {
context.do_heuristics_moves(server_folder.as_ref(), insert_msg_id);
}
info!(
@@ -219,7 +212,7 @@ pub fn dc_receive_imf(
cleanup(context, &create_event_to_send, created_db_entries);
mime_parser.handle_reports(context, from_id, sent_timestamp);
mime_parser.handle_reports(context, from_id, sent_timestamp, &server_folder, server_uid);
Ok(())
}
@@ -347,9 +340,11 @@ fn add_parts(
};
to_id = DC_CONTACT_ID_SELF;
// handshake may mark contacts as verified and must be processed before chats are created
// handshake messages must be processed _before_ chats are created
// (eg. contacs may be marked as verified)
if mime_parser.get(HeaderDef::SecureJoin).is_some() {
msgrmsg = MessengerMessage::Yes; // avoid discarding by show_emails setting
// avoid discarding by show_emails setting
msgrmsg = MessengerMessage::Yes;
*chat_id = ChatId::new(0);
allow_creation = true;
match handle_securejoin_handshake(context, mime_parser, from_id) {
@@ -363,7 +358,8 @@ fn add_parts(
state = MessageState::InSeen;
}
Ok(securejoin::HandshakeMessage::Propagate) => {
// process messages as "member added" normally
// Message will still be processed as "member
// added" or similar system message.
}
Err(err) => {
*hidden = true;
@@ -393,11 +389,7 @@ fn add_parts(
let (new_chat_id, new_chat_id_blocked) = create_or_lookup_group(
context,
&mut mime_parser,
if test_normal_chat_id.is_unset() {
allow_creation
} else {
true
},
allow_creation,
create_blocked,
from_id,
to_ids,
@@ -480,27 +472,6 @@ fn add_parts(
// We cannot recreate other states (read, error).
state = MessageState::OutDelivered;
to_id = to_ids.get_index(0).cloned().unwrap_or_default();
// handshake may mark contacts as verified and must be processed before chats are created
if mime_parser.get(HeaderDef::SecureJoin).is_some() {
msgrmsg = MessengerMessage::Yes; // avoid discarding by show_emails setting
*chat_id = ChatId::new(0);
allow_creation = true;
match observe_securejoin_on_other_device(context, mime_parser, to_id) {
Ok(securejoin::HandshakeMessage::Done)
| Ok(securejoin::HandshakeMessage::Ignore) => {
*hidden = true;
}
Ok(securejoin::HandshakeMessage::Propagate) => {
// process messages as "member added" normally
}
Err(err) => {
*hidden = true;
error!(context, "Error in Secure-Join watching: {}", err);
}
}
}
if !to_ids.is_empty() {
if chat_id.is_unset() {
let (new_chat_id, new_chat_id_blocked) = create_or_lookup_group(
@@ -608,13 +579,10 @@ fn add_parts(
let subject = mime_parser.get_subject().unwrap_or_default();
for part in mime_parser.parts.iter_mut() {
let is_mdn = !mime_parser.reports.is_empty();
let is_location_kml = mime_parser.location_kml.is_some()
if mime_parser.location_kml.is_some()
&& icnt == 1
&& (part.msg == "-location-" || part.msg.is_empty());
if is_mdn || is_location_kml {
&& (part.msg == "-location-" || part.msg.is_empty())
{
*hidden = true;
if state == MessageState::InFresh {
state = MessageState::InNoticed;
@@ -1055,17 +1023,6 @@ fn create_or_lookup_group(
// add members to group/check members
if recreate_member_list {
if !chat::is_contact_in_chat(context, chat_id, DC_CONTACT_ID_SELF) {
// Members could have been removed while we were
// absent. We can't use existing member list and need to
// start from scratch.
sql::execute(
context,
&context.sql,
"DELETE FROM chats_contacts WHERE chat_id=?;",
params![chat_id],
)
.ok();
chat::add_to_chat_contacts_table(context, chat_id, DC_CONTACT_ID_SELF);
}
if from_id > DC_CONTACT_ID_LAST_SPECIAL
@@ -1507,7 +1464,7 @@ fn is_known_rfc724_mid_in_list(context: &Context, mid_list: &str) -> bool {
return false;
}
if let Ok(ids) = mailparse::msgidparse(mid_list) {
if let Ok(ids) = mailparse::addrparse(mid_list) {
for id in ids.iter() {
if is_known_rfc724_mid(context, id) {
return true;
@@ -1519,8 +1476,8 @@ fn is_known_rfc724_mid_in_list(context: &Context, mid_list: &str) -> bool {
}
/// Check if a message is a reply to a known message (messenger or non-messenger).
fn is_known_rfc724_mid(context: &Context, rfc724_mid: &str) -> bool {
let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
fn is_known_rfc724_mid(context: &Context, rfc724_mid: &mailparse::MailAddr) -> bool {
let addr = extract_single_from_addr(rfc724_mid);
context
.sql
.exists(
@@ -1528,7 +1485,7 @@ fn is_known_rfc724_mid(context: &Context, rfc724_mid: &str) -> bool {
LEFT JOIN chats c ON m.chat_id=c.id \
WHERE m.rfc724_mid=? \
AND m.chat_id>9 AND c.blocked=0;",
params![rfc724_mid],
params![addr],
)
.unwrap_or_default()
}
@@ -1555,7 +1512,7 @@ fn is_reply_to_messenger_message(context: &Context, mime_parser: &MimeMessage) -
}
pub(crate) fn is_msgrmsg_rfc724_mid_in_list(context: &Context, mid_list: &str) -> bool {
if let Ok(ids) = mailparse::msgidparse(mid_list) {
if let Ok(ids) = mailparse::addrparse(mid_list) {
for id in ids.iter() {
if is_msgrmsg_rfc724_mid(context, id) {
return true;
@@ -1565,14 +1522,21 @@ pub(crate) fn is_msgrmsg_rfc724_mid_in_list(context: &Context, mid_list: &str) -
false
}
fn extract_single_from_addr(addr: &mailparse::MailAddr) -> &String {
match addr {
mailparse::MailAddr::Group(infos) => &infos.addrs[0].addr,
mailparse::MailAddr::Single(info) => &info.addr,
}
}
/// Check if a message is a reply to any messenger message.
fn is_msgrmsg_rfc724_mid(context: &Context, rfc724_mid: &str) -> bool {
let rfc724_mid = rfc724_mid.trim_start_matches('<').trim_end_matches('>');
fn is_msgrmsg_rfc724_mid(context: &Context, rfc724_mid: &mailparse::MailAddr) -> bool {
let addr = extract_single_from_addr(rfc724_mid);
context
.sql
.exists(
"SELECT id FROM msgs WHERE rfc724_mid=? AND msgrmsg!=0 AND chat_id>9;",
params![rfc724_mid],
params![addr],
)
.unwrap_or_default()
}
@@ -1657,9 +1621,7 @@ fn dc_create_incoming_rfc724_mid(
#[cfg(test)]
mod tests {
use super::*;
use crate::chatlist::Chatlist;
use crate::message::Message;
use crate::test_utils::{dummy_context, TestContext};
use crate::test_utils::dummy_context;
#[test]
fn test_hex_hash() {
@@ -1718,170 +1680,4 @@ mod tests {
Some("123-45-9@stub".into())
);
}
#[test]
fn test_is_known_rfc724_mid() {
let t = dummy_context();
let mut msg = Message::new(Viewtype::Text);
msg.text = Some("first message".to_string());
let msg_id = chat::add_device_msg(&t.ctx, None, Some(&mut msg)).unwrap();
let msg = Message::load_from_db(&t.ctx, msg_id).unwrap();
// Message-IDs may or may not be surrounded by angle brackets
assert!(is_known_rfc724_mid(
&t.ctx,
format!("<{}>", msg.rfc724_mid).as_str()
));
assert!(is_known_rfc724_mid(&t.ctx, &msg.rfc724_mid));
assert!(!is_known_rfc724_mid(&t.ctx, "nonexistant@message.id"));
}
#[test]
fn test_is_msgrmsg_rfc724_mid() {
let t = dummy_context();
let mut msg = Message::new(Viewtype::Text);
msg.text = Some("first message".to_string());
let msg_id = chat::add_device_msg(&t.ctx, None, Some(&mut msg)).unwrap();
let msg = Message::load_from_db(&t.ctx, msg_id).unwrap();
// Message-IDs may or may not be surrounded by angle brackets
assert!(is_msgrmsg_rfc724_mid(
&t.ctx,
format!("<{}>", msg.rfc724_mid).as_str()
));
assert!(is_msgrmsg_rfc724_mid(&t.ctx, &msg.rfc724_mid));
assert!(!is_msgrmsg_rfc724_mid(&t.ctx, "nonexistant@message.id"));
}
fn configured_offline_context() -> TestContext {
let t = dummy_context();
t.ctx
.set_config(Config::Addr, Some("alice@example.org"))
.unwrap();
t.ctx
.set_config(Config::ConfiguredAddr, Some("alice@example.org"))
.unwrap();
t.ctx.set_config(Config::Configured, Some("1")).unwrap();
t
}
static MSGRMSG: &[u8] = b"From: Bob <bob@example.org>\n\
To: alice@example.org\n\
Chat-Version: 1.0\n\
Subject: Chat: hello\n\
Message-ID: <Mr.1111@example.org>\n\
Date: Sun, 22 Mar 2020 22:37:55 +0000\n\
\n\
hello\n";
static ONETOONE_NOREPLY_MAIL: &[u8] = b"From: Bob <bob@example.org>\n\
To: alice@example.org\n\
Subject: Chat: hello\n\
Message-ID: <2222@example.org>\n\
Date: Sun, 22 Mar 2020 22:37:56 +0000\n\
\n\
hello\n";
static GRP_MAIL: &[u8] = b"From: bob@example.org\n\
To: alice@example.org, claire@example.org\n\
Subject: group with Alice, Bob and Claire\n\
Message-ID: <3333@example.org>\n\
Date: Sun, 22 Mar 2020 22:37:57 +0000\n\
\n\
hello\n";
#[test]
fn test_adhoc_group_show_chats_only() {
let t = configured_offline_context();
assert_eq!(t.ctx.get_config_int(Config::ShowEmails), 0);
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 0);
dc_receive_imf(&t.ctx, MSGRMSG, "INBOX", 1, false).unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 1);
dc_receive_imf(&t.ctx, ONETOONE_NOREPLY_MAIL, "INBOX", 1, false).unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 1);
dc_receive_imf(&t.ctx, GRP_MAIL, "INBOX", 1, false).unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 1);
}
#[test]
fn test_adhoc_group_show_accepted_contact_unknown() {
let t = configured_offline_context();
t.ctx.set_config(Config::ShowEmails, Some("1")).unwrap();
dc_receive_imf(&t.ctx, GRP_MAIL, "INBOX", 1, false).unwrap();
// adhoc-group with unknown contacts with show_emails=accepted is ignored for unknown contacts
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 0);
}
#[test]
fn test_adhoc_group_show_accepted_contact_known() {
let t = configured_offline_context();
t.ctx.set_config(Config::ShowEmails, Some("1")).unwrap();
Contact::create(&t.ctx, "Bob", "bob@example.org").unwrap();
dc_receive_imf(&t.ctx, GRP_MAIL, "INBOX", 1, false).unwrap();
// adhoc-group with known contacts with show_emails=accepted is still ignored for known contacts
// (and existent chat is required)
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 0);
}
#[test]
fn test_adhoc_group_show_accepted_contact_accepted() {
let t = configured_offline_context();
t.ctx.set_config(Config::ShowEmails, Some("1")).unwrap();
// accept Bob by accepting a delta-message from Bob
dc_receive_imf(&t.ctx, MSGRMSG, "INBOX", 1, false).unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 1);
assert!(chats.get_chat_id(0).is_deaddrop());
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap()).unwrap();
assert!(!chat_id.is_special());
let chat = chat::Chat::load_from_db(&t.ctx, chat_id).unwrap();
assert_eq!(chat.typ, Chattype::Single);
assert_eq!(chat.name, "Bob");
assert_eq!(chat::get_chat_contacts(&t.ctx, chat_id).len(), 1);
assert_eq!(chat::get_chat_msgs(&t.ctx, chat_id, 0, None).len(), 1);
// receive a non-delta-message from Bob, shows up because of the show_emails setting
dc_receive_imf(&t.ctx, ONETOONE_NOREPLY_MAIL, "INBOX", 2, false).unwrap();
assert_eq!(chat::get_chat_msgs(&t.ctx, chat_id, 0, None).len(), 2);
// let Bob create an adhoc-group by a non-delta-message, shows up because of the show_emails setting
dc_receive_imf(&t.ctx, GRP_MAIL, "INBOX", 3, false).unwrap();
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 2);
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap()).unwrap();
let chat = chat::Chat::load_from_db(&t.ctx, chat_id).unwrap();
assert_eq!(chat.typ, Chattype::Group);
assert_eq!(chat.name, "group with Alice, Bob and Claire");
assert_eq!(chat::get_chat_contacts(&t.ctx, chat_id).len(), 3);
}
#[test]
fn test_adhoc_group_show_all() {
let t = configured_offline_context();
t.ctx.set_config(Config::ShowEmails, Some("2")).unwrap();
dc_receive_imf(&t.ctx, GRP_MAIL, "INBOX", 1, false).unwrap();
// adhoc-group with unknown contacts with show_emails=all will show up in the deaddrop
let chats = Chatlist::try_load(&t.ctx, 0, None, None).unwrap();
assert_eq!(chats.len(), 1);
assert!(chats.get_chat_id(0).is_deaddrop());
let chat_id = chat::create_by_msg_id(&t.ctx, chats.get_msg_id(0).unwrap()).unwrap();
let chat = chat::Chat::load_from_db(&t.ctx, chat_id).unwrap();
assert_eq!(chat.typ, Chattype::Group);
assert_eq!(chat.name, "group with Alice, Bob and Claire");
assert_eq!(chat::get_chat_contacts(&t.ctx, chat_id).len(), 3);
}
}

View File

@@ -19,10 +19,10 @@ pub(crate) fn dc_exactly_one_bit_set(v: i32) -> bool {
0 != v && 0 == v & (v - 1)
}
/// Shortens a string to a specified length and adds "[...]" to the
/// end of the shortened string.
pub(crate) fn dc_truncate(buf: &str, approx_chars: usize) -> Cow<str> {
let ellipse = "[...]";
/// Shortens a string to a specified length and adds "..." or "[...]" to the end of
/// the shortened string.
pub(crate) fn dc_truncate(buf: &str, approx_chars: usize, do_unwrap: bool) -> Cow<str> {
let ellipse = if do_unwrap { "..." } else { "[...]" };
let count = buf.chars().count();
if approx_chars > 0 && count > approx_chars + ellipse.len() {
@@ -538,42 +538,54 @@ mod tests {
#[test]
fn test_dc_truncate_1() {
let s = "this is a little test string";
assert_eq!(dc_truncate(s, 16), "this is a [...]");
assert_eq!(dc_truncate(s, 16, false), "this is a [...]");
assert_eq!(dc_truncate(s, 16, true), "this is a ...");
}
#[test]
fn test_dc_truncate_2() {
assert_eq!(dc_truncate("1234", 2), "1234");
assert_eq!(dc_truncate("1234", 2, false), "1234");
assert_eq!(dc_truncate("1234", 2, true), "1234");
}
#[test]
fn test_dc_truncate_3() {
assert_eq!(dc_truncate("1234567", 1), "1[...]");
assert_eq!(dc_truncate("1234567", 1, false), "1[...]");
assert_eq!(dc_truncate("1234567", 1, true), "1...");
}
#[test]
fn test_dc_truncate_4() {
assert_eq!(dc_truncate("123456", 4), "123456");
assert_eq!(dc_truncate("123456", 4, false), "123456");
assert_eq!(dc_truncate("123456", 4, true), "123456");
}
#[test]
fn test_dc_truncate_edge() {
assert_eq!(dc_truncate("", 4), "");
assert_eq!(dc_truncate("", 4, false), "");
assert_eq!(dc_truncate("", 4, true), "");
assert_eq!(dc_truncate("\n hello \n world", 4), "\n [...]");
assert_eq!(dc_truncate("\n hello \n world", 4, false), "\n [...]");
assert_eq!(dc_truncate("\n hello \n world", 4, true), "\n ...");
assert_eq!(dc_truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 1), "𐠈[...]");
assert_eq!(
dc_truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 0),
dc_truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 1, false),
"𐠈[...]"
);
assert_eq!(
dc_truncate("𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ", 0, false),
"𐠈0Aᝮa𫝀®!ꫛa¡0A𐢧00𐹠®A 丽ⷐએ"
);
// 9 characters, so no truncation
assert_eq!(dc_truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠", 6), "𑒀ὐ¢🜀\u{1e01b}A a🟠",);
assert_eq!(
dc_truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠", 6, false),
"𑒀ὐ¢🜀\u{1e01b}A a🟠",
);
// 12 characters, truncation
assert_eq!(
dc_truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠bcd", 6),
dc_truncate("𑒀ὐ¢🜀\u{1e01b}A a🟠bcd", 6, false),
"𑒀ὐ¢🜀\u{1e01b}A[...]",
);
}
@@ -689,10 +701,11 @@ mod tests {
#[test]
fn test_dc_truncate(
buf: String,
approx_chars in 0..10000usize
approx_chars in 0..10000usize,
do_unwrap: bool,
) {
let res = dc_truncate(&buf, approx_chars);
let el_len = 5;
let res = dc_truncate(&buf, approx_chars, do_unwrap);
let el_len = if do_unwrap { 3 } else { 5 };
let l = res.chars().count();
if approx_chars > 0 {
assert!(
@@ -706,7 +719,11 @@ mod tests {
if approx_chars > 0 && buf.chars().count() > approx_chars + el_len {
let l = res.len();
assert_eq!(&res[l-5..l], "[...]", "missing ellipsis in {}", &res);
if do_unwrap {
assert_eq!(&res[l-3..l], "...", "missing ellipsis in {}", &res);
} else {
assert_eq!(&res[l-5..l], "[...]", "missing ellipsis in {}", &res);
}
}
}
}

View File

@@ -126,7 +126,7 @@ pub fn try_decrypt(
) -> Result<(Option<Vec<u8>>, HashSet<String>)> {
let from = mail
.headers
.get_header_value(HeaderDef::From_)
.get_header_value(HeaderDef::From_)?
.and_then(|from_addr| mailparse::addrparse(&from_addr).ok())
.and_then(|from| from.extract_single_info())
.map(|from| from.addr)
@@ -417,6 +417,7 @@ Sent with my Delta Chat Messenger: https://delta.chat";
}
#[test]
#[ignore] // generating keys is expensive
fn test_generate() {
let t = dummy_context();
let addr = "alice@example.org";
@@ -428,6 +429,7 @@ Sent with my Delta Chat Messenger: https://delta.chat";
}
#[test]
#[ignore]
fn test_generate_concurrent() {
use std::sync::Arc;
use std::thread;

View File

@@ -1,345 +0,0 @@
// use crate::dc_tools::*;
use crate::chat::*;
use crate::constants::{Viewtype, DC_CONTACT_ID_SELF};
use crate::contact::*;
use crate::context::Context;
use crate::error::Error;
use crate::message::*;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use zip::write::FileOptions;
#[derive(Debug)]
pub struct ExportChatResult {
html: String,
referenced_blobs: Vec<String>,
}
struct ContactInfo {
name: String,
initial: String,
color: String,
profile_img: Option<String>,
}
pub fn pack_exported_chat(
context: &Context,
artifact: ExportChatResult,
filename: &str,
) -> zip::result::ZipResult<()> {
let path = std::path::Path::new(filename);
let file = std::fs::File::create(&path).unwrap();
let mut zip = zip::ZipWriter::new(file);
zip.start_file("index.html", Default::default())?;
zip.write_all(artifact.html.as_bytes())?;
zip.start_file("styles.css", Default::default())?;
zip.write_all(include_bytes!("../assets/exported-chat.css"))?;
zip.add_directory("blobs/", Default::default())?;
let options = FileOptions::default();
for blob_name in artifact.referenced_blobs {
let path = context.get_blobdir().join(&blob_name);
// println!("adding file {:?} as {:?} ...", path, &blob_name);
zip.start_file_from_path(Path::new(&format!("blobs/{}", &blob_name)), options)?;
let mut f = File::open(path)?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
zip.write_all(&*buffer)?;
buffer.clear();
}
zip.finish()?;
Ok(())
}
pub fn export_chat(context: &Context, chat_id: ChatId) -> ExportChatResult {
let mut blobs = Vec::new();
let mut chat_author_ids = Vec::new();
// get all messages
let messages: Vec<std::result::Result<Message, Error>> =
get_chat_msgs(context, chat_id, 0, None)
.into_iter()
.map(|msg_id| Message::load_from_db(context, msg_id))
.collect();
// push all referenced blobs and populate contactid list
for message in &messages {
if let Ok(msg) = &message {
let filename = msg.get_filename();
if let Some(file) = filename {
// push referenced blobs (attachments)
blobs.push(file);
}
chat_author_ids.push(msg.from_id);
}
}
// deduplicate contact list and load the contacts
chat_author_ids.dedup();
// chache information about the authors
let mut chat_authors: HashMap<u32, ContactInfo> = HashMap::new();
chat_authors.insert(
0,
ContactInfo {
name: "Err: Contact not found".to_owned(),
initial: "#".to_owned(),
profile_img: None,
color: "grey".to_owned(),
},
);
for author_id in chat_author_ids {
let contact = Contact::get_by_id(context, author_id);
if let Ok(c) = contact {
let profile_img_path: String;
if let Some(path) = c.get_profile_image(context) {
profile_img_path = path
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new(""))
.to_str()
.unwrap()
.to_owned();
// push referenced blobs (avatars)
blobs.push(profile_img_path.clone());
} else {
profile_img_path = "".to_owned();
}
chat_authors.insert(
author_id,
ContactInfo {
name: c.get_display_name().to_owned(),
initial: "#".to_owned(), // TODO
profile_img: match profile_img_path != "" {
true => Some(profile_img_path),
false => None,
},
color: "rgb(18, 126, 208)".to_owned(), // TODO
},
);
}
}
// run message_to_html for each message and generate the html that way
let mut html_messages: Vec<String> = Vec::new();
for message in messages {
if let Ok(msg) = message {
html_messages.push(message_to_html(&chat_authors, msg, context));
} else {
html_messages.push(format!(
r#"<li>
<div class='message error'>
<div class="msg-container">
<div class="msg-body">
<div dir="auto" class="text">{:?}</div>
</div>
</div>
</div>
</li>"#,
message.unwrap_err()
));
}
}
// todo chat image, chat name and so on..
let chat = Chat::load_from_db(context, chat_id).unwrap();
let chat_avatar = match chat.get_profile_image(context) {
Some(img) => {
let path = img
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new(""))
.to_str()
.unwrap()
.to_owned();
blobs.push(path.clone());
format!("<img class=\"avatar\" src=\"blobs/{}\" />", path)
}
None => format!(
"<div class=\"avatar text-avatar\" style=\"background-color:#{:#}\">{}</div>",
chat.get_color(context),
chat.get_name().chars().next().unwrap()
),
};
// todo option to export locations as kml?
// todo export message infos and save them to txt files
// (those can be linked from the messages, they are stored in msg_info/[msg-id].txt)
blobs.dedup();
ExportChatResult {
html: format!(
"<html>\
<head>\
<title>{chat_name}</title>\
<link rel=\"stylesheet\" href=\"styles.css\" type=\"text/css\">\
</head>\
<body>\
<div class=\"header\">\
{chat_avatar}\
<div class=\"name\">{chat_name}</div>\
</div>\
<div class=\"message-list-and-composer__message-list\">\
<div id=\"message-list\">\
<ul>{messages}</ul>\
</div>\
</div>\
</body>\
</html>",
chat_name = chat.get_name(),
chat_avatar = chat_avatar,
messages = html_messages.join("")
),
referenced_blobs: blobs,
}
}
fn message_to_html(
author_cache: &HashMap<u32, ContactInfo>,
message: Message,
context: &Context,
) -> String {
let author: &ContactInfo = {
if let Some(c) = author_cache.get(&message.get_from_id()) {
c
} else {
author_cache.get(&0).unwrap()
}
};
let avatar: String = {
if let Some(profile_img) = &author.profile_img {
format!(
"<div class=\"author-avatar\">\
<img \
alt=\"{author_name}\"\
src=\"blobs/{author_avatar_src}\"\
/>\
</div>",
author_name = author.name,
author_avatar_src = profile_img
)
} else {
format!(
"<div class=\"author-avatar default\" alt=\"{name}\">\
<div class=\"label\" style=\"background-color: {color}\">\
{initial}\
</div>\
</div>",
name = author.name,
initial = author.initial,
color = author.color
)
}
};
// save and refernce message source code somehow?
let has_text = message.get_text().is_some() && !message.get_text().unwrap().is_empty();
let attachment = match message.get_file(context) {
None => "".to_owned(),
Some(file) => {
let modifier_class = if has_text { "content-below" } else { "" };
let filename = file
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new(""))
.to_str()
.unwrap()
.to_owned();
match message.get_viewtype() {
Viewtype::Audio => {
format!("<audio \
controls \
class=\"message-attachment-audio {}\"> \
<source src=\"blobs/{}\" /> \
</audio>", modifier_class ,filename)
},
Viewtype::Gif | Viewtype::Image | Viewtype::Sticker => {
format!("<a \
href=\"blobs/{filename}\" \
role=\"button\" \
class=\"message-attachment-media {modifier_class}\"> \
<img className='attachment-content' src=\"blobs/{filename}\" /> \
</a>", modifier_class=modifier_class, filename=filename)
},
Viewtype::Video => {
format!("<a \
href=\"blobs/{filename}\" \
role=\"button\" \
class=\"message-attachment-media {modifier_class}\"> \
<video className='attachment-content' src=\"blobs/{filename}\" controls=\"true\" /> \
</a>", modifier_class=modifier_class, filename=filename)
},
_ => {
format!("<div class=\"message-attachment-generic {modifier_class}\">\
<div class=\"file-icon\">\
<div class=\"file-extension\">\
{extension} \
</div>\
</div>\
<div className=\"text-part\">\
<a href=\"blobs/{filename}\" className=\"name\">{filename}</a>\
<div className=\"size\">{filesize}</div>\
</div>\
</div>",
modifier_class=modifier_class,
filename=filename,
filesize=message.get_filebytes(&context) /* todo human readable file size*/,
extension=file.extension().unwrap_or_else(|| std::ffi::OsStr::new("")).to_str().unwrap().to_owned())
}
}
}
};
format!(
"<li>\
<div class=\"message {direction}\">\
{avatar}\
<div class=\"msg-container\">\
<span class=\"author\" style=\"color: {author_color};\">{author_name}</span>\
<div class=\"msg-body\">\
{attachment}
<div dir=\"auto\" class=\"text\">\
{content}\
</div>\
<div class=\"metadata {with_image_no_caption}\">\
{encryption}\
<span class=\"date date--{direction}\" title=\"{full_time}\">{relative_time}</span>\
<span class=\"spacer\"></span>\
</div>\
</div>\
</div>\
<div>\
</li>",
direction = match message.from_id == DC_CONTACT_ID_SELF {
true => "outgoing",
false => "incoming",
},
avatar = avatar,
author_name = author.name,
author_color = author.color,
attachment = attachment,
content = message.get_text().unwrap_or_else(|| "".to_owned()),
with_image_no_caption = if !has_text && message.get_viewtype() == Viewtype::Image {
"with-image-no-caption"
} else {
""
},
encryption = match message.get_showpadlock() {
true => r#"<div aria-label="Encryption padlock" class="padlock-icon"></div>"#,
false => "",
},
full_time = "Tue, Feb 25, 2020 3:49 PM", // message.get_timestamp() ? // todo
relative_time = "Tue 3:49 PM" // todo
)
// todo link to raw message data
// todo link to message info
}
//TODO tests

View File

@@ -1,5 +1,5 @@
use crate::strum::AsStaticRef;
use mailparse::{MailHeader, MailHeaderMap};
use mailparse::{MailHeader, MailHeaderMap, MailParseError};
#[derive(Debug, Display, Clone, PartialEq, Eq, EnumVariantNames, AsStaticStr)]
#[strum(serialize_all = "kebab_case")]
@@ -52,11 +52,11 @@ impl HeaderDef {
}
pub trait HeaderDefMap {
fn get_header_value(&self, headerdef: HeaderDef) -> Option<String>;
fn get_header_value(&self, headerdef: HeaderDef) -> Result<Option<String>, MailParseError>;
}
impl HeaderDefMap for [MailHeader<'_>] {
fn get_header_value(&self, headerdef: HeaderDef) -> Option<String> {
fn get_header_value(&self, headerdef: HeaderDef) -> Result<Option<String>, MailParseError> {
self.get_first_value(headerdef.get_headername())
}
}
@@ -79,13 +79,18 @@ mod tests {
let (headers, _) =
mailparse::parse_headers(b"fRoM: Bob\naUtoCryPt-SeTup-MessAge: v99").unwrap();
assert_eq!(
headers.get_header_value(HeaderDef::AutocryptSetupMessage),
headers
.get_header_value(HeaderDef::AutocryptSetupMessage)
.unwrap(),
Some("v99".to_string())
);
assert_eq!(
headers.get_header_value(HeaderDef::From_),
headers.get_header_value(HeaderDef::From_).unwrap(),
Some("Bob".to_string())
);
assert_eq!(headers.get_header_value(HeaderDef::Autocrypt), None);
assert_eq!(
headers.get_header_value(HeaderDef::Autocrypt).unwrap(),
None
);
}
}

View File

@@ -188,6 +188,7 @@ struct ImapConfig {
/// True if the server has MOVE capability as defined in
/// https://tools.ietf.org/html/rfc6851
pub can_move: bool,
pub imap_delimiter: char,
}
impl Default for ImapConfig {
@@ -205,6 +206,7 @@ impl Default for ImapConfig {
selected_folder_needs_expunge: false,
can_idle: false,
can_move: false,
imap_delimiter: '.',
}
}
}
@@ -794,6 +796,7 @@ impl Imap {
folder: &str,
uid: u32,
dest_folder: &str,
dest_uid: &mut u32,
) -> ImapActionResult {
task::block_on(async move {
if folder == dest_folder {
@@ -810,6 +813,10 @@ impl Imap {
return imapresult;
}
// we are connected, and the folder is selected
// XXX Rust-Imap provides no target uid on mv, so just set it to 0
*dest_uid = 0;
let set = format!("{}", uid);
let display_folder_id = format!("{}/{}", folder, uid);
@@ -989,10 +996,10 @@ impl Imap {
context: &Context,
message_id: &str,
folder: &str,
uid: u32,
uid: &mut u32,
) -> ImapActionResult {
task::block_on(async move {
if let Some(imapresult) = self.prepare_imap_operation_on_msg(context, folder, uid) {
if let Some(imapresult) = self.prepare_imap_operation_on_msg(context, folder, *uid) {
return imapresult;
}
// we are connected, and the folder is selected
@@ -1014,7 +1021,7 @@ impl Imap {
display_imap_id,
message_id,
);
return ImapActionResult::AlreadyDone;
return ImapActionResult::Failed;
};
let remote_message_id = get_fetch_headers(fetch)
@@ -1029,7 +1036,7 @@ impl Imap {
remote_message_id,
message_id,
);
return ImapActionResult::Failed;
*uid = 0;
}
}
Err(err) => {
@@ -1037,18 +1044,18 @@ impl Imap {
context,
"Cannot delete {} on IMAP: {}", display_imap_id, err
);
return ImapActionResult::RetryLater;
*uid = 0;
}
}
}
// mark the message for deletion
if !self.add_flag_finalized(context, uid, "\\Deleted").await {
if !self.add_flag_finalized(context, *uid, "\\Deleted").await {
warn!(
context,
"Cannot mark message {} as \"Deleted\".", display_imap_id
);
ImapActionResult::RetryLater
ImapActionResult::Failed
} else {
emit_event!(
context,
@@ -1067,14 +1074,12 @@ impl Imap {
let folders_configured = context
.sql
.get_raw_config_int(context, "folders_configured");
if folders_configured.unwrap_or_default() >= DC_FOLDERS_CONFIGURED_VERSION {
if folders_configured.unwrap_or_default() >= 3 {
// the "3" here we increase if we have future updates to
// to folder configuration
return Ok(());
}
self.configure_folders(context, create_mvbox)
}
pub fn configure_folders(&self, context: &Context, create_mvbox: bool) -> Result<()> {
task::block_on(async move {
if !self.is_connected().await {
return Err(Error::NoConnection);
@@ -1099,15 +1104,7 @@ impl Imap {
});
info!(context, "sentbox folder is {:?}", sentbox_folder);
let mut delimiter = ".";
if let Some(folder) = folders.first() {
if let Some(d) = folder.delimiter() {
if !d.is_empty() {
delimiter = d;
}
}
}
info!(context, "Using \"{}\" as folder-delimiter.", delimiter);
let delimiter = self.config.read().await.imap_delimiter;
let fallback_folder = format!("INBOX{}DeltaChat", delimiter);
let mut mvbox_folder = folders
@@ -1171,11 +1168,9 @@ impl Imap {
Some(sentbox_folder.name()),
)?;
}
context.sql.set_raw_config_int(
context,
"folders_configured",
DC_FOLDERS_CONFIGURED_VERSION,
)?;
context
.sql
.set_raw_config_int(context, "folders_configured", 3)?;
}
info!(context, "FINISHED configuring IMAP-folders.");
Ok(())
@@ -1210,13 +1205,13 @@ impl Imap {
return;
}
if let Err(err) = self.setup_handle_if_needed(context).await {
error!(context, "could not setup imap connection: {}", err);
error!(context, "could not setup imap connection: {:?}", err);
return;
}
if let Err(err) = self.select_folder(context, Some(&folder)).await {
error!(
context,
"Could not select {} for expunging: {}", folder, err
"Could not select {} for expunging: {:?}", folder, err
);
return;
}
@@ -1236,21 +1231,9 @@ impl Imap {
emit_event!(context, Event::ImapFolderEmptied(folder.to_string()));
}
Err(err) => {
error!(context, "expunge failed {}: {}", folder, err);
error!(context, "expunge failed {}: {:?}", folder, err);
}
}
if let Err(err) = crate::sql::execute(
context,
&context.sql,
"UPDATE msgs SET server_folder='',server_uid=0 WHERE server_folder=?",
params![folder],
) {
warn!(
context,
"Failed to reset server_uid and server_folder for deleted messages: {}", err
);
}
});
}
}
@@ -1301,52 +1284,17 @@ fn precheck_imf(context: &Context, rfc724_mid: &str, server_folder: &str, server
message::rfc724_mid_exists(context, &rfc724_mid)
{
if old_server_folder.is_empty() && old_server_uid == 0 {
info!(
info!(context, "[move] detected bcc-self {}", rfc724_mid,);
context.do_heuristics_moves(server_folder.as_ref(), msg_id);
job_add(
context,
"[move] detected bcc-self {} as {}/{}", rfc724_mid, server_folder, server_uid
Action::MarkseenMsgOnImap,
msg_id.to_u32() as i32,
Params::new(),
0,
);
let delete_server_after = context.get_config_delete_server_after();
if delete_server_after != Some(0) {
context.do_heuristics_moves(server_folder.as_ref(), msg_id);
job_add(
context,
Action::MarkseenMsgOnImap,
msg_id.to_u32() as i32,
Params::new(),
0,
);
}
} else if old_server_folder != server_folder {
info!(
context,
"[move] detected message {} moved by other device from {}/{} to {}/{}",
rfc724_mid,
old_server_folder,
old_server_uid,
server_folder,
server_uid
);
} else if old_server_uid == 0 {
info!(
context,
"[move] detected message {} moved by us from {}/{} to {}/{}",
rfc724_mid,
old_server_folder,
old_server_uid,
server_folder,
server_uid
);
} else if old_server_uid != server_uid {
warn!(
context,
"UID for message {} in folder {} changed from {} to {}",
rfc724_mid,
server_folder,
old_server_uid,
server_uid
);
info!(context, "[move] detected moved message {}", rfc724_mid,);
}
if old_server_folder != server_folder || old_server_uid != server_uid {
@@ -1358,6 +1306,17 @@ fn precheck_imf(context: &Context, rfc724_mid: &str, server_folder: &str, server
}
}
fn parse_message_id(value: &str) -> crate::error::Result<String> {
let addrs = mailparse::addrparse(value)
.map_err(|err| format_err!("failed to parse message id {:?}", err))?;
if let Some(info) = addrs.extract_single_info() {
return Ok(info.addr);
}
bail!("could not parse message_id: {}", value);
}
fn get_fetch_headers(prefetch_msg: &Fetch) -> Result<Vec<mailparse::MailHeader>> {
let header_bytes = match prefetch_msg.header() {
Some(header_bytes) => header_bytes,
@@ -1368,27 +1327,30 @@ fn get_fetch_headers(prefetch_msg: &Fetch) -> Result<Vec<mailparse::MailHeader>>
}
fn prefetch_get_message_id(headers: &[mailparse::MailHeader]) -> Result<String> {
if let Some(message_id) = headers.get_header_value(HeaderDef::MessageId) {
Ok(crate::mimeparser::parse_message_id(&message_id)?)
if let Some(message_id) = headers.get_header_value(HeaderDef::MessageId)? {
Ok(parse_message_id(&message_id)?)
} else {
Err(Error::Other("prefetch: No message ID found".to_string()))
}
}
fn prefetch_is_reply_to_chat_message(context: &Context, headers: &[mailparse::MailHeader]) -> bool {
if let Some(value) = headers.get_header_value(HeaderDef::InReplyTo) {
fn prefetch_is_reply_to_chat_message(
context: &Context,
headers: &[mailparse::MailHeader],
) -> Result<bool> {
if let Some(value) = headers.get_header_value(HeaderDef::InReplyTo)? {
if is_msgrmsg_rfc724_mid_in_list(context, &value) {
return true;
return Ok(true);
}
}
if let Some(value) = headers.get_header_value(HeaderDef::References) {
if let Some(value) = headers.get_header_value(HeaderDef::References)? {
if is_msgrmsg_rfc724_mid_in_list(context, &value) {
return true;
return Ok(true);
}
}
false
Ok(false)
}
fn prefetch_should_download(
@@ -1396,16 +1358,16 @@ fn prefetch_should_download(
headers: &[mailparse::MailHeader],
show_emails: ShowEmails,
) -> Result<bool> {
let is_chat_message = headers.get_header_value(HeaderDef::ChatVersion).is_some();
let is_reply_to_chat_message = prefetch_is_reply_to_chat_message(context, &headers);
let is_chat_message = headers.get_header_value(HeaderDef::ChatVersion)?.is_some();
let is_reply_to_chat_message = prefetch_is_reply_to_chat_message(context, &headers)?;
// Autocrypt Setup Message should be shown even if it is from non-chat client.
let is_autocrypt_setup_message = headers
.get_header_value(HeaderDef::AutocryptSetupMessage)
.get_header_value(HeaderDef::AutocryptSetupMessage)?
.is_some();
let from_field = headers
.get_header_value(HeaderDef::From_)
.get_header_value(HeaderDef::From_)?
.unwrap_or_default();
let (_contact_id, blocked_contact, origin) = from_field_to_contact_id(context, &from_field)?;
@@ -1422,3 +1384,20 @@ fn prefetch_should_download(
let show = show && !blocked_contact;
Ok(show)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_message_id() {
assert_eq!(
parse_message_id("Mr.PRUe8HJBoaO.3whNvLCMFU0@testrun.org").unwrap(),
"Mr.PRUe8HJBoaO.3whNvLCMFU0@testrun.org"
);
assert_eq!(
parse_message_id("<Mr.PRUe8HJBoaO.3whNvLCMFU0@testrun.org>").unwrap(),
"Mr.PRUe8HJBoaO.3whNvLCMFU0@testrun.org"
);
}
}

View File

@@ -756,6 +756,7 @@ mod tests {
assert!(msg.contains("-----BEGIN PGP MESSAGE-----\r\n"));
assert!(msg.contains("Passphrase-Format: numeric9x4\r\n"));
assert!(msg.contains("Passphrase-Begin: he\n"));
assert!(msg.contains("==\n"));
assert!(msg.contains("-----END PGP MESSAGE-----\n"));
}

View File

@@ -80,14 +80,10 @@ pub enum Action {
// Jobs in the INBOX-thread, range from DC_IMAP_THREAD..DC_IMAP_THREAD+999
Housekeeping = 105, // low priority ...
EmptyServer = 107,
OldDeleteMsgOnImap = 110,
DeleteMsgOnImap = 110,
MarkseenMdnOnImap = 120,
MarkseenMsgOnImap = 130,
// Moving message is prioritized lower than deletion so we don't
// bother moving message if it is already scheduled for deletion.
MoveMsg = 200,
DeleteMsgOnImap = 210,
ConfigureImap = 900,
ImexImap = 910, // ... high priority
@@ -112,9 +108,9 @@ impl From<Action> for Thread {
Unknown => Thread::Unknown,
Housekeeping => Thread::Imap,
OldDeleteMsgOnImap => Thread::Imap,
DeleteMsgOnImap => Thread::Imap,
EmptyServer => Thread::Imap,
MarkseenMdnOnImap => Thread::Imap,
MarkseenMsgOnImap => Thread::Imap,
MoveMsg => Thread::Imap,
ConfigureImap => Thread::Imap,
@@ -417,12 +413,18 @@ impl Job {
if let Some(dest_folder) = dest_folder {
let server_folder = msg.server_folder.as_ref().unwrap();
let mut dest_uid = 0;
match imap_inbox.mv(context, server_folder, msg.server_uid, &dest_folder) {
match imap_inbox.mv(
context,
server_folder,
msg.server_uid,
&dest_folder,
&mut dest_uid,
) {
ImapActionResult::RetryLater => Status::RetryLater,
ImapActionResult::Success => {
// XXX Rust-Imap provides no target uid on mv, so just set it to 0
message::update_server_uid(context, &msg.rfc724_mid, &dest_folder, 0);
message::update_server_uid(context, &msg.rfc724_mid, &dest_folder, dest_uid);
Status::Finished(Ok(()))
}
ImapActionResult::Failed => {
@@ -435,29 +437,14 @@ impl Job {
}
}
/// Deletes a message on the server.
///
/// foreign_id is a MsgId pointing to a message in the trash chat
/// or a hidden message.
///
/// This job removes the database record. If there are no more
/// records pointing to the same message on the server, the job
/// also removes the message on the server.
#[allow(non_snake_case)]
fn DeleteMsgOnImap(&mut self, context: &Context) -> Status {
let imap_inbox = &context.inbox_thread.read().unwrap().imap;
let msg = job_try!(Message::load_from_db(context, MsgId::new(self.foreign_id)));
let mut msg = job_try!(Message::load_from_db(context, MsgId::new(self.foreign_id)));
if !msg.rfc724_mid.is_empty() {
let cnt = message::rfc724_mid_cnt(context, &msg.rfc724_mid);
info!(
context,
"Running delete job for message {} which has {} entries in the database",
&msg.rfc724_mid,
cnt
);
if cnt > 1 {
if message::rfc724_mid_cnt(context, &msg.rfc724_mid) > 1 {
info!(
context,
"The message is deleted from the server when all parts are deleted.",
@@ -467,47 +454,13 @@ impl Job {
we delete the message from the server */
let mid = msg.rfc724_mid;
let server_folder = msg.server_folder.as_ref().unwrap();
let res = if msg.server_uid == 0 {
// Message is already deleted on IMAP server.
ImapActionResult::AlreadyDone
} else {
imap_inbox.delete_msg(context, &mid, server_folder, msg.server_uid)
};
match res {
ImapActionResult::AlreadyDone | ImapActionResult::Success => {}
ImapActionResult::RetryLater | ImapActionResult::Failed => {
// If job has failed, for example due to some
// IMAP bug, we postpone it instead of failing
// immediately. This will prevent adding it
// immediately again if user has enabled
// automatic message deletion. Without this,
// we might waste a lot of traffic constantly
// retrying message deletion.
return Status::RetryLater;
}
let res = imap_inbox.delete_msg(context, &mid, server_folder, &mut msg.server_uid);
if res == ImapActionResult::RetryLater {
// XXX RetryLater is converted to RetryNow here
return Status::RetryNow;
}
}
if msg.chat_id.is_trash() || msg.hidden {
// Messages are stored in trash chat only to keep
// their server UID and Message-ID. Once message is
// deleted from the server, database record can be
// removed as well.
//
// Hidden messages are similar to trashed, but are
// related to some chat. We also delete their
// database records.
job_try!(msg.id.delete_from_db(context))
} else {
// Remove server UID from the database record.
//
// We have either just removed the message from the
// server, in which case UID is not valid anymore, or
// we have more refernces to the same server UID, so
// we remove UID to reduce the number of messages
// pointing to the corresponding UID. Once the counter
// reaches zero, we will remove the message.
job_try!(msg.id.unlink(context));
}
Message::delete_from_db(context, msg.id);
Status::Finished(Ok(()))
} else {
/* eg. device messages have no Message-ID */
@@ -559,6 +512,43 @@ impl Job {
}
}
}
#[allow(non_snake_case)]
fn MarkseenMdnOnImap(&mut self, context: &Context) -> Status {
let folder = self
.param
.get(Param::ServerFolder)
.unwrap_or_default()
.to_string();
let uid = self.param.get_int(Param::ServerUid).unwrap_or_default() as u32;
let imap_inbox = &context.inbox_thread.read().unwrap().imap;
if imap_inbox.set_seen(context, &folder, uid) == ImapActionResult::RetryLater {
return Status::RetryLater;
}
if self.param.get_bool(Param::AlsoMove).unwrap_or_default() {
if let Err(err) = imap_inbox.ensure_configured_folders(context, true) {
warn!(context, "configuring folders failed: {:?}", err);
return Status::RetryLater;
}
let dest_folder = context
.sql
.get_raw_config(context, "configured_mvbox_folder");
if let Some(dest_folder) = dest_folder {
let mut dest_uid = 0;
if ImapActionResult::RetryLater
== imap_inbox.mv(context, &folder, uid, &dest_folder, &mut dest_uid)
{
Status::RetryLater
} else {
Status::Finished(Ok(()))
}
} else {
Status::Finished(Err(format_err!("MVBOX is not configured")))
}
} else {
Status::Finished(Ok(()))
}
}
}
/* delete all pending jobs with the given action */
@@ -831,11 +821,7 @@ pub fn job_send_msg(context: &Context, msg_id: MsgId) -> Result<()> {
.get_config(Config::ConfiguredAddr)
.unwrap_or_default();
let lowercase_from = from.to_lowercase();
// Send BCC to self if it is enabled and we are not going to
// delete it immediately.
if context.get_config_bool(Config::BccSelf)
&& context.get_config_delete_server_after() != Some(0)
&& !recipients
.iter()
.any(|x| x.to_lowercase() == lowercase_from)
@@ -911,41 +897,6 @@ pub fn job_send_msg(context: &Context, msg_id: MsgId) -> Result<()> {
Ok(())
}
fn add_imap_deletion_jobs(context: &Context) -> sql::Result<()> {
if let Some(delete_server_after) = context.get_config_delete_server_after() {
let threshold_timestamp = time() - delete_server_after;
// Select all expired messages which don't have a
// corresponding message deletion job yet.
let msg_ids = context.sql.query_map(
"SELECT id FROM msgs \
WHERE timestamp < ? \
AND server_uid != 0 \
AND NOT EXISTS (SELECT 1 FROM jobs WHERE foreign_id = msgs.id \
AND action = ?)",
params![threshold_timestamp, Action::DeleteMsgOnImap],
|row| row.get::<_, MsgId>(0),
|ids| {
ids.collect::<std::result::Result<Vec<_>, _>>()
.map_err(Into::into)
},
)?;
// Schedule IMAP deletion for expired messages.
for msg_id in msg_ids {
job_add(
context,
Action::DeleteMsgOnImap,
msg_id.to_u32() as i32,
Params::new(),
0,
)
}
}
Ok(())
}
pub fn perform_inbox_jobs(context: &Context) {
info!(context, "dc_perform_inbox_jobs starting.",);
@@ -953,9 +904,6 @@ pub fn perform_inbox_jobs(context: &Context) {
*context.probe_imap_network.write().unwrap() = false;
*context.perform_inbox_jobs_needed.write().unwrap() = false;
if let Err(err) = add_imap_deletion_jobs(context) {
warn!(context, "Can't add IMAP message deletion jobs: {}", err);
}
job_perform(context, Thread::Imap, probe_imap_network);
info!(context, "dc_perform_inbox_jobs ended.",);
}
@@ -1097,9 +1045,9 @@ fn perform_job_action(context: &Context, mut job: &mut Job, thread: Thread, trie
Action::Unknown => Status::Finished(Err(format_err!("Unknown job id found"))),
Action::SendMsgToSmtp => job.SendMsgToSmtp(context),
Action::EmptyServer => job.EmptyServer(context),
Action::OldDeleteMsgOnImap => job.DeleteMsgOnImap(context),
Action::DeleteMsgOnImap => job.DeleteMsgOnImap(context),
Action::MarkseenMsgOnImap => job.MarkseenMsgOnImap(context),
Action::MarkseenMdnOnImap => job.MarkseenMdnOnImap(context),
Action::MoveMsg => job.MoveMsg(context),
Action::SendMdn => job.SendMdn(context),
Action::ConfigureImap => JobConfigureImap(context),

View File

@@ -36,7 +36,6 @@ pub mod constants;
pub mod contact;
pub mod context;
mod e2ee;
pub mod export_chat;
mod imap;
pub mod imex;
#[macro_use]

View File

@@ -4,7 +4,6 @@ use std::path::{Path, PathBuf};
use deltachat_derive::{FromSql, ToSql};
use failure::Fail;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use crate::chat::{self, Chat, ChatId};
@@ -22,10 +21,6 @@ use crate::pgp::*;
use crate::sql;
use crate::stock::StockMessage;
lazy_static! {
static ref UNWRAP_RE: regex::Regex = regex::Regex::new(r"\s+").unwrap();
}
// In practice, the user additionally cuts the string themselves
// pixel-accurate.
const SUMMARY_CHARACTERS: usize = 160;
@@ -85,55 +80,6 @@ impl MsgId {
self.0 == DC_MSG_ID_DAYMARKER
}
/// Put message into trash chat and delete message text.
///
/// It means the message is deleted locally, but not on the server
/// yet.
pub fn trash(self, context: &Context) -> crate::sql::Result<()> {
let chat_id = ChatId::new(DC_CHAT_ID_TRASH);
sql::execute(
context,
&context.sql,
"UPDATE msgs SET chat_id=?, txt='', txt_raw='' WHERE id=?",
params![chat_id, self],
)
}
/// Deletes a message and corresponding MDNs from the database.
pub fn delete_from_db(self, context: &Context) -> crate::sql::Result<()> {
// We don't use transactions yet, so remove MDNs first to make
// sure they are not left while the message is deleted.
sql::execute(
context,
&context.sql,
"DELETE FROM msgs_mdns WHERE msg_id=?;",
params![self],
)?;
sql::execute(
context,
&context.sql,
"DELETE FROM msgs WHERE id=?;",
params![self],
)?;
Ok(())
}
/// Removes IMAP server UID and folder from the database record.
///
/// It is used to avoid trying to remove the message from the
/// server multiple times when there are multiple message records
/// pointing to the same server UID.
pub(crate) fn unlink(self, context: &Context) -> sql::Result<()> {
sql::execute(
context,
&context.sql,
"UPDATE msgs \
SET server_folder='', server_uid=0 \
WHERE id=?",
params![self],
)
}
/// Bad evil escape hatch.
///
/// Avoid using this, eventually types should be cleaned up enough
@@ -354,6 +300,25 @@ impl Message {
.map_err(Into::into)
}
pub fn delete_from_db(context: &Context, msg_id: MsgId) {
if let Ok(msg) = Message::load_from_db(context, msg_id) {
sql::execute(
context,
&context.sql,
"DELETE FROM msgs WHERE id=?;",
params![msg.id],
)
.ok();
sql::execute(
context,
&context.sql,
"DELETE FROM msgs_mdns WHERE msg_id=?;",
params![msg.id],
)
.ok();
}
}
pub fn get_filemime(&self) -> Option<String> {
if let Some(m) = self.param.get(Param::MimeType) {
return Some(m.to_string());
@@ -473,7 +438,7 @@ impl Message {
pub fn get_text(&self) -> Option<String> {
self.text
.as_ref()
.map(|text| dc_truncate(text, 30000).to_string())
.map(|text| dc_truncate(text, 30000, false).to_string())
}
pub fn get_filename(&self) -> Option<String> {
@@ -844,7 +809,7 @@ pub fn get_msg_info(context: &Context, msg_id: MsgId) -> String {
return ret;
}
let rawtxt = rawtxt.unwrap_or_default();
let rawtxt = dc_truncate(rawtxt.trim(), 100_000);
let rawtxt = dc_truncate(rawtxt.trim(), 100_000, false);
let fts = dc_timestamp_to_str(msg.get_timestamp());
ret += &format!("Sent: {}", fts);
@@ -981,15 +946,13 @@ pub fn get_mime_headers(context: &Context, msg_id: MsgId) -> Option<String> {
}
pub fn delete_msgs(context: &Context, msg_ids: &[MsgId]) {
for msg_id in msg_ids {
for msg_id in msg_ids.iter() {
if let Ok(msg) = Message::load_from_db(context, *msg_id) {
if msg.location_id > 0 {
delete_poi_location(context, msg.location_id);
}
}
if let Err(err) = msg_id.trash(context) {
error!(context, "Unable to trash message {}: {}", msg_id, err);
}
update_msg_chat_id(context, *msg_id, ChatId::new(DC_CHAT_ID_TRASH));
job_add(
context,
Action::DeleteMsgOnImap,
@@ -1009,6 +972,16 @@ pub fn delete_msgs(context: &Context, msg_ids: &[MsgId]) {
};
}
fn update_msg_chat_id(context: &Context, msg_id: MsgId, chat_id: ChatId) -> bool {
sql::execute(
context,
&context.sql,
"UPDATE msgs SET chat_id=? WHERE id=?;",
params![chat_id, msg_id],
)
.is_ok()
}
fn delete_poi_location(context: &Context, location_id: u32) -> bool {
sql::execute(
context,
@@ -1168,20 +1141,18 @@ pub fn get_summarytext_by_raw(
return prefix;
}
let summary = if let Some(text) = text {
if let Some(text) = text {
if text.as_ref().is_empty() {
prefix
} else if prefix.is_empty() {
dc_truncate(text.as_ref(), approx_characters).to_string()
dc_truncate(text.as_ref(), approx_characters, true).to_string()
} else {
let tmp = format!("{} {}", prefix, text.as_ref());
dc_truncate(&tmp, approx_characters).to_string()
dc_truncate(&tmp, approx_characters, true).to_string()
}
} else {
prefix
};
UNWRAP_RE.replace_all(&summary, " ").to_string()
}
}
// as we do not cut inside words, this results in about 32-42 characters.
@@ -1369,55 +1340,10 @@ pub fn get_deaddrop_msg_cnt(context: &Context) -> usize {
}
}
pub fn estimate_deletion_cnt(
context: &Context,
from_server: bool,
seconds: i64,
) -> Result<usize, Error> {
let self_chat_id = chat::lookup_by_contact_id(context, DC_CONTACT_ID_SELF)
.unwrap_or_default()
.0;
let threshold_timestamp = time() - seconds;
let cnt: isize = if from_server {
context.sql.query_row(
"SELECT COUNT(*)
FROM msgs m
WHERE m.id > ?
AND timestamp < ?
AND chat_id != ?
AND server_uid != 0;",
params![DC_MSG_ID_LAST_SPECIAL, threshold_timestamp, self_chat_id],
|row| row.get(0),
)?
} else {
context.sql.query_row(
"SELECT COUNT(*)
FROM msgs m
WHERE m.id > ?
AND timestamp < ?
AND chat_id != ?
AND chat_id != ? AND hidden = 0;",
params![
DC_MSG_ID_LAST_SPECIAL,
threshold_timestamp,
self_chat_id,
ChatId::new(DC_CHAT_ID_TRASH)
],
|row| row.get(0),
)?
};
Ok(cnt as usize)
}
/// Counts number of database records pointing to specified
/// Message-ID.
///
/// Unlinked messages are excluded.
pub fn rfc724_mid_cnt(context: &Context, rfc724_mid: &str) -> i32 {
// check the number of messages with the same rfc724_mid
match context.sql.query_row(
"SELECT COUNT(*) FROM msgs WHERE rfc724_mid=? AND NOT server_uid = 0",
"SELECT COUNT(*) FROM msgs WHERE rfc724_mid=?;",
&[rfc724_mid],
|row| row.get(0),
) {
@@ -1458,8 +1384,7 @@ pub fn update_server_uid(
server_uid: u32,
) {
match context.sql.execute(
"UPDATE msgs SET server_folder=?, server_uid=? \
WHERE rfc724_mid=?",
"UPDATE msgs SET server_folder=?, server_uid=? WHERE rfc724_mid=?;",
params![server_folder.as_ref(), server_uid, rfc724_mid],
) {
Ok(_) => {}

View File

@@ -368,7 +368,7 @@ impl<'a, 'b> MimeFactory<'a, 'b> {
self.from_addr.clone(),
);
let mut to = Vec::new();
let mut to = Vec::with_capacity(self.recipients.len());
for (name, addr) in self.recipients.iter() {
if name.is_empty() {
to.push(Address::new_mailbox(addr.clone()));
@@ -380,10 +380,6 @@ impl<'a, 'b> MimeFactory<'a, 'b> {
}
}
if to.is_empty() {
to.push(from.clone());
}
if !self.references.is_empty() {
unprotected_headers.push(Header::new("References".into(), self.references.clone()));
}

View File

@@ -7,6 +7,7 @@ use mailparse::{DispositionType, MailAddr, MailHeaderMap};
use crate::aheader::Aheader;
use crate::bail;
use crate::blob::BlobObject;
use crate::config::Config;
use crate::constants::Viewtype;
use crate::contact::*;
use crate::context::Context;
@@ -16,6 +17,7 @@ use crate::e2ee;
use crate::error::Result;
use crate::events::Event;
use crate::headerdef::{HeaderDef, HeaderDefMap};
use crate::job::{job_add, Action};
use crate::location;
use crate::message;
use crate::param::*;
@@ -83,7 +85,7 @@ impl MimeMessage {
let message_time = mail
.headers
.get_header_value(HeaderDef::Date)
.get_header_value(HeaderDef::Date)?
.and_then(|v| mailparse::dateparse(&v).ok())
.unwrap_or_default();
@@ -109,7 +111,8 @@ impl MimeMessage {
// Handle any gossip headers if the mail was encrypted. See section
// "3.6 Key Gossip" of https://autocrypt.org/autocrypt-spec-1.1.0.pdf
let gossip_headers = decrypted_mail.headers.get_all_values("Autocrypt-Gossip");
let gossip_headers =
decrypted_mail.headers.get_all_values("Autocrypt-Gossip")?;
gossipped_addr =
update_gossip_peerstates(context, message_time, &mail, gossip_headers)?;
@@ -542,16 +545,6 @@ impl MimeMessage {
if let Some(report) = self.process_report(context, mail)? {
self.reports.push(report);
}
// Add MDN part so we can track it, avoid
// downloading the message again and
// delete if automatic message deletion is
// enabled.
let mut part = Part::default();
part.typ = Viewtype::Unknown;
self.parts.push(part);
any_part_added = true;
} else {
/* eg. `report-type=delivery-status`;
maybe we should show them as a little error icon */
@@ -748,18 +741,21 @@ impl MimeMessage {
pub fn get_rfc724_mid(&self) -> Option<String> {
self.get(HeaderDef::MessageId)
.and_then(|msgid| parse_message_id(msgid).ok())
.and_then(|msgid| parse_message_id(msgid))
}
fn merge_headers(headers: &mut HashMap<String, String>, fields: &[mailparse::MailHeader<'_>]) {
for field in fields {
// lowercasing all headers is technically not correct, but makes things work better
let key = field.get_key().to_lowercase();
if !headers.contains_key(&key) || // key already exists, only overwrite known types (protected headers)
if let Ok(key) = field.get_key() {
// lowercasing all headers is technically not correct, but makes things work better
let key = key.to_lowercase();
if !headers.contains_key(&key) || // key already exists, only overwrite known types (protected headers)
is_known(&key) || key.starts_with("chat-")
{
let value = field.get_value();
headers.insert(key.to_string(), value);
{
if let Ok(value) = field.get_value() {
headers.insert(key, value);
}
}
}
}
}
@@ -774,17 +770,23 @@ impl MimeMessage {
let (report_fields, _) = mailparse::parse_headers(&report_body)?;
// must be present
if let Some(_disposition) = report_fields.get_header_value(HeaderDef::Disposition) {
if let Some(_disposition) = report_fields
.get_header_value(HeaderDef::Disposition)
.ok()
.flatten()
{
if let Some(original_message_id) = report_fields
.get_header_value(HeaderDef::OriginalMessageId)
.and_then(|v| parse_message_id(&v).ok())
.ok()
.flatten()
.and_then(|v| parse_message_id(&v))
{
let additional_message_ids = report_fields
.get_header_value(HeaderDef::AdditionalMessageIds)
.ok()
.flatten()
.map_or_else(Vec::new, |v| {
v.split(' ')
.filter_map(|s| parse_message_id(s).ok())
.collect()
v.split(' ').filter_map(parse_message_id).collect()
});
return Ok(Some(Report {
@@ -796,18 +798,26 @@ impl MimeMessage {
warn!(
context,
"ignoring unknown disposition-notification, Message-Id: {:?}",
report_fields.get_header_value(HeaderDef::MessageId)
report_fields.get_header_value(HeaderDef::MessageId).ok()
);
Ok(None)
}
/// Handle reports (only MDNs for now)
pub fn handle_reports(&self, context: &Context, from_id: u32, sent_timestamp: i64) {
pub fn handle_reports(
&self,
context: &Context,
from_id: u32,
sent_timestamp: i64,
server_folder: impl AsRef<str>,
server_uid: u32,
) {
if self.reports.is_empty() {
return;
}
let mut mdn_recognized = false;
for report in &self.reports {
for original_message_id in
std::iter::once(&report.original_message_id).chain(&report.additional_message_ids)
@@ -816,9 +826,20 @@ impl MimeMessage {
message::mdn_from_ext(context, from_id, original_message_id, sent_timestamp)
{
context.call_cb(Event::MsgRead { chat_id, msg_id });
mdn_recognized = true;
}
}
}
if self.has_chat_version() || mdn_recognized {
let mut param = Params::new();
param.set(Param::ServerFolder, server_folder.as_ref());
param.set_int(Param::ServerUid, server_uid as i32);
if self.has_chat_version() && context.get_config_bool(Config::MvboxMove) {
param.set_int(Param::AlsoMove, 1);
}
job_add(context, Action::MarkseenMdnOnImap, 0, param, 0);
}
}
}
@@ -837,9 +858,14 @@ fn update_gossip_peerstates(
if let Ok(ref header) = gossip_header {
if recipients.is_none() {
recipients = Some(get_recipients(
mail.headers.iter().map(|v| (v.get_key(), v.get_value())),
));
recipients = Some(get_recipients(mail.headers.iter().filter_map(|v| {
let key = v.get_key();
let value = v.get_value();
if key.is_err() || value.is_err() {
return None;
}
Some((v.get_key().unwrap(), v.get_value().unwrap()))
})));
}
if recipients
@@ -883,15 +909,14 @@ pub(crate) struct Report {
additional_message_ids: Vec<String>,
}
pub(crate) fn parse_message_id(value: &str) -> crate::error::Result<String> {
let ids = mailparse::msgidparse(value)
.map_err(|err| format_err!("failed to parse message id {:?}", err))?;
if let Some(id) = ids.first() {
Ok(id.to_string())
} else {
bail!("could not parse message_id: {}", value);
fn parse_message_id(field: &str) -> Option<String> {
if let Ok(addrs) = mailparse::addrparse(field) {
// Assume the message id is a single id in the form of <id>
if let mailparse::MailAddr::Single(mailparse::SingleInfo { ref addr, .. }) = addrs[0] {
return Some(addr.clone());
}
}
None
}
fn is_known(key: &str) -> bool {
@@ -954,12 +979,15 @@ fn get_mime_type(mail: &mailparse::ParsedMail<'_>) -> Result<(Mime, Viewtype)> {
}
fn is_attachment_disposition(mail: &mailparse::ParsedMail<'_>) -> bool {
let ct = mail.get_content_disposition();
ct.disposition == DispositionType::Attachment
&& ct
.params
.iter()
.any(|(key, _value)| key.starts_with("filename"))
if let Ok(ct) = mail.get_content_disposition() {
return ct.disposition == DispositionType::Attachment
&& ct
.params
.iter()
.any(|(key, _value)| key.starts_with("filename"));
}
false
}
/// Tries to get attachment filename.
@@ -974,7 +1002,7 @@ fn get_attachment_filename(mail: &mailparse::ParsedMail) -> Result<Option<String
// or `Content-Disposition: ... filename*0*=... filename*1*=... filename*2*=...`
// or `Content-Disposition: ... filename=...`
let ct = mail.get_content_disposition();
let ct = mail.get_content_disposition()?;
let desired_filename: Option<String> = ct
.params
@@ -1333,7 +1361,7 @@ Disposition: manual-action/MDN-sent-automatically; displayed\n\
Some("Chat: Message opened".to_string())
);
assert_eq!(message.parts.len(), 1);
assert_eq!(message.parts.len(), 0);
assert_eq!(message.reports.len(), 1);
}
@@ -1411,7 +1439,7 @@ Disposition: manual-action/MDN-sent-automatically; displayed\n\
Some("Chat: Message opened".to_string())
);
assert_eq!(message.parts.len(), 2);
assert_eq!(message.parts.len(), 0);
assert_eq!(message.reports.len(), 2);
}
@@ -1456,7 +1484,7 @@ Additional-Message-IDs: <foo@example.com> <foo@example.net>\n\
Some("Chat: Message opened".to_string())
);
assert_eq!(message.parts.len(), 1);
assert_eq!(message.parts.len(), 0);
assert_eq!(message.reports.len(), 1);
assert_eq!(message.reports[0].original_message_id, "foo@example.org");
assert_eq!(

View File

@@ -88,6 +88,12 @@ pub enum Param {
/// For Jobs
SetLongitude = b'n',
/// For Jobs
ServerFolder = b'Z',
/// For Jobs
ServerUid = b'z',
/// For Jobs
AlsoMove = b'M',

View File

@@ -394,6 +394,7 @@ mod tests {
}
#[test]
#[ignore] // is too expensive
fn test_create_keypair() {
let keypair0 = create_keypair(
EmailAddress::new("foo@bar.de").unwrap(),

View File

@@ -22,9 +22,9 @@ lazy_static::lazy_static! {
// aol.md: aol.com
static ref P_AOL: Provider = Provider {
status: Status::PREPARATION,
before_login_hint: "To log in to AOL with Delta Chat, you need to set up an app password in the AOL web interface.",
after_login_hint: "",
status: Status::BROKEN,
before_login_hint: "You can't use Delta Chat to login to AOL.",
after_login_hint: "Seems like you logged in anyway, congratulations! 🎉 Feel free to tell us at https://github.com/deltachat/provider-db/issues that AOL works again.",
overview_page: "https://providers.delta.chat/aol",
server: vec![
],

View File

@@ -770,38 +770,6 @@ pub(crate) fn handle_securejoin_handshake(
}
}
/// observe_securejoin_on_other_device() must be called when a self-sent securejoin message is seen.
/// currently, the message is only ignored, in the future,
/// we may mark peers as verified accross devices:
///
/// in a multi-device-setup, there may be other devices that "see" the handshake messages.
/// if the seen messages seen are self-sent messages encrypted+signed correctly with our key,
/// we can make some conclusions of it:
///
/// - if we see the self-sent-message vg-member-added/vc-contact-confirm,
/// we know that we're an inviter-observer.
/// the inviting device has marked a peer as verified on vg-request-with-auth/vc-request-with-auth
/// before sending vg-member-added/vc-contact-confirm - so, if we observe vg-member-added/vc-contact-confirm,
/// we can mark the peer as verified as well.
///
/// - if we see the self-sent-message vg-member-added-received
/// we know that we're an joiner-observer.
/// the joining device has marked the peer as verified on vg-member-added/vc-contact-confirm
/// before sending vg-member-added-received - so, if we observe vg-member-added-received,
/// we can mark the peer as verified as well.
///
/// to make this work, (a) some messages must not be deleted,
/// (b) we need a vc-contact-confirm-received message if bcc_self is set,
/// (c) we should make sure, we do not only rely on the unencrypted To:-header for identifying the peer
/// (in handle_securejoin_handshake() we have the oob information for that)
pub(crate) fn observe_securejoin_on_other_device(
_context: &Context,
_mime_message: &MimeMessage,
_contact_id: u32,
) -> Result<HandshakeMessage, HandshakeError> {
Ok(HandshakeMessage::Ignore)
}
fn secure_connection_established(context: &Context, contact_chat_id: ChatId) {
let contact_id: u32 = chat_id_2_contact_id(context, contact_chat_id);
let contact = Contact::get_by_id(context, contact_id);

View File

@@ -8,7 +8,7 @@ use rusqlite::{Connection, OpenFlags, Statement, NO_PARAMS};
use thread_local_object::ThreadLocal;
use crate::chat::{update_device_icon, update_saved_messages_icon};
use crate::constants::{ShowEmails, DC_CHAT_ID_TRASH};
use crate::constants::ShowEmails;
use crate::context::Context;
use crate::dc_tools::*;
use crate::param::*;
@@ -1053,18 +1053,6 @@ pub fn get_rowid2_with_conn(
}
}
/// Removes from the database locally deleted messages that also don't
/// have a server UID.
fn prune_tombstones(context: &Context) -> Result<()> {
context.sql.execute(
"DELETE FROM msgs \
WHERE (chat_id = ? OR hidden) \
AND server_uid = 0",
params![DC_CHAT_ID_TRASH],
)?;
Ok(())
}
pub fn housekeeping(context: &Context) {
let mut files_in_use = HashSet::new();
let mut unreferenced_count = 0;
@@ -1177,13 +1165,6 @@ pub fn housekeeping(context: &Context) {
}
}
if let Err(err) = prune_tombstones(context) {
warn!(
context,
"Houskeeping: Cannot prune message tombstones: {}", err
);
}
info!(context, "Housekeeping done.",);
}

View File

@@ -1 +1 @@
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

View File

@@ -1 +1 @@
lFgEXlh13RYJKwYBBAHaRw8BAQdAzfVIAleCXMJrq8VeLlEVof6ITCviMktKjmcBKAu4m5AAAQDMpCY4sD5/DUR0jRjGC5WstwShz1q+5Vofo5mY9+XRXRA3tBlBbGljZSA8YWxpY2VAZXhhbXBsZS5vcmc+iJAEExYIADgWIQQub6LLI7Uy1yhjS1hksI9hqe2UQwUCXlh13QIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRBksI9hqe2UQxN6AP4uDAsgzE7I1qg2aEMF/wPxqEztv1dMCj4YyScv/JtqTAD5AYzpxjrcdkmaULyRk2vYfNOEWOog60biPAP/LRBFwAOcXQReWHXdEgorBgEEAZdVAQUBAQdABu3I1stkhQFPCp5bZbm1Vuu6xYsn6dNSa0Xul6stth0DAQgHAAD/X9y9I/JFBeArkgR3U363cWXXxMCWftS+BDwM9zE4PrgQb4h4BBgWCAAgFiEELm+iyyO1MtcoY0tYZLCPYantlEMFAl5Ydd0CGwwACgkQZLCPYantlEMujwEA5sTwaewZXArM2oK8d5aAmyqGNLcLqC9KVXe0Sb1eYXoBANe5wjJV+gHCjIyHaHpxKf8BOflAlvfmmCj6K+neOwwC
xcLYBF425W8BCADLIbltPzG1vk/V2ov2+eBeJJJnRu1kJHdo6e3oNB+HTIxVde5+7Uq8tTEDZB1O7m9NBUFrXr7UYQsA/86G2jmsyWKTzIu1O/t5kdcNDqsNcTVZAhBu2ixYsYVc3ws6kJONjpXLtD2u3P7vEXU3INiOb2JrBQDT8/ubEm1xas/UirYnP5DMaH068IHRdVEYs9ULFaD5scw1m/94buXYZ1CRt/2hT8iRrtBi6ki8kArnhsZC2Xr0+jRQNMUnG5k7Bwi6saCqVmd7IlqSM6MbfYank30Gi/UyDmyIrOk7daTg6WIqgiVOTHav65EK/aUvvjlr+awM+C+u35rQytzyTitZABEBAAEAB/oDQFnwdrd7+jza5nGhFWTS/PDe+FKqbK8AneXx9ouepcoFQCr+Gxw8IwZS0JJrhgOADxp59n1FdvwvGukaXXnY2yxZw0dlMj2XN49ipR51y58X+qF6tMFK9iR1VRif6lqCRIr/RLZMCzuFZhkjNcJhnUTNA7p8qgYX+FaKHzSOaVat/v0kIUHUcZDkREWPUESYDmc1Nv6FXhB0WBiTsBglF+fq5Rm7UWPSmA59Cr7BrW8DctbzTh0+6bkzum2xdOcZ59nuTZa+IKcReI1+kVne5JPNFNJ2tP2f9GSSlL7u+NBtx3zRxZgAotXcJK9cVNIWtegqf+2hoLvm7m2CkWKRBADglpC7TpjV+8wJH+KuyGQ7jepqzf5EHwMrK2i6lPnnmoi0nkKvkklvtdcC7FoFGtLCDJ7vwlUdeN+itDxPlP8bbbUabcy0lLuzyGOVt5NwYXgIuPicpdt2ZTJgvChd9oWi1DG8pVpm+EMJZPyYVEpvDGl6q95oktrytbqjASZbBQQA54roJnwBcptLMTrttDrglULX7ciSKY5HXN1c0rqZn1dTKB1nPYB26hNbu6lZ8ixSOyZm3KwpeDUNW7A3hyzXOfoGFPaddH6WMSFFsGGC/orRVxnuPZLr3UJ3uFX7J0JOav90n/6A4YmS7uImRAG4/vTrAbEfmlBl5msHVUaYh0UD/jSX22JLenO1o8pNU04JQl3lQ4mWY6MvgTyCvpchTzDDva+wdOBTUeVUmb/KqYkYBq98tXl1VnGnNpeEymUISSi60RjaXDhbg7a3ELV0yvvWcBN9zreyyINuCU5OmNefPRvPt4Co12KtIxPACByFNTevzPKbrXd1cyhHOxAuqfzLRbDNEzxhbGljZUBleGFtcGxlLmNvbT7CwIkEEAEIADMCGQEFAl425ZQCGwMECwkIBwYVCAkKCwIDFgIBFiEEsBJRVVptIGB7DRLzYuJiDHjRb8EACgkQYuJiDHjRb8HiZQf+PLDxzWchkHAdQFbxxtoXj66aiknofjlRWHDWvUG4nULZ15tjDjnv3z22Meldr8kSV4r1+ejhLFHou9gTzAYk7eAxiybDd8AJOdK+ZgK/Nn7xjdO+HTZLhNdi+R7EektDyf8WDNktEaS8pZc74VKu4984ESi4PoqVxqGHRiSisH4cw4b2pQYxp32BkIdil7sWnqRUEoCpMoKdw2h0N7/lm+rS7/JR9cdjXaVzy1dYTqAVsTL1FTGy4osOKGOyQbkP+Cm6uNq7kC/Bt+fefsb+c2JycmI1uwdvnG7PoFslKv3lRnfkNSmrcIYlJHUl5z0yAgliophr5fqMfzQpO4zMc8fC2AReNuVvAQgAuNjE1i+g4v25UNDPIMgXODU4WztE30074gQs5sZa0DQnDUMsdWc2g1o060YZDojMYJQAtBjlW1Dz8FEE7WsLNohGtRyUWmIgNxE5CpodjpwIZ0MdO4Aji0YM+g+WsOSS8kiHMs+dMFfQJuNKjujGFaMIciSaMMrUmPtzkQ/o8NEJs2Aftw90fpVR+M7Mue3++rcEX09ntbgqkgm8SV6OIrOY2kfILudtybocgYkCTeNVqz5VFXuxrnT4ceyFQ64JkwsZxb+X/pCm4V5Q2TbKRwtdonU8HfAz0nAd5tsNeGmf/dPLOKBCxlNEme399YmzWrT+kJBp7CIH5jlWQKyuLwARAQABAAf/YmpfWp5fLZvjJ8kVDqIZ4r5LNB+5Sp7nbC3G7lPblBDAXgpOyG9ckdDcbguTWa6yChWizkCXFOhkCKZKVlHw1Wb3JoSB5CFsf4U29pMZe41N2BTeoohV5Fg2nojgNWxtZHwDJ6VsTonidGH9l1sN5AU6gPNF+QZ07MKsRCbRYi0yMgX064gwZXRtkm8AECz8ay1wDzoBy14ALe9aDClafVwfxdYUcxDBqtvjLhGeTWX5lMMAQ1Ix8D0Gp4r0Zvtl+oxlTSZFAt9m6sbRBbJf4LJjRQh07aWF2gUOiyIyz7YymYdwsyFnCPn2Aj84uRdqYCekAUfzBeNTBukUQq1DYQQA3BeH38pnr34m0UyD/tCrTvrX60MOJVvFuaTQw+IgY4XmT9UiiiqYMaoLfzxeevdMCQ9EtMdXUTjI27/II3dR5Obg6J0QTybj78IKPbH8Vdlg0etllRjC3bV/M4a5UcXPKG6W5CvB0UJg7eqn/8wUqwiL9x+hZoLy+nU5rCAjzZEEANcBK8Vy9eBxkKmEfH/mChDSKE82ua0xdQuZiTvvGedUYG3ucH4rAlkZaZcZrtJTod1BKhAhDBrjxk/yLCjK3z5JDsacdDGGfaqga3zdPBJubWE7f4mg6uYVs04Uf90YVY7t0LEQAh7i9QYiIqUOJDy3L8y3+bNgNz2r1p8pFd+/A/0YoYE0YDgABbLKmBQFoWjF3Op7P+k6Z4ENK4Me1fkNSAU451QX7ZduI7i3pGTM06bXG2umhTI1lg48ZveMRk1vBezHU+ThnciEkuhYafnq7NRdkEtI20MyFmN7dZF8LQ/joYKsJbeSG5svj8f1ue2eHkiIIlTtDqVUTizDU3ddlzUZwsB2BBgBCAAgBQJeNuWUAhsMFiEEsBJRVVptIGB7DRLzYuJiDHjRb8EACgkQYuJiDHjRb8HrEgf/Xu8eRPPdskwtyd98y64teidBpkHuIjuZKJpNyy2HhdGXQwYbNIzwINg0EJ+u2nkreNF/h2Lu+/saqI8Dai02dpYXjvxJIlCgP2os7sNhVaZSaS4XmmJjkHCfZuIKblZypKDJVc5AceZxrtvUbgG+94+H3zeRWVAA30S5ep6YPvxigvhmQah/sdzY7708/jd9uXcCbkP47PBaXCpuPiYLb3t7z8mOteJb7LOZUmSI1efiLDLTGj7ofkdDfA7E6/nF/1+nq+UIDWqljwiUzeNIJsFlZRa/9/uDEjcQbaDe9/knBs7k9pEDZX5u8SSwSED75L+OvRpFWenp4SSKvd2BUw==

View File

@@ -44,9 +44,9 @@ fn stress_functions(context: &Context) {
// assert!(dc_is_configured(context) != 0, "Missing configured context");
// let setupcode = dc_create_setup_code(context);
// let setupcode_c = CString::new(setupcode.clone()).unwrap();
// let setupcode_c = CString::yolo(setupcode.clone());
// let setupfile = dc_render_setup_file(context, &setupcode).unwrap();
// let setupfile_c = CString::new(setupfile).unwrap();
// let setupfile_c = CString::yolo(setupfile);
// let mut headerline_2: *const libc::c_char = ptr::null();
// let payload = dc_decrypt_setup_file(context, setupcode_c.as_ptr(), setupfile_c.as_ptr());